desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Render a widget for the Field/value @param field: the Field @param value: the value @param download_url: the download URL for upload fields @param attr: the HTML attributes for the widget @note: upload fields currently not rendered because the upload widget wouldn\'t render the current value, hence pointless for merge...
@staticmethod def widget(field, value, download_url=None, **attr):
widgets = SQLFORM.widgets ftype = str(field.type) if ((value is not None) and (ftype not in ('id', 'upload', 'blob'))): value = field.formatter(value) if (ftype == 'id'): inp = None elif (ftype == 'upload'): inp = None elif field.widget: if isinstance(field.widget...
'Constructor @param resource: the resource'
def __init__(self, resource):
self.resource = resource
'Roll back the current transaction and raise an error @param message: error message @param error: exception class to raise'
@staticmethod def raise_error(msg, error=RuntimeError):
current.db.rollback() raise error(msg)
'Merge the realms of two person entities (update all realm_entities in all records from duplicate to original) @param table: the table original and duplicate belong to @param original: the original record @param duplicate: the duplicate record'
def merge_realms(self, table, original, duplicate):
if ('pe_id' not in table.fields): return original_pe_id = original['pe_id'] duplicate_pe_id = duplicate['pe_id'] db = current.db for t in db: if ('realm_entity' in t.fields): query = (t.realm_entity == duplicate_pe_id) if ('deleted' in t.fields): ...
'Merge a duplicate record into its original and remove the duplicate, updating all references in the database. @param original_id: the ID of the original record @param duplicate_id: the ID of the duplicate record @param replace: list fields names for which to replace the values in the original record with the values of...
def merge(self, original_id, duplicate_id, replace=None, update=None, main=True):
self.main = main db = current.db resource = self.resource table = resource.table tablename = resource.tablename if resource.parent: self.raise_error('Must not merge from component', SyntaxError) auth = current.auth has_permission = auth.s3_has_permission permitted...
'Constructor: @param table: a Table object @param tablename: a Str tablename @param record: a Row object @param query: a Query object @param record_id: a record ID (if object is a Table) @param record_ids: a list of record IDs (if object is a Table) - these should be in ascending order @param rtable: the resource table...
def __init__(self, table=None, tablename=None, record=None, query=None, record_id=None, record_ids=None, rtable=None):
db = current.db s3db = current.s3db self.records = [] self.table = s3db.sit_trackable self.rtable = rtable if (table or tablename): if table: tablename = table._tablename else: table = s3db[tablename] fields = self.__get_fields(table) if (n...
'Check whether a trackable is a super-entity @param trackable: the trackable object'
@staticmethod def __super_entity(trackable):
if hasattr(trackable, 'fields'): keys = trackable.fields else: keys = trackable return ('instance_type' in keys)
'Check a trackable for presence of required fields @param: the trackable object'
def __get_fields(self, trackable, super_entity=True):
fields = [] if hasattr(trackable, 'fields'): keys = trackable.fields else: keys = trackable try: if (super_entity and self.__super_entity(trackable) and (UID in keys)): return ('instance_type', UID) if (LOCATION_ID in keys): fields.append(LOCATION_...
'Get the current location of the instance(s) (at the given time) @param timestmp: last datetime for presence (defaults to current time) @param _fields: fields to retrieve from the location records (None for ALL) @param _filter: filter for the locations @param as_rows: return the result as Rows object @param exclude: in...
def get_location(self, timestmp=None, _fields=None, _filter=None, as_rows=False, exclude=[], empty=True):
db = current.db s3db = current.s3db ptable = s3db[PRESENCE] ltable = s3db[LOCATION] if (timestmp is None): timestmp = datetime.utcnow() locations = [] for r in self.records: location = None if (TRACK_ID in r): query = (((ptable.deleted == False) & (ptable[...
'Set the current location of instance(s) (at the given time) @param location: the location (as Row or record ID) @param timestmp: the datetime of the presence (defaults to current time) @return: location'
def set_location(self, location, timestmp=None):
ptable = current.s3db[PRESENCE] if (timestmp is None): timestmp = datetime.utcnow() if isinstance(location, S3Trackable): location = location.get_base_location() if isinstance(location, Rows): location = location.first() if isinstance(location, Row): if ('location_id'...
'Bind the presence of the instance(s) to another instance @param table: table name of the other resource @param record: record in the other resource (as Row or record ID) @param timestmp: datetime of the check-in @return: nothing'
def check_in(self, table, record, timestmp=None):
db = current.db s3db = current.s3db ptable = s3db[PRESENCE] if isinstance(table, str): table = s3db[table] fields = self.__get_fields(table) if (not fields): raise SyntaxError(('No location data in %s' % table._tablename)) interlock = None if isinstance(record...
'Make the last log entry before timestmp independent from the referenced entity (if any) @param timestmp: the date/time of the check-out, defaults to current time'
def check_out(self, table=None, record=None, timestmp=None):
db = current.db s3db = current.s3db ptable = s3db[PRESENCE] if (timestmp is None): timestmp = datetime.utcnow() interlock = None if (table is not None): if isinstance(table, str): table = s3db[table] if isinstance(record, Rows): record = record.fir...
'Remove a location from the presence log of the instance(s) @todo: implement'
def remove_location(self, location=None):
raise NotImplementedError
'Get the base location of the instance(s) @param _fields: fields to retrieve from the location records (None for ALL) @param _filter: filter for the locations @param as_rows: return the result as Rows object @param empty: return None if no locations (set to False by gis.get_location_data()) @return: the base location(s...
def get_base_location(self, _fields=None, _filter=None, as_rows=False, empty=True):
db = current.db s3db = current.s3db ltable = s3db[LOCATION] rtable = self.rtable locations = [] for r in self.records: location = None query = None if (LOCATION_ID in r): query = (ltable.id == r[LOCATION_ID]) if rtable: query = (que...
'Set the base location of the instance(s) @param location: the location for the base location as Row or record ID @return: nothing @note: instance tables without a location_id field will be ignored'
def set_base_location(self, location=None):
if isinstance(location, S3Trackable): location = location.get_base_location() if isinstance(location, Rows): location = location.first() if isinstance(location, Row): location.get('id', None) if ((not location) or (not str(location).isdigit())): return else: d...
'Update the timestamp of a trackable @param track_id: the trackable ID (super-entity key) @param timestamp: the timestamp'
def __update_timestamp(self, track_id, timestamp):
if (timestamp is None): timestamp = datetime.utcnow() if track_id: trackable = self.table[track_id] if trackable: trackable.update_record(track_timestmp=timestamp)
'Get a tracking interface for a record or set of records @param table: a Table object @param record_id: a record ID (together with Table or tablename) @param record_ids: a list/tuple of record IDs (together with Table or tablename) @param tablename: a Str object @param record: a Row object @param query: a Query object ...
def __call__(self, table=None, record_id=None, record_ids=None, tablename=None, record=None, query=None):
return S3Trackable(table=table, tablename=tablename, record_id=record_id, record_ids=record_ids, record=record, query=query)
'Get all instances of the given entity at the given location and time'
def get_all(self, entity, location=None, bbox=None, timestmp=None):
raise NotImplementedError
'Get all trackables of the given type that are checked-in to the given instance at the given time'
def get_checked_in(self, table, record, instance_type=None, timestmp=None):
raise NotImplementedError
'Apply method. @param r: the S3Request @param attr: controller options for this request'
@staticmethod def apply_method(r, **attr):
if (r.representation == 'html'): T = current.T s3db = current.s3db response = current.response table = r.table tracker = S3Trackable(table, record_id=r.id) title = T('Check-In') get_vars = r.get_vars location_id = get_vars.get('location_id', None) ...
'Apply method. @param r: the S3Request @param attr: controller options for this request'
@staticmethod def apply_method(r, **attr):
if (r.representation == 'html'): T = current.T s3db = current.s3db response = current.response tracker = S3Trackable(r.table, record_id=r.id) title = T('Check-Out') formstyle = current.deployment_settings.get_ui_formstyle() row = formstyle('test', 'test', 'tes...
'Language menu'
@classmethod def menu_lang(cls, **attr):
settings = current.deployment_settings if (not settings.get_L10n_display_toolbar()): return None languages = current.response.s3.l10n_languages request = current.request menu_lang = MM('Language', **attr) for language in languages: menu_lang.append(MM(languages[language], r=reque...
'Help Menu'
@classmethod def menu_help(cls, **attr):
menu_help = MM('Help', c='default', f='help', **attr)(MM('Contact us', f='contact'), MM('About', f='about')) if current.deployment_settings.get_base_guided_tour(): table = current.s3db.tour_config logged_in = current.auth.is_logged_in() if logged_in: query = ((table.delete...
'Auth Menu'
@classmethod def menu_auth(cls, **attr):
auth = current.auth logged_in = auth.is_logged_in() settings = current.deployment_settings if (not logged_in): request = current.request login_next = URL(args=request.args, vars=request.vars) if ((request.controller == 'default') and (request.function == 'user') and ('_next' in r...
'Administrator Menu'
@classmethod def menu_admin(cls, **attr):
has_role = current.auth.s3_has_role settings = current.deployment_settings name_nice = settings.modules['admin'].name_nice if has_role('ADMIN'): translate = settings.has_module('translate') menu_admin = MM(name_nice, c='admin', **attr)(MM('Settings', f='setting'), MM('Users', f='user'), ...
'GIS Config Menu'
@classmethod def menu_gis(cls, **attr):
settings = current.deployment_settings if (not settings.get_gis_menu()): return None T = current.T db = current.db auth = current.auth s3db = current.s3db request = current.request s3 = current.session.s3 _config = s3.gis_config_id if ('_config' in request.get_vars): ...
'Menu for authentication with external services - used in default/user controller'
@classmethod def menu_oauth(cls, **attr):
T = current.T settings = current.deployment_settings return MOA(c='default')(MOA('Login with Facebook', f='facebook', args=['login'], api='facebook', check=(lambda item: current.s3db.msg_facebook_login()), title=T('Login using Facebook account')), MOA('Login with Google', f='google', ar...
'Constructor'
def __init__(self, name):
try: self.menu = getattr(self, name)() except AttributeError: if hasattr(self, name): raise self.menu = None
'ADMIN menu'
def admin(self):
ADMIN = current.session.s3.system_roles.ADMIN settings_messaging = self.settings_messaging() translate = current.deployment_settings.has_module('translate') return M(restrict=[ADMIN])(M('Settings', c='admin', f='setting')(settings_messaging), M('User Management', c='admin', f='user')(M('Create Use...
'ASSESS Menu'
@staticmethod def assess():
return M(c='assess')(M('Building Assessments', f='building')(M('Create', m='create'), M('Map', m='map')), M('Canvassing', f='canvass')(M('Create', m='create'), M('Map', m='map')))
'ASSET Controller'
@staticmethod def asset():
ADMIN = current.session.s3.system_roles.ADMIN telephones = (lambda i: current.deployment_settings.get_asset_telephones()) return M(c='asset')(M('Assets', f='asset', m='summary')(M('Create', m='create'), M('Import', m='import', p='create')), M('Telephones', f='telephone', m='summary', check=telephones)(M('Cr...
'BUDGET Controller'
@staticmethod def budget():
return M(c='budget')(M('Budgets', f='budget')(M('Create', m='create')), M('Staff Types', f='staff')(M('Create', m='create')), M('Projects', f='project')(M('Create', m='create')), M('Locations', f='location')(M('Create', m='create')), M('Bundles', f='bundle')(M('Create', m='create')), M('Kits', f='kit')(M('Create...
'BUILDING Controller'
@staticmethod def building():
return M(c='building')(M('NZSEE Level 1', f='nzseel1')(M('Submit New (triage)', m='create', vars={'triage': 1}), M('Submit New (full form)', m='create')), M('NZSEE Level 2', f='nzseel2')(M('Submit New', m='create')), M('Report', f='index')(M('Snapshot', f='report'), M('Assessment ti...
'CAP menu'
@staticmethod def cap():
return M(c='cap')(M('Alerts', f='alert')(M('Create', m='create'), M('Import from CSV', m='import', p='create'), M('Import from Feed URL', m='import_feed', p='create')), M('Templates', f='template')(M('Create', m='create')))
'CR / Shelter Registry'
@staticmethod def cr():
ADMIN = current.session.s3.system_roles.ADMIN if current.deployment_settings.get_ui_label_camp(): shelter = 'Camps' types = 'Camp Settings' else: shelter = 'Shelters' types = 'Shelter Settings' return M(c='cr')(M(shelter, f='shelter')(M('Create', m='create'), M('Map...
'CMS / Content Management System'
@staticmethod def cms():
return M(c='cms')(M('Series', f='series')(M('Create', m='create'), M('View as Pages', f='blog')), M('Posts', f='post')(M('Create', m='create'), M('View as Pages', f='page')))
'Data Collection Tool'
@staticmethod def dc():
return M(c='dc')(M('Templates', f='template')(M('Create', m='create'), M('Import', f='question', m='import')), M('Targets', f='target')(M('Create', m='create')), M('Responses', f='respnse')(M('Create', m='create')))
'DELPHI / Delphi Decision Maker'
@staticmethod def delphi():
ADMIN = current.session.s3.system_roles.ADMIN return M(c='delphi')(M('Active Problems', f='problem')(M('Create', m='create')), M('Groups', f='group')(M('Create', m='create')))
'Deployments'
@staticmethod def deploy():
deploy_team = current.deployment_settings.get_deploy_team_label() team_menu = ('%(team)s Members' % dict(team=deploy_team)) return M()(M('Missions', c='deploy', f='mission', m='summary')(M('Create', m='create'), M('Active Missions', m='summary', vars={'~.status__belongs': '2'})), M('Alerts', c='deploy...
'Disease Case Tracking and Contact Tracing'
@staticmethod def disease():
return M(c='disease')(M('Cases', c='disease', f='case', m='summary')(M('Create', m='create'), M('Watch List', m='summary', vars={'~.monitoring_level__belongs': 'OBSERVATION,DIAGNOSTICS'})), M('Contact Tracing', c='disease', f='tracing')(M('Create', m='create')), M('Statistics Data', c='disease', f='stats_d...
'DOC Menu'
@staticmethod def doc():
return M(c='doc')(M('Documents', f='document')(M('Create', m='create')), M('Photos', f='image')(M('Create', m='create')))
'DVI / Disaster Victim Identification'
@staticmethod def dvi():
return M(c='dvi')(M('Recovery Requests', f='recreq')(M('New Request', m='create'), M('List Current', vars={'recreq.status': '1,2,3'})), M('Dead Bodies', f='body')(M('Add', m='create'), M('List unidentified', vars={'identification.status': 'None'}), M('Report by Age/Gender', m='report', vars=dic...
'DVR Menu'
@staticmethod def dvr():
if current.deployment_settings.get_dvr_label(): return M(c='dvr')(M('Beneficiaries', f='person')(M('Create', m='create'))) return M(c='dvr')(M('Cases', f='person')(M('Create', m='create'), M('Archived Cases', vars={'archived': '1'})), M('Case Types', f='case_type')(M('Create', m='create')), M('Nee...
'Education Module'
@staticmethod def edu():
return M()(M('Schools', c='edu', f='school')(M('Create', m='create')), M('School Types', c='edu', f='school_type')(M('Create', m='create'), M('Import', m='import', p='create')))
'EVENT / Event Module'
@staticmethod def event():
if current.deployment_settings.get_event_label(): EVENTS = 'Disasters' EVENT_TYPES = 'Disaster Types' else: EVENTS = 'Events' EVENT_TYPES = 'Event Types' return M()(M('Scenarios', c='scenario', f='scenario')(M('Create', m='create'), M('Import', m='import', p='create')),...
'FIRE'
@staticmethod def fire():
return M(c='fire')(M('Fire Stations', f='station')(M('Create', m='create'), M('Map', m='map'), M('Import Stations', m='import'), M('Import Vehicles', f='station_vehicle', m='import')), M('Fire Zones', f='zone')(M('Create', m='create')), M('Zone Types', f='zone_type')(M('Create', m='create')), M('Wate...
'GIS / GIS Controllers'
@staticmethod def gis():
MAP_ADMIN = current.session.s3.system_roles.MAP_ADMIN settings = current.deployment_settings gis_menu = settings.get_gis_menu() def pois(i): poi_resources = settings.get_gis_poi_create_resources() if (not poi_resources): return False for res in poi_resources: ...
'HMS / Hospital Status Assessment and Request Management'
@staticmethod def hms():
return M(c='hms')(M('Hospitals', f='hospital')(M('Create', m='create'), M('Map', m='map'), M('Report', m='report'), M('Import', m='import', p='create')))
'HRM / Human Resources Management'
@staticmethod def hrm():
s3 = current.session.s3 ADMIN = s3.system_roles.ADMIN skills = (lambda i: settings.get_hrm_use_skills()) certificates = (lambda i: settings.get_hrm_use_certificates()) is_org_admin = (lambda i: ((s3.hrm.orgs and True) or (ADMIN in s3.roles))) settings = current.deployment_settings teams = se...
'Volunteer Management'
@staticmethod def vol():
s3 = current.session.s3 ADMIN = s3.system_roles.ADMIN is_org_admin = (lambda i: ((s3.hrm.orgs and True) or (ADMIN in s3.roles))) settings = current.deployment_settings show_programmes = (lambda i: (settings.get_hrm_vol_experience() == 'programme')) show_tasks = (lambda i: (settings.has_module('p...
'INV / Inventory'
@staticmethod def inv():
ADMIN = current.session.s3.system_roles.ADMIN current.s3db.inv_recv_crud_strings() inv_recv_list = current.response.s3.crud_strings.inv_recv.title_list settings = current.deployment_settings use_adjust = (lambda i: (not settings.get_inv_direct_stock_edits())) use_commit = (lambda i: settings.get...
'IRS / Incident Report System'
@staticmethod def irs():
ADMIN = current.session.s3.system_roles.ADMIN return M(c='irs')(M('Incident Reports', f='ireport')(M('Create Incident Report', m='create'), M('Open Incidents', vars={'open': 1}), M('Map', m='map'), M('Timeline', args='timeline'), M('Import', m='import'), M('Report', m='report')), M('Incident Cate...
'Security Management System'
@staticmethod def security():
ADMIN = current.session.s3.system_roles.ADMIN return M(c='security')(M('Incident Reports', c='event', f='incident_report', m='summary')(M('Create', m='create'), M('Import', m='import')), M('Security Levels', f='level')(M('level', m='create')), M('Security Zones', f='zone')(M('Create', m='create')), M('...
'SCENARIO'
def scenario(self):
return self.event()
'SUPPLY'
def supply(self):
return self.inv()
'SURVEY / Survey'
@staticmethod def survey():
ADMIN = current.session.s3.system_roles.ADMIN series_id = False get_vars = Storage() try: series_id = int(current.request.args[0]) except: try: (dummy, series_id) = current.request.get_vars['viewing'].split('.') series_id = int(series_id) except: ...
'Membership Management'
@staticmethod def member():
types = (lambda i: current.deployment_settings.get_member_membership_types()) return M(c='member')(M('Members', f='membership', m='summary')(M('Create', m='create'), M('Import', f='person', m='import')), M('Membership Types', f='membership_type', check=types)(M('Create', m='create')))
'MPR / Missing Person Registry'
@staticmethod def mpr():
return M(c='mpr')(M('Missing Persons', f='person')(M('Create', m='create')))
'MSG / Messaging'
def msg(self):
ADMIN = current.session.s3.system_roles.ADMIN if (current.request.function in ('sms_outbound_gateway', 'email_channel', 'facebook_channel', 'sms_modem_channel', 'sms_smtp_channel', 'sms_webapi_channel', 'tropo_channel', 'twitter_channel')): return self.admin() settings_messaging = self.settings_mess...
'ORG / Organization Registry'
@staticmethod def org():
settings = current.deployment_settings ADMIN = current.session.s3.system_roles.ADMIN SECTORS = ('Clusters' if settings.get_ui_label_cluster() else 'Sectors') stats = (lambda i: settings.has_module('stats')) return M(c='org')(M('Organizations', f='organisation')(M('Create', m='create'), M('Import', m...
'PATIENT / Patient Tracking'
@staticmethod def patient():
return M(c='patient')(M('Patients', f='patient')(M('Create', m='create')))
'PO / Population Outreach'
@staticmethod def po():
due_followups = current.s3db.po_due_followups() DUE_FOLLOWUPS = current.T('Due Follow-ups') if due_followups: follow_up_label = ('%s (%s)' % (DUE_FOLLOWUPS, due_followups)) else: follow_up_label = DUE_FOLLOWUPS return M(c='po')(M('Overview', f='index'), M('Households', f='house...
'Police'
@staticmethod def police():
return M(c='police')(M('Police Stations', f='station')(M('Create', m='create')))
'PR / Person Registry'
@staticmethod def pr():
ADMIN = current.session.s3.system_roles.ADMIN return M(c='pr', restrict=ADMIN)(M('Persons', f='person')(M('Create', m='create')), M('Groups', f='group')(M('Create', m='create')))
'PROC / Procurement'
@staticmethod def proc():
return M(c='proc')(M('Procurement Plans', f='plan')(M('Create', m='create')), M('Suppliers', f='supplier')(M('Create', m='create')))
'PROJECT / Project Tracking & Management'
@staticmethod def project():
settings = current.deployment_settings activities = (lambda i: settings.get_project_activities()) activity_types = (lambda i: settings.get_project_activity_types()) community = settings.get_project_community() if community: IMPORT = 'Import Project Communities' else: IMPORT...
'REQ / Request Management'
@staticmethod def req():
ADMIN = current.session.s3.system_roles.ADMIN settings = current.deployment_settings types = settings.get_req_req_type() if (len(types) == 1): t = types[0] if (t == 'Stock'): create_menu = M('Create', m='create', vars={'type': 1}) elif (t == 'People'): cre...
'Statistics'
@staticmethod def stats():
return M(c='stats')(M('Demographics', f='demographic')(M('Create', m='create')), M('Demographic Data', f='demographic_data', args='summary')(M('Create', m='create'), M('Time Plot', m='timeplot'), M('Import', m='import')))
'Social Tenure Domain Model'
@staticmethod def stdm():
ADMIN = current.session.s3.system_roles.ADMIN has_role = current.auth.s3_has_role informal = (lambda i: has_role('INFORMAL_SETTLEMENT')) gov = (lambda i: has_role('LOCAL_GOVERNMENT')) rural = (lambda i: has_role('RURAL_AGRICULTURE')) return M(c='stdm')(M('Administrative Units', c='gis', f='lo...
'SYNC menu'
def sync(self):
return self.admin()
'Guided Tour'
@staticmethod def tour():
ADMIN = current.session.s3.system_roles.ADMIN return M(c='tour')(M('Configuration', f='config', restrict=[ADMIN])(M('Import', m='import', restrict=[ADMIN])), M('Detail', f='details', restrict=[ADMIN]), M('User', f='user', restrict=[ADMIN]))
'TRANSPORT'
@staticmethod def transport():
ADMIN = current.session.s3.system_roles.ADMIN return M(c='transport')(M('Airports', f='airport')(M('Create', m='create'), M('Map', m='map'), M('Import', m='import', restrict=[ADMIN])), M('Border Crossings', f='border_crossing')(M('Create', m='create'), M('Map', m='map'), M('Import', m='import', restrict=[ADM...
'VEHICLE / Vehicle Tracking'
@staticmethod def vehicle():
return M(c='vehicle')(M('Vehicles', f='vehicle')(M('Create', m='create'), M('Import', m='import', p='create'), M('Map', m='map')), M('Vehicle Types', f='vehicle_type')(M('Create', m='create')))
'Vulnerability'
@staticmethod def vulnerability():
return M(c='vulnerability')(M('Indicators', f='indicator')(M('Create', m='create')), M('Data', f='data')(M('Create', m='create'), M('Import', m='import')))
'Water: Floods, etc'
@staticmethod def water():
return M(c='water')(M('Gauges', f='gauge')(M('Create', m='create'), M('Map', m='map'), M('Import', m='import')), M('Rivers', f='river')(M('Create', m='create'), M('Map', m='map')), M('Zones', f='zone')(M('Create', m='create'), M('Map', m='map')), M('Zone Types', f='zone_type')(M('Create', m='create'), M('Map', m...
'WORK: Simple Volunteer Jobs Management'
@staticmethod def work():
return M(c='work')(M('Joblist', f='job', m='datalist'), M('Jobs', f='job')(M('Create', m='create')), M('Assignments', f='assignment')(M('Create', m='create')), M('Job Types', f='job_type')(M('Create', m='create')))
'Messaging settings menu items: These items are used in multiple menus, but each item instance can always only belong to one parent, so we need to re-instantiate with the same parameters, and therefore this is defined as a function here.'
@classmethod def settings_messaging(cls):
return [M('Email Channels (Inbound)', c='msg', f='email_channel'), M('Facebook Channels', c='msg', f='facebook_channel'), M('RSS Channels', c='msg', f='rss_channel'), M('SMS Outbound Gateways', c='msg', f='sms_outbound_gateway')(M('SMS Modem Channels', c='msg', f='sms_modem_channel'), M('SMS...
'Breadcrumbs from the current options menu'
@classmethod def breadcrumbs(cls):
layout = S3BreadcrumbsLayout request = current.request controller = request.controller function = request.function all_modules = current.deployment_settings.modules breadcrumbs = layout()(layout(all_modules['default'].name_nice)) if (controller != 'default'): try: breadcr...
'Create the base Figure object @param: height x100px @param: width x100px'
def __init__(self, path, width=9, height=6):
try: from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas self.FigureCanvas = FigureCanvas from matplotlib.figure import Figure self.Figure = Figure MATPLOTLIB = True except ImportError: import sys print >>sys.stderr, 'WARNING: S3...
'Return the opened cached file, if the file can\'t be found then return None'
@staticmethod def getCachedFile(filename):
chartFile = S3Chart.getCachedPath(filename) if chartFile: try: f = open(chartFile) return f.read() except: pass return None
'Save the file in the cache area, and return the path to this file'
@staticmethod def storeCachedFile(filename, image):
path = 'applications' chartFile = ('%s/%s.png' % (S3Chart.CACHE_PATH, filename)) fullPath = ('%s%s' % (path, chartFile)) try: f = open(fullPath, 'w+') print >>f, image except: return None return chartFile
'Delete the files in the cache that match the file name prefix, if the prefix is None then all files will be deleted'
@staticmethod def purgeCache(prefix=None):
import os folder = ('applications%s/' % S3Chart.CACHE_PATH) if os.path.exists(folder): filelist = os.listdir(folder) for file in filelist: if ((prefix == None) or file.startswith(prefix)): os.remove(('%s%s' % (folder, file)))
'Output the chart as a PNG embedded in an IMG tag - used by the Delphi module'
def draw(self, output='xml'):
fig = self.fig if (not fig): return 'Matplotlib not installed' chart = Storage() chart.body = StringIO() chart.headers = Storage() chart.headers['Content-Type'] = 'image/png' canvas = self.FigureCanvas(fig) canvas.print_figure(chart.body) image = chart.body.getvalue() ...
'Draw a Histogram - used by the Survey module'
def survey_hist(self, title, data, bins, min, max, xlabel=None, ylabel=None):
fig = self.fig if (not fig): return 'Matplotlib not installed' from numpy import arange ax = fig.add_subplot(111) ax.hist(data, bins=bins, range=(min, max)) left = arange(0, (bins + 1)) if self.asInt: label = (left * int((max / bins))) else: label = ((left *...
'Draw a Pie Chart - used by the Survey module'
def survey_pie(self, title, data, label):
fig = self.fig if (not fig): return 'Matplotlib not installed' ax = fig.add_subplot(111) ax.pie(data, labels=label) ax.legend() ax.set_title(title)
'Draw a Bar Chart - used by the Survey module'
def survey_bar(self, title, data, labels, legendLabels):
barColourList = ['#F2D7A0', '#7B77A8', '#69889A', '#9D7B34'] barColourListExt = [(242, 215, 160), (123, 118, 168), (105, 136, 154), (157, 123, 52)] fig = self.fig if (not fig): return 'Matplotlib not installed' from numpy import arange if (not isinstance(data[0], list)): da...
'Update Affiliation, record ownership and component ownership'
@staticmethod def transport_airport_onaccept(form):
return
'Update Affiliation, record ownership and component ownership'
@staticmethod def transport_heliport_onaccept(form):
return
'Update Affiliation, record ownership and component ownership'
@staticmethod def transport_seaport_onaccept(form):
return
'Constructor @param show_link: render as link to the border crossing'
def __init__(self, show_link=False):
super(transport_BorderCrossingRepresent, self).__init__(lookup='transport_border_crossing', show_link=show_link)
'Represent a row @param row: the Row'
def represent_row(self, row):
if hasattr(row, 'transport_border_crossing'): row = row.transport_border_crossing representation = row.name if hasattr(row, 'countries'): representation = ('%s (%s)' % (representation, ', '.join(row.countries))) return representation
'Custom rows lookup @param key: the key Field @param values: the values @param fields: unused (retained for API compatibility)'
def lookup_rows(self, key, values, fields=[]):
s3db = current.s3db btable = self.table ctable = s3db.transport_border_crossing_country left = ctable.on(((ctable.border_crossing_id == btable.id) & (ctable.deleted != True))) if (len(values) == 1): query = (key == values[0]) else: query = key.belongs(values) rows = current.d...
'After DB I/O, check the correctness of fiscal code (ITALY) @ToDo: The function should be made a deployment_setting when anyone else wishes to use this module'
@staticmethod def evr_case_onaccept(form):
fiscal_code = form.vars.fiscal_code if ((fiscal_code == '') or (fiscal_code == None)): return fiscal_code = fiscal_code.upper() MALE = 3 CONSONANTS = 'BCDFGHJKLMNPQRSTVWXYZ' VOWELS = 'AEIOU' MONTHS = 'ABCDEHLMPRST' T = current.T ptable = current.s3db.pr_person query = (fo...
'Entry point for REST controller @param r: the S3Request @param attr: dictionary of parameters for the method handler @return: output object to send to the view'
def apply_method(self, r, **attr):
if (r.http in ('GET', 'POST')): if (((r.representation == 'html') and r.id) or (r.representation == 'aadata')): return self.add_members(r, **attr) else: r.error(415, current.ERROR.BAD_FORMAT) else: r.error(405, current.ERROR.BAD_METHOD)
'Add-members action: renders a filtered multi-select datatable form, and creates group_memberships on POST @param r: the S3Request @param attr: dictionary of parameters for the method handler @return: output object to send to the view'
def add_members(self, r, **attr):
T = current.T db = current.db s3db = current.s3db unaffiliated = ((S3FieldSelector('group_membership.id') == None) & (S3FieldSelector('case.id') != None)) if (r.http == 'POST'): group_id = r.id added = 0 post_vars = r.post_vars if all([(name in post_vars) for name in ...
'Represent a staff type in list views'
@staticmethod def security_staff_type_multirepresent(opt):
db = current.db table = db.security_staff_type set = db((table.id > 0)).select(table.id, table.name).as_dict() if isinstance(opt, (list, tuple)): opts = opt vals = [str(set.get(o)['name']) for o in opts] multiple = True elif isinstance(opt, int): opts = [opt] ...
'Safe defaults for names in case the module is disabled'
@staticmethod def defaults():
return {'security_seized_item_status_opts': {}}
'Onaccept-routine for seized items: - set returned_on and returned_by if status=="RET"'
@staticmethod def seized_item_onaccept(form):
db = current.db s3db = current.s3db formvars = form.vars try: record_id = formvars.id except AttributeError: return table = s3db.security_seized_item query = ((table.id == record_id) & (table.deleted == False)) record = db(query).select(table.id, table.status, table.retur...
'Safe defaults for model-global names in case module is disabled'
@staticmethod def defaults():
dummy = S3ReusableField('dummy_id', 'integer', readable=False, writable=False) return dict(hrm_department_id=(lambda **attr: dummy('department_id')), hrm_job_title_id=(lambda **attr: dummy('job_title_id')), hrm_human_resource_id=(lambda **attr: dummy('human_resource_id')))
'Update detection for hrm_job_title @param item: the S3ImportItem'
@staticmethod def hrm_job_title_duplicate(item):
data = item.data name = data.get('name', None) if current.deployment_settings.get_hrm_org_dependent_job_titles(): org = data.get('organisation_id', None) else: org = None role_type = data.get('type', None) table = item.table query = (table.name.lower() == s3_unicode(name).low...