text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_login(self, event): """Manual password based login"""
# TODO: Refactor to simplify self.log("Auth request for ", event.username, 'client:', event.clientuuid) # TODO: Define the requirements for secure passwords etc. # They're also required in the Enrol module..! if (len(event.username) < 1) or (len(event.passwo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_profile(self, user_account): """Retrieves a user's profile"""
try: # TODO: Load active profile, not just any user_profile = objectmodels['profile'].find_one( {'owner': str(user_account.uuid)}) self.log("Profile: ", user_profile, user_account.uuid, lvl=debug) except Exception as e: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 li...
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): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """Entry point for the script"""
desc = 'Converts between geodetic, modified apex, quasi-dipole and MLT' parser = argparse.ArgumentParser(description=desc, prog='apexpy') parser.add_argument('source', metavar='SOURCE', choices=['geo', 'apex', 'qd', 'mlt'], help='Convert from {geo, apex, qd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getsinIm(alat): """Computes sinIm from modified apex latitude. Parameters ========== alat : array_like Modified apex latitude Returns ======= sinIm : ndarray...
alat = np.float64(alat) return 2*np.sin(np.radians(alat))/np.sqrt(4 - 3*np.cos(np.radians(alat))**2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getcosIm(alat): """Computes cosIm from modified apex latitude. Parameters ========== alat : array_like Modified apex latitude Returns ======= cosIm : ndarray...
alat = np.float64(alat) return np.cos(np.radians(alat))/np.sqrt(4 - 3*np.cos(np.radians(alat))**2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gc2gdlat(gclat): """Converts geocentric latitude to geodetic latitude using WGS84. Parameters ========== gclat : array_like Geocentric latitude Returns =====...
WGS84_e2 = 0.006694379990141317 # WGS84 first eccentricity squared return np.rad2deg(-np.arctan(np.tan(np.deg2rad(gclat))/(WGS84_e2 - 1)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subsol(datetime): """Finds subsolar geocentric latitude and longitude. Parameters ========== datetime : :class:`datetime.datetime` Returns ======= sbsllat : ...
# 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 nlea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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') args.remove('-config') except ValueError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:', mis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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, r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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', 'data': l10n_schemastore[event.client.language][eve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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'] = { 'c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_r...
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] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
internal_backup(schema, uuid, object_filter, export_format, filename, pretty, all_schemata, omit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 p...
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 objectc...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 configurable from modules, navdata is _very_ noisy # but should not ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_ev...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 SSL. Do not use without SSL proxy in production!", lvl=warn) t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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, ...
# 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_ent...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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("/", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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'].object...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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=False, data_type='bool'): try: del_u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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: lo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) > 0: if xdot: l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) if definition in old_config: print("Service definition already inserted") return pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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[actio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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]: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def notify(self, event): """Notify a user"""
self.log('Got a notification event!') self.log(event, pretty=True) self.log(event.__dict__)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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.compo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) component.save() response = { ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 self.log("Config data get request for ", event.data, "from", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 else: do_subscribe = False t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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('Object list for', schema, 'requested from', user....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'] new_data = change['value'] except KeyError as e: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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("Put request with missing arguments!", e, data, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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] if schema not in objectmodels.keys(): s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) subscribed.append(uuid) except KeyError: continue ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: self.subscriptions[uuid].pop(event.client.uuid) if len(se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.append(lang) rv.sort() rv.append('en') l10n_log('Registered languages:', rv,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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[language] = language_lookup[language] except KeyError: l10n_log('Language ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def i18n(msg, event=None, lang='en', domain='backend'): """Gettext function wrapper to return a message in a specified language by domain To use internationaliza...
if event is not None: language = event.client.language else: language = lang domain = Domain(domain) return domain.get(language, msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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( color=choice(colors), adjective=choice(adjectives), kind=choice(kind_list), attribute=choi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(str(x))))) formats = [] hformats = [] for i in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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[lang] = gettext.translation(self._domain, localedir=localedir, languages=[lang], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handler(*names, **kwargs): """Creates an Event Handler This decorator can be applied to methods of classes derived from :class:`circuits.core.components.Base...
def wrapper(f): if names and isinstance(names[0], bool) and not names[0]: f.handler = False return f if len(names) > 0 and inspect.isclass(names[0]) and \ issubclass(names[0], hfosEvent): f.names = (str(names[0].realname()),) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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() line_no = exc_tb.tb_lineno # print('EXCEPTION DATA:', line_no, exc_ty...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) configschemastore[self.name] = self.configschema
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregister(self): """Removes the unique name from the systems unique name list"""
self.names.remove(self.uniquename) super(ConfigurableMeta, self).unregister()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 mongodb is running " "correctly.", lvl=critical) if self.confi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) # pprint(self.config.__dict__) # pprint(self.config._fields) try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reload_configuration(self, event): """Event triggered configuration reload"""
if event.target == self.uniquename: self.log('Reloading configuration') self._read_config()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 keyword in info['keywords'].split(" "): print(keyword) inf...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 item in templates.values(): source = os.path.join('dev/templates', item[0]) filename = os.pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 and type(response) != str: response = response.decode('utf-8') a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) done = False info = None while not done: info = _ask_questionnaire()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_field(key, lookup_type=None, placeholder=None, html_class="div", select_type="strapselect", mapping="uuid"): """Generates a lookup field for form defi...
if lookup_type is None: lookup_type = key if placeholder is None: placeholder = "Select a " + lookup_type result = { 'key': key, 'htmlClass': html_class, 'type': select_type, 'placeholder': placeholder, 'options': { "type": lookup_type,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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): try: item = items[horizontal][vertical] column_items.append(i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'] = [content] tabs.append(tab) result = { 'type'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timed_connectivity_check(self, event): """Tests internet connectivity in regular intervals and updates the nodestate accordingly"""
self.status = self._can_connect() self.log('Timed connectivity check:', self.status, lvl=verbose) if self.status: if not self.old_status: self.log('Connectivity gained') self.fireEvent(backend_nodestate_toggle(STATE_UUID_CONNECTIVITY, on=True, force=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def activityrequest(self, event): """ActivityMonitor event handler for incoming events :param event with incoming ActivityMonitor message """
# self.log("Event: '%s'" % event.__dict__) try: action = event.action data = event.data self.log("Activityrequest: ", action, data) except Exception as e: self.log("Error: '%s' %s" % (e, type(e)), lvl=error)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify(ctx, schema, uuid, object_filter, field, value): """Modify field values of objects"""
database = ctx.obj['db'] model = database.objectmodels[schema] obj = None if uuid: obj = model.find_one({'uuid': uuid}) elif object_filter: obj = model.find_one(literal_eval(object_filter)) else: log('No object uuid or filter specified.', lvl=error) if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def view(ctx, schema, uuid, object_filter): """Show stored objects"""
database = ctx.obj['db'] if schema is None: log('No schema given. Read the help', lvl=warn) return model = database.objectmodels[schema] if uuid: obj = model.find({'uuid': uuid}) elif object_filter: obj = model.find(literal_eval(object_filter)) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(ctx, schema, all_schemata): """Validates all objects or all objects of a given schema."""
database = ctx.obj['db'] if schema is None: if all_schemata is False: log('No schema given. Read the help', lvl=warn) return else: schemata = database.objectmodels.keys() else: schemata = [schema] for schema in schemata: try: ...