def generate_output(setup, title, img_height, conts_to_display, skin, imgs=[]): """Recursively generate output for setup+continuations.""" #not the penultimate bag, need to go deeper if len(setup.continuations[0].continuations) > 0: #store images in list to print at the end new_imgs = imgs.copy() #don't think this needs to be a deepcopy new_imgs.append(fumen_to_image(setup.solution.fumen, img_height, skin)) # this naming scheme could get messy, anything better? maybe Setup 1-A-A? # but I'm not sure what to do if more continuatons than 26, maybe just AA, then AAA new_ctd = conts_to_display - 1 if conts_to_display > 1 else 1 for i, s in enumerate(tqdm(setup.continuations, unit="setup", leave=False)): generate_output(s, title + (" - Sub-Setup %d" % i), img_height, new_ctd, skin, new_imgs) else: h2(title) with div(): for url in imgs: img(src=url) #final setup with conts, still need to display it's image img(src=fumen_to_image(setup.solution.fumen, img_height, skin)) conts_to_display -= 1 for cont in setup.continuations[:conts_to_display]: img(src=fumen_to_image(cont.solution.fumen, img_height, skin)) with p(): total_conts = len(setup.continuations) text("Showing ") b("%d" % min(conts_to_display, total_conts)) text(" of ") b(a("%d continuations" % total_conts, href=fumen_url + setup.to_fumen()))
def writeContent(self): self.writeln('<h1>Using Webware with Dominate</h1>') self.writeln( '<p>Dominate is a Python library that can be used in Webware' ' applications to generate HTML programmatically.</p>') if not dominate: self.writeln( f'<p>Please install <a href="{self.homepage}">Dominate</a>' ' in order to view this demo.</p>') return content = div(id='content') with content: h2('Hello World!') with table(cls="NiceTable").add(tbody()): tr(th('Demo table', colspan=3)) r = tr() r += td('One') r.add(td('Two')) with r: td('Three') para = p(__pretty=False) with para: text('This content has been produced with ') a('Dominate', href=self.homepage) text(' programmatically.') self.write(content)
def render(self): if len(self.highlights) == 0 \ and len(self.notes) == 0 \ and len(self.bookmarks) == 0: return with div(): h2(self.title) if self.authors is not None: p(f'Authors: {self.authors}') p(f'File: {self.file_name}') if len(self.bookmarks) > 0: h3('Bookmarks') with ol(): for bookmark in self.bookmarks: with li(): bookmark.render() if len(self.highlights) > 0: h3('Highlights') with ol(): for highlight in self.highlights: with li(): highlight.render() if len(self.notes) > 0: h3('Notes') with ol(): for note in self.notes: with li(): note.render()
def h2(self, txt): """Insert a header to the HTML file Parameters: text (str) -- the header text """ with self.doc: h2(txt)
def generate_output_pc(setup, title, pc_cutoff, pc_height, img_height, skin, cache, imgs=[]): #not the penultimate bag, need to go deeper if len(setup.continuations[0].continuations) > 0: #store images in list to print at the end new_imgs = imgs.copy() #don't think this needs to be a deepcopy new_imgs.append(fumen_to_image(setup.solution.fumen, img_height, skin)) for i, s in enumerate(tqdm(setup.continuations, unit="setup", leave=False)): generate_output_pc(s, title + (" - Sub-Setup %d" % i), pc_cutoff, pc_height, img_height, skin, cache, new_imgs) else: sf = SFinder(setup_cache=cache) h2(title) with div(): best_continuation = setup.continuations[0].solution best_pc = sf.path( fumen=best_continuation.to_fumen(), pieces=best_continuation.get_remaining_pieces(), height=pc_height)[0] #todo: hack! change this when i fix cache for url in imgs: img(src=url) img(src=fumen_to_image(setup.solution.fumen, img_height, skin)) img(src=fumen_to_image(best_continuation.fumen, img_height, skin)) img(src=fumen_to_image(best_pc.fumen, img_height, skin)) with p(): text("Best continuation: ") b("%.2f%%" % setup.continuations[0].PC_rate) text(" PC success rate – ") b(a("%d continuations" % len(setup.continuations), href=fumen_url + setup.to_fumen())) text("with >%.2f%% PC success rate" % pc_cutoff)
def createHtmlStructure(channel, limit, html_path, pdf_path): ''' 1. in loop create html structure 2. return html_structure 3. or file name of pdf for send_from_directory function ''' html_document = dominate.document(title="HTML document") for index, item in enumerate(channel.entries): if (index == limit): break with html_document: with div(): h2("Title: " + html.unescape(item.title)) p("Link: " + item.link) media_content = news_parser.checkMediaContent(item) if (media_content): img(src=media_content) description = news_parser.getDescription(item.description) if (description): p("Description: " + description) if (html_path): return str(html_document) elif (pdf_path): return topdf.convertHtmlToPdf(str(html_document), pdf_path)
def createHtmlFromDB(limit, html_path, pdf_path, arg_date): ''' 1. in loop create html structure 2. create html document or convert html structure into pdf ''' records = getCacheFromDB(arg_date) html_document = dominate.document(title="HTML document") for index, row in enumerate(records): if(limit and index == limit): break with html_document: with div(): h2("Title: " + row[0]) p("Link: " + row[1]) if (row[2]): img(src="data:image/jpg;base64," + base64.b64encode(row[2]).decode('ascii')) if (row[3]): p("Description: " + row[3]) if (html_path): return str(html_document) elif (pdf_path): return topdf.convertHtmlToPdf(str(html_document), pdf_path)
def convert_new_in_html(cmd_args, new, html_file): """ Convert one new to HTML format """ with html_file: with tag.div(): tag.h2(new.get('title')) tag.p(new.get('date')) tag.br() tag.a("Read the full article", href=new.get('link')) tag.br() tag.br() if cmd_args.date: for num, link in enumerate(new.get('img_link'), 1): tag.a(f"Image link № {num}", href=link) tag.br() else: for num, link in enumerate(new.get('img_link')): tag.img(src=link, alt=new.get('img_title')[num]) tag.br() tag.p(new.get('text')) tag.br() return html_file
def add_caption(self, text): """ Insert a caption under the first line Parametres: text (str): -- the caption text """ with self.doc: h2(text)
def report(job, report): """Generate a report.html with analysis and timelines from given jobs.""" jobs = job today = datetime.datetime.now().strftime("%Y-%m-%d") doc = dominate.document(title='Build Stats - {}'.format(today)) with doc.head: dt.link( rel='stylesheet', href= 'https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/3.0.1/github-markdown.min.css' ) dt.meta(name='viewport', content='width=device-width, initial-scale=1') # Create <article>...</article> according to sindresorhus/github-markdown-css article = dt.article(cls='markdown-body') doc += article with article: dt.h1('Marathon Loop Build Stats ({})'.format(today)) # Generate report for each job. for job in jobs: j = JenkinsJob.load(job) loop = asyncio.get_event_loop() tests = loop.run_until_complete(j.unique_fails()).to_html() errors = loop.run_until_complete(j.unique_errors()).to_html() f = io.BytesIO() fail_statuses = ['FAILED', 'REGRESSION'] loop = asyncio.get_event_loop() df = loop.run_until_complete(j.test_dataframe()) ts = df.groupby(level=0).agg({ 'status': lambda x: x.isin(fail_statuses).any(), 'timestamp': 'max' }) plt.figure(figsize=(20, 3)) c = ts.status.map({True: 'xkcd:light red', False: 'xkcd:light blue'}) plt.bar(x=ts.timestamp, height=1, width=0.01, color=c, align='edge') plt.xlim([ts.timestamp.min(), ts.timestamp.max()]) plt.savefig(f, format='svg') with article: dt.h2('Marathon {}'.format(job)) dt.div(dominate.util.raw(errors)) dt.div(dominate.util.raw(tests)) dt.div(dominate.util.raw(f.getvalue().decode('utf-8'))) with open(report, "w") as report_file: print(doc, file=report_file)
def generateHtml(): with open(path.join(current_dir, '../changelog/', 'storage.json'), 'r') as f: data = json.load(f)[::-1] doc = document(title='Changelog - lkellar.org') articles = [] with doc.head: tags.link(rel='stylesheet', href='style.css') tags.meta(charset="UTF-8") tags.meta(name="description", content="A log of all changes made on lkellar.org") tags.meta(name="viewport", content="width=device-width, initial-scale=1") tags.link(rel="alternate", title="Changelog Feed", type="application/json", href="https://lkellar.org/changelog/feed.json") with doc: with tags.nav().add(tags.ol()): with tags.li(): tags.a("Home", href="../") tags.li("Changelog") with tags.main(): tags.h1('Changelog') for entry in data: tags.hr() article_content = tags.article() with article_content: tags.h2( f'{entry["title"]} - {entry["date"].split("T")[0]}', id=f'{entry["title"]} - {entry["date"]}'.replace( ' ', ''.lower())) list_content = tags.ul() with list_content: for line in entry['items']: line = urls.sub(r'<a href="\2">\1</a>', line) tags.li(raw(line)) articles.append((f'{entry["title"]} - {entry["date"]}'.replace( ' ', ''.lower()), list_content.render(), entry["date"], entry['title'])) with open(path.join(current_dir, '../changelog/', 'index.html'), 'w') as f: f.write(doc.render()) generateFeed(articles)
def dominate_enter_page(): """ 第三頁:確認資訊頁面,對應到 @app.route('/jump') 及其函數 registerpage_run [if request.method == 'POST'] 目標:利用dominate寫出 enter_page 的 html並在 templates 資料夾中存成 index3.html 分為三個區塊 doc = dominate.document() with doc.head (包含css的style;meta確保中文可以運行在utf-8下) with doc.body (包含 6 information: name/ password/ student_id/ telephone_number/ school_bike_license/ bike_lock_number and a button confirm) 最後寫入文件中(在templates資料夾中存成index3.html) """ doc = dominate.document(title="entered") with doc.head: tags.meta(name='charset', content="utf-8") tags.style("""\ body { background-color: #F9F8F1; color: #2C232A; font-family: sans-serif; font-size: 14; text-align: center; } """) with doc.body: tags.h1('welcome' + str(name_list_temp[0])) tags.h2('please confirm your information') with tags.section(cls='information check'): with tags.div(cls='name', style="text-align: center"): tags.label('your name is ' + str(name_list_temp[0])) with tags.div(cls='password', style="text-align: center"): tags.label('your password is ' + str(password_temp[0])) with tags.div(cls='student_id', style="text-align: center"): tags.label('your student id is ' + str(student_id_temp[0])) with tags.div(cls='telephone', style="text-align: center"): tags.label('your telephone number is ' + str(telephone_number_temp[0])) with tags.div(cls='license', style="text-align: center"): tags.label('the status of your bike_lice ' + str(school_bike_license_temp[0])) with tags.div(cls='lock_number', style="text-align: center"): tags.label('your bike lock number is ' + str(bike_lock_number_temp[0])) with tags.div(cls='button', style="margin:0 auto; width:250px;"): tags.input(type='button', value='confirm', style="width:120px; background-color:pink;", onclick="location.href='http://127.0.0.1:5000/entered'") fn = 'templates/index3.html' with open(file=fn, mode='w', encoding='utf-8') as f: f.write(doc.render()) print(f)
def add_nulls(self): with self.doc: dtg.h2("Null tests", id='nulls') lst = dtg.ul() sorter = self.s_null.sortTracers() # All cross-correlations xcorrs = np.array(["%d_%d" % (s[0], s[1]) for s in sorter]) # Unique cross-correlations xc_un = np.unique(xcorrs) cls_null = self.s_null.mean.vector err_null = np.sqrt(self.s_null.precision.getCovarianceMatrix()) # Loop over unique correlations for comb in xc_un: t1, t2 = comb.split('_') t1 = int(t1) t2 = int(t2) # Find all power spectra for this pair of tracers ind_spectra = np.where(xcorrs == comb)[0] # Plot title title = self.s_null.tracers[t1].name[2:-1] title += " x " title += self.s_null.tracers[t2].name[2:-1] # Plot file fname = self.get_output('plots') + '/cls_null_' fname += self.s_null.tracers[t1].name[2:-1] fname += "_x_" fname += self.s_null.tracers[t2].name[2:-1] fname += ".png" print(fname) # Plot all power spectra plt.figure() plt.title(title, fontsize=15) for ind in ind_spectra: typ = sorter[ind][2].decode() ndx = sorter[ind][4] plt.errorbar(self.ells[self.msk], (cls_null[ndx] / err_null[ndx])[self.msk], yerr=np.ones(len(ndx))[self.msk], fmt=self.cols_typ[typ] + '-', label=typ) plt.xlabel('$\\ell$', fontsize=15) plt.ylabel('$C_\\ell/\\sigma_\\ell$', fontsize=15) plt.legend() plt.savefig(fname, bbox_index='tight') plt.close() lst += dtg.li(dtg.a(title, href=fname)) dtg.div(dtg.a('Back to TOC', href='#contents'))
def dominate_wrong_information_page(): """ 第五頁:資料庫連接錯誤頁面,對應到 @app.route('/entered') 及其函數 eneter_success() 目標:利用dominate寫出homepage的html並在templates資料夾中存成index5.html 分為三個區塊 doc = dominate.document() with doc.head (包含css的style;meta確保中文可以運行在utf-8下) with doc.body (包含 words and a button) 最後寫入文件中(在templates資料夾中存成index5.html) """ doc = dominate.document(title='error_page') with doc.head: tags.meta(name='charset', content="utf-8") tags.style("""\ body { background-color: #F9F8F1; color: #2C232A; font-family: sans-serif; font-size: 30; text-align: center; } section{ width: 300px; height: 300px; position: absolute; top: 50%; left: 50%; overflow: auto; text-align: center; margin-left:-150px; margin-top:-150px; } """) with doc.body: with tags.section(): with tags.div(cls='headline', style='font-size: 30;'): tags.h2("wrong information! please try again") tags.input(type='button', value='return back', onclick="location.href='http://127.0.0.1:5000/'", style="width:120px; background-color:pink; font-size: 14;") fn = 'templates/index6.html' with open(file=fn, mode='w', encoding='utf-8') as f: f.write(doc.render()) print(f)
def create_html(items: list) -> document: """ convert article data in html format """ html_document = document(title='Dominate your HTML') log.info('Start make html format') for item in items: item = printers.prepare_one_item(item) with html_document: with div(): h2("Title: " + item['Title:']) p("Link: " + item['Link: ']) img(src=item['Media content:\n']) p("Description: " + item['Description: ']) p("Date: " + item['Date:']) return html_document
def __init__(self, subtitle=''): self.doc = dominate.document(self.site_name) self.subtitle = subtitle if subtitle else self.__class__.__name__ self.on_ready_scriptage = [] with self.doc.head: for css in self.cssfiles.split(): self._link_css(css) for scripturl in self.scripturls: tags.script(crossorigin="anonymous", src=scripturl) self.script_list = tags.script().children with self.doc.body.add(tags.div(cls="container")): self.header = tags.div(id="header") with self.header.add(tags.h2()): tags.a(self.site_name, href='/', id="site_name") tags.h3(self.subtitle, id="subtitle") with tags.ul(id="status", style=self.status_style): for msg in flask.get_flashed_messages(): tags.li(msg) self.content = tags.div(id="content") self.footer = tags.div(id="footer") with self.footer: tags.a("Latest", href=url_for("list_latest")) tags.a("Back to the Front", href="/") tags.a("Catalog", href=url_for("show_catalog_page"), onclick="shift_edit(event, this)") tags.a("Register", href=url_for('loginbp.new_user')) tags.label("") if flask_login.current_user.is_authenticated: tags.a(f"Log out", href=url_for('loginbp.logout')) else: tags.a(f"Login", href=url_for('loginbp.login'))
def generateStatsHTML(graph,statsFilePath = "stats.html",postStatsFilePath = "postStats.html"): #Generates the Stats HTML section firstLevel = checkFirstLevel(graph) softwareLabelNum = queryVersionNum(graph) softwareLabelNumList = addQueryToList(softwareLabelNum) stats = document(title="FSL Viewer") #Creates initial html page (stats) stats += h1("Sample FSL Viewer") stats += ul(li(a("Stats", href="stats.html")), li("-"),li(a("Post Stats", href = "postStats.html"))) stats += h2("Stats") stats += hr() stats += h3("Analysis Methods") if askSpm(graph) == True: #Checks if SPM was used stats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/)." % softwareLabelNumList[1]) elif askFsl(graph) == True: #Checks if FSL was used fslFeatVersion = queryFslFeatVersion(graph) stats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl)." % (fslFeatVersion[0], softwareLabelNumList[1])) stats += hr() stats += h3("Design Matrix") designMatrixLocation = queryDesignMatrixLocation(graph) stats += a(img(src = designMatrixLocation[1], style = "border:5px solid black", border = 0), href = designMatrixLocation[0]) #Adds design matrix image (as a link) to html page statsFile = open(statsFilePath, "x") print(stats, file = statsFile) #Prints html page to a file statsFile.close()
def create_page(self): # Open plots directory if not os.path.isdir(self.get_output('plots')): os.mkdir(self.get_output('plots')) # Create HTML page self.doc = dom.document(title='BBPipe plots page') with self.doc.head: dtg.link(rel='stylesheet', href='style.css') dtg.script(type='text/javascript', src='script.js') with self.doc: dtg.h1("Pipeline outputs") dtg.h2("Contents:", id='contents') lst = dtg.ul() lst += dtg.li(dtg.a('Bandpasses', href='#bandpasses')) lst += dtg.li(dtg.a('Coadded power spectra', href='#coadded')) lst += dtg.li(dtg.a('Null tests', href='#nulls')) lst += dtg.li(dtg.a('Likelihood', href='#like'))
def test_file_structure(self): c = Converter('Man', file='structured_file.man') c.translate() text = c.html.render() text = c.change_special_symbols(text) doc = tags.html(lang='en') doc = add_head(doc) doc_body = tags.body() row = tags.div(cls='row') row = add_row(row, 'BASH(1)', '', 'BASH(1)') doc_body.add(row) with doc_body: tags.h2('NAME') content = tags.div(cls='content') paragraph = tags.p() paragraph += '\ngrep, egrep, fgrep, rgrep' content.add(paragraph) content.add(tags.h4('Simple Commands')) content2 = tags.div(cls='content') content2.add(tags.br()) paragraph = tags.p() paragraph += '\nA \\fIsimple command\\fP' content2.add(paragraph) def_list = tags.dl() def_termin = tags.dt() def_termin.add('\nInterpret') def_list.add(def_termin) def_list.add(tags.dd(cls='indent')) content2.add(def_list) def_list = tags.dl() def_termin = tags.dt(cls='short') def_termin.add((tags.b('%%'))) def_list.add(def_termin) def_def = tags.dd(cls='indent') def_def.add('\nA literal') def_list.add(def_def) content2.add(def_list) content.add(content2) row = tags.div(cls='row') row = add_row(row, 'GNU Bash 4.4', '2016-08-26', 'BASH(1)') doc_body.add(row) doc.add(doc_body) doc = c.change_special_symbols(doc.render()) self.assertEqual(doc, text)
def webpageContent(self): """ Make some HTML for the webpage. """ return div( h2("Analysis"), h3(f"Pagerank"), p(self.formatPageRank()), # p(self.formatKEdges()), id="analysis")
def write_date(doc: dominate.document): """ Write date in HTML document :param doc: Dominate document """ now = datetime.datetime.now() locale.setlocale(locale.LC_ALL, 'fr-FR') doc.add( tags.h2( str(time.strftime('%A %d %B %Y', now.timetuple())).capitalize()))
def gen_report_complex_with_files(datadir: Path, single_file: bool = False, local_report: bool = False) -> dp.Report: # Asset tests lis = [1, 2, 3] small_df = gen_df() big_df = gen_df(10000) # text # md_block html_block = dp.HTML(html="<h1>Hello World</h1>") html_block_1 = dp.HTML(html=h2("Hello World")) code_block = dp.Code(code="print('hello')", language="python") formula_block = dp.Formula(formula=r"\frac{1}{\sqrt{x^2 + 1}}") big_number = dp.BigNumber(heading="Tests written", value=1234) big_number_1 = dp.BigNumber(heading="Real Tests written :)", value=11, change=2, is_upward_change=True) embed_block = dp.Embed(url="https://www.youtube.com/watch?v=JDe14ulcfLA") # assets plot_asset = dp.Plot(data=gen_plot(), caption="Plot Asset") list_asset = dp.File(data=lis, filename="List Asset", is_json=True) img_asset = dp.File(file=datadir / "datapane-logo.png") # tables table_asset = dp.Table(data=small_df, caption="Test Basic Table") # local reports don't support DataTable dt_asset = table_asset if local_report else dp.DataTable( df=big_df, caption="Test DataTable") if single_file: return dp.Report(dp.Group(blocks=[md_block, dt_asset])) else: return dp.Report( dp.Page( dp.Select(md_block, html_block, html_block_1, code_block, formula_block, embed_block, type=dp.SelectType.TABS), dp.Group(big_number, big_number_1, columns=2), ), dp.Page( plot_asset, list_asset, img_asset, table_asset, dt_asset, ), )
def add_bandpasses(self): with self.doc: dtg.h2("Bandpasses", id='bandpasses') lst = dtg.ul() # Overall plot title = 'Bandpasses summary' fname = self.get_output('plots') + '/bpass_summary.png' plt.figure() plt.title(title, fontsize=14) for t in self.s_fid.tracers: n = t.name[2:-1] nu_mean = np.sum(t.Nz * t.z**3 * t.extra_cols['dnu']) / np.sum( t.Nz * t.z**2 * t.extra_cols['dnu']) plt.plot( t.z, t.Nz / np.amax(t.Nz), label=n + ', $\\langle\\nu\\rangle=%.1lf\\,{\\rm GHz}$' % nu_mean) plt.xlabel('$\\nu\\,[{\\rm GHz}]$', fontsize=14) plt.ylabel('Transmission', fontsize=14) plt.ylim([0., 1.3]) plt.legend(frameon=0, ncol=2, labelspacing=0.1, loc='upper left') plt.xscale('log') plt.savefig(fname, bbox_inches='tight') plt.close() lst += dtg.li(dtg.a(title, href=fname)) for t in self.s_fid.tracers: n = t.name[2:-1] title = 'Bandpass ' + n fname = self.get_output('plots') + '/bpass_' + n + '.png' plt.figure() plt.title(title, fontsize=14) plt.plot(t.z, t.Nz / np.amax(t.Nz)) plt.xlabel('$\\nu\\,[{\\rm GHz}]$', fontsize=14) plt.ylabel('Transmission', fontsize=14) plt.ylim([0., 1.05]) plt.savefig(fname, bbox_inches='tight') plt.close() lst += dtg.li(dtg.a(title, href=fname)) dtg.div(dtg.a('Back to TOC', href='#contents'))
def index(): removed = list((REPORTS_PATH / "removed").iterdir()) added = list((REPORTS_PATH / "added").iterdir()) diff = list((REPORTS_PATH / "diff").iterdir()) title = "UI changes from master" doc = dominate.document(title=title) with doc: h1("UI changes from master") hr() h2("Removed:", style="color: red;") i("UI fixtures that have been removed:") html.report_links(removed, REPORTS_PATH) br() hr() h2("Added:", style="color: green;") i("UI fixtures that have been added:") html.report_links(added, REPORTS_PATH) br() hr() h2("Differs:", style="color: grey;") i("UI fixtures that have been modified:") html.report_links(diff, REPORTS_PATH) return html.write(REPORTS_PATH, doc, "index.html")
def index() -> Path: passed_tests = list((REPORTS_PATH / "passed").iterdir()) failed_tests = list((REPORTS_PATH / "failed").iterdir()) title = "UI Test report " + datetime.now().strftime("%Y-%m-%d %H:%M:%S") doc = document(title=title, index=True) with doc: h1("UI Test report") if not failed_tests: p("All tests succeeded!", style="color: green; font-weight: bold;") else: p("Some tests failed!", style="color: red; font-weight: bold;") hr() h2("Failed", style="color: red;") with p(id="file-hint"): strong("Tip:") text(" use ") t.span("./tests/show_results.sh", style="font-family: monospace") text(" to enable smart features.") with div("Test colors", _class="script-hidden"): with t.ul(): with t.li(): t.span("new", style="color: blue") t.button("clear all", onclick="resetState('all')") with t.li(): t.span("marked OK", style="color: grey") t.button("clear", onclick="resetState('ok')") with t.li(): t.span("marked BAD", style="color: darkred") t.button("clear", onclick="resetState('bad')") html.report_links(failed_tests, REPORTS_PATH, ACTUAL_HASHES) h2("Passed", style="color: green;") html.report_links(passed_tests, REPORTS_PATH) return html.write(REPORTS_PATH, doc, "index.html")
def _render_response(resp): with H.section(): with H.div(_class=u'message-display'): with H.h2(), H.code(): # Status line # See above regarding spaces. if resp.version: H.span(printable(resp.version), **_for_object(resp.version)) with H.span(**_for_object(resp.status)): _render_known(resp.status) H.span(printable(find_reason_phrase(resp))) _render_message(resp) # Headers, body and all that _render_complaints(resp)
def index(): passed_tests = list((REPORTS_PATH / "passed").iterdir()) failed_tests = list((REPORTS_PATH / "failed").iterdir()) title = "UI Test report " + datetime.now().strftime("%Y-%m-%d %H:%M:%S") doc = dominate.document(title=title) with doc: h1("UI Test report") if not failed_tests: p("All tests succeeded!", style="color: green; font-weight: bold;") else: p("Some tests failed!", style="color: red; font-weight: bold;") hr() h2("Failed", style="color: red;") html.report_links(failed_tests, REPORTS_PATH) h2("Passed", style="color: green;") html.report_links(passed_tests, REPORTS_PATH) return html.write(REPORTS_PATH, doc, "index.html")
def generate_html_report(html, recipients, message): current_time = time.strftime('%d/%m/%Y') if not message: message = f"Daily test results for {current_time}" subject = f"Execution Results {current_time}" else: subject = message with dominate.document(title='Test Report') as doc: tags.html(tags.h2("Greetings,")) tags.html(tags.h3(f"{message} (attached)")) doc = str(doc) send_mail(send_to=recipients, subject=subject, message=doc, payload=html) return html
def _render_response(resp): with H.section(): with H.div(_class=u'message-display'): if resp.remark: H.p(printable(resp.remark), _class=u'message-remark') with H.h2(), H.code(): # Status line # See above regarding spaces. if resp.version: H.span(printable(resp.version), **_for_object(resp.version)) with H.span(**_for_object(resp.status)): _render_known(resp.status) H.span(printable(find_reason_phrase(resp))) _render_message(resp) # Headers, body and all that _render_complaints(resp)
def _render_request(req): with H.section(): with H.div(_class=u'message-display'): with H.h2(), H.code(): # Request line # We don't insert spaces here because we assume that # Dominate will render each element on its own line, # thus implicitly creating whitespace. # https://github.com/Knio/dominate/issues/68 with H.span(**_for_object(req.method)): _render_known(req.method) H.span(printable(req.target), **_for_object(req.target)) if req.version: H.span(printable(req.version), **_for_object(req.version)) _render_message(req) # Headers, body and all that _render_complaints(req)
def _render_request(req): with H.section(): with H.div(_class=u'message-display'): with H.h2(), H.code(): # Request line # We don't insert spaces here because, # without ``__pretty=False``, # Dominate renders each element on its own line, # thus implicitly creating whitespace. with H.span(**_for_object(req.method)): _render_known(req.method) H.span(printable(req.target), **_for_object(req.target)) if req.version: H.span(printable(req.version), **_for_object(req.version)) _render_message(req) # Headers, body and all that _render_complaints(req)
def add_nulls(self): with self.doc: dtg.h2("Null tests", id='nulls') lst = dtg.ul() pols = ['e', 'b'] for t1, t2 in self.s_null.get_tracer_combinations(): title = f"{t1} x {t2}" fname = self.get_output('plots') + '/cls_null_' fname += f"{t1}_x_{t2}.png" print(fname) plt.figure() plt.title(title, fontsize=15) for p1 in range(2): for p2 in range(2): x = pols[p1] + pols[p2] typ = 'cl_' + x l, cl, cv = self.s_null.get_ell_cl(typ, t1, t2, return_cov=True) msk = l < self.lmx el = np.sqrt(np.fabs(np.diag(cv)))[msk] plt.errorbar(l[msk], cl[msk] / el, yerr=np.ones_like(el), fmt=self.cols_typ[x] + '-', label=x) plt.xlabel('$\\ell$', fontsize=15) plt.ylabel('$C_\\ell/\\sigma_\\ell$', fontsize=15) plt.legend() plt.savefig(fname, bbox_index='tight') plt.close() lst += dtg.li(dtg.a(title, href=fname)) dtg.div(dtg.a('Back to TOC', href='#contents'))
def courseTextContent(analysis): """ Make a list of courses and their assigned texts. """ intro = div( h2("Course-Text Graph"), p("This graph shows courses that teach data ethics, and the required texts scraped from those courses' syllabi." ), _class="intro") container = div(id="mynetwork") loadingBar = div(div(div("0%", id="text"), div(div(id="bar"), id="border"), _class="outerBorder"), id="loadingBar") return (intro, container, loadingBar, analysis, courseTextList())
def uniCourseContent(analysis): """ Make a list of universities and their courses. """ intro = div( h2("University-Course Graph"), p("This graph shows courses that teach data ethics, and the universities in which those courses are taught." ), _class="intro") container = div(id="mynetwork") loadingBar = div(div(div("0%", id="text"), div(div(id="bar"), id="border"), _class="outerBorder"), id="loadingBar") return (intro, container, loadingBar, analysis, uniCourseList())
def _render_response(resp): with H.section(): with H.div(_class=u'message-display'): if resp.remark: H.p(printable(resp.remark), _class=u'message-remark') with H.h2(), H.code(): # Status line # See above regarding spaces. if resp.version: H.span(printable(resp.version), **_for_object(resp.version)) # httpolice-devtool (the Chrome extension) relies # on the ``StatusCode`` class. Avoid breaking it, at least # as long as it doesn't inconvenience HTTPolice itself. with H.span(**_for_object(resp.status, u'StatusCode')): _render_known(resp.status) text_node(u' ' + printable(find_reason_phrase(resp))) _render_message(resp) # Headers, body and all that _render_complaints(resp)
def generatePostStatsHTML(graph,statsFilePath = "stats.html",postStatsFilePath = "postStats.html"): #Generates Post-Stats page voxelWise = checkHeightThreshold(graph) clusterWise = checkExtentThreshold(graph) softwareLabelNum = queryVersionNum(graph) softwareLabelNumList = addQueryToList(softwareLabelNum) statisticType = queryStatisticType(graph) statisticType = statisticImage(statisticType[0]) statisticTypeString = statisticImageString(statisticType) contrastName = queryContrastName(graph) statisticMapImage = queryExcursionSetMap(graph) postStats = document(title="FSL Viewer") #Creates initial HTML page (Post Stats) postStats += h1("Sample FSL Viewer") postStats += ul(li(a("Stats", href="stats.html")), li("-"),li(a("Post Stats", href = "postStats.html"))) postStats += h2("Post-stats") postStats += hr() postStats += h3("Analysis Methods") if voxelWise == True: #If main threshold is Height Threshold mainThreshValue = queryHeightThresholdValue(graph) if askSpm(graph) == True: postStats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/). %s statistic images were thresholded at P = %s (corrected)" % (softwareLabelNumList[1], statisticTypeString, mainThreshValue[0])) elif askFsl(graph) == True: fslFeatVersion = queryFslFeatVersion(graph) postStats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl)." "%s statistic images were thresholded at P = %s (corrected)" %(fslFeatVersion[0], softwareLabelNumList[1], statisticTypeString, mainThreshValue[0])) elif clusterWise == True: #If main threshold is extent threshold mainThreshValue = queryClusterThresholdValue(graph) heightThreshValue = queryUHeightThresholdValue(graph) clusterThreshType = clusterFormingThreshType(graph, statisticType) if askSpm(graph) == True: postStats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/). %s statistic images were thresholded using clusters determined by %s > %s and a (corrected) " "cluster significance of P = %s " % (softwareLabelNumList[1], statisticTypeString, clusterThreshType, heightThreshValue[0], mainThreshValue[0])) elif askFsl(graph) == True: fslFeatVersion = queryFslFeatVersion(graph) postStats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl). %s statistic images were thresholded " "using clusters determined by %s > %s and a (corrected) cluster significance of P = %s" %(fslFeatVersion[0], softwareLabelNumList[1], statisticTypeString, clusterThreshType, heightThreshValue[0], mainThreshValue[0])) else: #If there is no corrected threshold - assume voxel wise mainThreshValue = queryUHeightThresholdValue(graph) if askSpm(graph) == True and askIfPValueUncorrected(graph) == True: #SPM used and threshold type is nidm_PValueUncorrected postStats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/). %s statistic images were thresholded at P = %s (uncorrected)" % (softwareLabelNumList[1], statisticTypeString, mainThreshValue[0])) elif askSpm(graph) == True and askIfOboStatistic(graph) == True: #SPM used and threshold type is obo_statistic postStats += p("FMRI data processing was carried out using SPM Version %s (SPM, http://www.fil.ion.ucl.ac.uk/spm/). %s statistic images were thresholded at %s = %s (uncorrected)" % (softwareLabelNumList[1], statisticTypeString, statisticType, mainThreshValue[0])) elif askFsl(graph) == True and askIfPValueUncorrected(graph) == True: fslFeatVersion = queryFslFeatVersion(graph) postStats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl)." "%s statistic images were thresholded at P = %s (uncorrected)." % (fslFeatVersion[0], softwareLabelNumList[1], statisticTypeString, mainThreshValue[0])) elif askFsl(graph) == True and askIfOboStatistic(graph) == True: fslFeatVersion = queryFslFeatVersion(graph) postStats += p("FMRI data processing was carried out using FEAT (FMRI Expert Analysis Tool) Version %s, part of FSL %s (FMRIB's Software Library, www.fmrib.ox.ac.uk/fsl)." "%s statistic images were thresholded at %s = %s (uncorrected)." % (fslFeatVersion[0], softwareLabelNumList[1], statisticTypeString, statisticType, mainThreshValue[0])) postStats += hr() postStats += h3("Thresholded Activation Images") postStats += hr() i = 0 if askFsl(graph) == True: while i < len(contrastName): postStats += p("%s" % contrastName[i]) postStats += img(src = statisticMapImage[i]) i = i + 1 postStatsFile = open(postStatsFilePath, "x") print(postStats, file = postStatsFile) postStatsFile.close()