def mergeWithDefaultStatistics(statistics, defaultStatistics, appendToDefaultStatistics, hideStatisticsByDefault): if not hideStatisticsByDefault and not statistics: Print.logWarning( 'Please provide \'statistics\' keyword for all relevant pages') if statistics is None or not defaultStatistics: return statistics if isinstance(statistics, str): defaultStatistics['title'] = statistics return defaultStatistics if not appendToDefaultStatistics: return statistics s = { 'substatistics': [], } if 'key' in statistics: s['key'] = statistics['key'] if 'title' in statistics: s['title'] = statistics['title'] if not 'substatistics' in statistics and 'substatistics' in defaultStatistics: if 'key' in defaultStatistics: s['key'] = defaultStatistics['key'] if 'title' in defaultStatistics: s['title'] = defaultStatistics['title'] s['substatistics'].extend(StatisticsTools.statisticsToList(statistics)) s['substatistics'].extend( StatisticsTools.statisticsToList(defaultStatistics, prefixToKey='default')) return s
def _createPathStaticFile(self, pathStatic): try: p = os.path.join(pathStatic, Experiment._pathStaticFile) if not os.path.exists(p): Print.log('Creating path for static files') os.makedirs(p) Print.log2('Success') except: Print.log2() Print.log2( f'{COLORS.ERROR}ERROR: Could not create path for static files.{COLORS.DEFAULT}' ) Print.log2() return False return True
def init(app, password): if password is None: Print.log('No password for the statistics website provided. The') Print.log2('page will be disabled.') elif not Authenticate._validPassword(password): Print.logWarning('The password for the statistics websites needs to be') Print.log2Warning('six characters in length at the minimum. The page will') Print.log2Warning('be disabled.') app.config.update(SECRET_KEY='Empiric!', USE_SESSION_FOR_NEXT=True) loginManager = LoginManager() loginManager.init_app(app) loginManager.login_view = 'login' defaultUser = '******' class User(UserMixin): def __init__(self, username): self.id = username def __repr__(self): return self.username @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': if 'password' in request.form and Authenticate._validPassword(password) and request.form['password'] == password: login_user(User(defaultUser)) return redirect(url_for('statistics')) else: return render_template('login.html', message='Wrong password. Please try again.') elif request.method == 'GET': return render_template('login.html') return render_template('login.html', message='Bad login request.') @app.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('login')) @loginManager.user_loader def loader_user(username): return User(username)
def _yarnInstall(self, pathStatic): try: Print.log('Installing JavaScript libraries using yarn') subprocess.run(['yarn', 'install'], capture_output=True, cwd=pathStatic) Print.log2('Success') except: Print.log2() Print.log2( f'{COLORS.ERROR}ERROR: Yarn could not install the libraries needed.' ) Print.log2() Print.log2('Please run yarn on your own:') Print.log2(f'> cd static && yarn install{COLORS.DEFAULT}') Print.log2() return False return True
def _yarnCopyPackageFiles(self, pathStatic): try: if not os.path.exists(pathStatic): Print.log('Creating path for static data') os.makedirs(pathStatic) Print.log2('Success') Print.log('Copy files to the path for static data') for filenameSrc, filenameDst in [('package.json', 'package.json'), ('yarn.lock', 'yarn.lock'), ('yarnrc', '.yarnrc')]: shutil.copy( os.path.join(os.path.dirname(__file__), 'files', filenameSrc), os.path.join(pathStatic, filenameDst)) Print.log2('Success') except Exception as e: print(e) Print.log2() Print.log2( f'{COLORS.ERROR}ERROR: Could not copy Yarn package files.{COLORS.DEFAULT}' ) Print.log2() return False return True
def _yarnCheck(self): try: Print.log('Checking for Yarn') subprocess.run(['yarn', '--version'], capture_output=True) Print.log2('Found') except: Print.log2() Print.log2( f'{COLORS.ERROR}ERROR: Yarn is needed. Please install it.') Print.log2() Print.log2('You find Yarn here: https://yarnpkg.com') Print.log2() Print.log2('Yarn is required to download libraries needed for the') Print.log2(f'web interface.{COLORS.DEFAULT}') Print.log2() return False return True
def _info(self): width = 54 Print.log2() Print.log2('=' * width) Print.log2('== ', f'{pkgName} v{pkgVersion}', ' ' * (width - 8 - len(pkgName) - len(pkgVersion)), ' ==') Print.log2('== ', pkgUrl, ' ' * (width - 6 - len(pkgUrl)), ' ==') Print.log2('=' * width) Print.log2()
def createPageStructure(self): pathRoot = self._computePath(None, '') pathPages = self._computePath(None, 'pages') pathPagesInit = os.path.join(pathPages, '__init__.py') pathTemplates = self._computePath(None, 'templates') if not os.path.exists(pathPages): Print.log('Creating path for pages') os.makedirs(pathPages) Print.log2('Success') if not os.path.exists(pathPagesInit): Print.log('Creating init file for the path for pages') with open(pathPagesInit, 'a'): pass Print.log2('Success') if not os.path.exists(pathTemplates): Print.log('Creating path for templates') os.makedirs(pathTemplates) Print.log2('Success') Print.log('Copy example files') for p, filename in [(pathPages, '_PageExample.py'), (pathTemplates, '_pageExample.html')]: if not os.path.exists(os.path.join(p, filename)): shutil.copy( os.path.join(os.path.dirname(__file__), 'files', filename), os.path.join(p, filename)) for filenameSrc, filenameDst in [('package2.json', 'package.json'), ('yarnrc2', '.yarnrc')]: if not os.path.exists(os.path.join(pathRoot, filenameDst)): shutil.copy( os.path.join(os.path.dirname(__file__), 'files', filenameSrc), os.path.join(pathRoot, filenameDst)) Print.log2('Success')
def run(self, **settings): statistics = None if 'statistics' in settings and isinstance(settings['statistics'], str): statistics = { 'title': settings['statistics'], } try: substatistics = {} if 'questions' in settings: questions = ElementTree.fromstring( '<root>' + re.sub('required(?!=)', 'required="true"', settings['questions']) + '</root>') for n in questions: key = PageQuestionnaire._attrib(n, 'key') if not key or key in statistics: continue s = {'key': key} if n.tag == 'choice': substatistics[key] = { **s, 'title': PageQuestionnaire._attrib(n, 'text'), 'data': { 'selector': f'questionnaire.{key}', 'aggregateByPage': 'first', 'defaultValue': None, }, 'visualization': { 'type': VISUALIZATION_TYPE.BAR_CHART, 'options': list(map(lambda x: x.text, n)), }, } elif n.tag == 'slider': substatistics[key] = { **s, 'title': PageQuestionnaire._attrib(n, 'text'), 'data': { 'selector': f'questionnaire.{key}', 'aggregateByPage': 'first', 'defaultValue': None, }, 'visualization': { 'type': VISUALIZATION_TYPE.BOX_PLOT, 'options': list(map(lambda x: x.text, n)), 'min': PageQuestionnaire._attrib(n, 'min', defaultValue=-2, mapFn=float), 'center': PageQuestionnaire._attrib( n, 'center', defaultValue=None, mapFn=float), 'max': PageQuestionnaire._attrib(n, 'max', defaultValue=2, mapFn=float), 'min-label': PageQuestionnaire._attrib(n, 'min-label'), 'center-label': PageQuestionnaire._attrib( n, 'center-label'), 'max-label': PageQuestionnaire._attrib(n, 'max-label'), }, } elif n.tag == 'text': substatistics[key] = { **s, 'title': PageQuestionnaire._attrib(n, 'text'), 'data': { 'selector': f'questionnaire.{key}', 'aggregateByPage': 'first', }, 'visualization': { 'type': VISUALIZATION_TYPE.TEXT_COLLECTION, }, } statistics['substatistics'] = list(substatistics.values()) except Exception as e: Print.log('WARNING: Could not parse questionnaire: ', str(e)) return super().run(defaultStatistics=statistics, **settings)