Ejemplo n.º 1
0
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()
Ejemplo n.º 2
0
 def add_header(self, text):
     """Insert a header to the HTML file
     Parameters:
         text (str) -- the header text
     """
     with self.doc:
         h3(text)
Ejemplo n.º 3
0
    def output_intro(self):
        """Output introductory section"""

        tags.h3("Algorithm Support comparison results")
        tags.p("This module compares Java Card "
               "algorithm support between the cards.")
        tags.p("To learn more about testing methodology, visit:")
        tags.a("https://www.fi.muni.cz/~xsvenda/jcalgtest/table.html",
               href="https://www.fi.muni.cz/~xsvenda/jcalgtest/table.html")
        tags.h4("Overview:")
        tags.p(
            "The cards match in " + str(len(self.matching)) + " algorithms."
        )
        tags.p(
            "There are " + str(len(self.missing)) +
            " algorithms with missing results for either card."
        )
        tags.p(
            "There are " + str(len(self.support_mismatch)) +
            " algorithms with different results."
        )
        mem_mismatch = len(self.memory_mismatch) + len(self.reset_mismatch) \
            + len(self.deselect_mismatch)
        tags.p(
            "There are " + str(mem_mismatch) +
            " algorithms with suspicious differences in memory allocation."
        )
Ejemplo n.º 4
0
    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'))
Ejemplo n.º 5
0
 def add_header(self, str):
     if self.is_test:
         with self.doc:
             h3(str)
     else:
         with self.edoc:
             h3(str)
Ejemplo n.º 6
0
    def output_intro(self):
        """Output introductory section"""

        tags.h3("Algorithm Performance comparison results")
        tags.p("This module compares Java Card "
               "algorithm performance between the cards.")
        tags.p("To learn more about testing methodology, visit")
        tags.a(
            "https://www.fi.muni.cz/~xsvenda/jcalgtest/knowledgebase.html",
            href="https://www.fi.muni.cz/~xsvenda/jcalgtest/knowledgebase.html"
        )
        tags.h4("Overview:")
        tags.p(
            "The cards' performance match in " +
            str(len(self.matching)) + " algorithms."
        )
        tags.p(
            "There are " + str(len(self.missing)) +
            " algorithms with missing results for either card."
        )
        tags.p(
            "There are " + str(len(self.mismatch)) +
            " algorithms with different results."
        )
        tags.p(
            "There are " + str(len(self.erroneous)) +
            " algorithms that failed with different error message."
        )
        tags.p(
            str(len(self.skipped)) +
            " algorithms were omitted due to being too fast in general."
        )
Ejemplo n.º 7
0
    def add_header(self, text):
        """"""
        """ insert head text to html

        args:
            text (str) -- header text
        """
        with self.doc:
            h3(text)
Ejemplo n.º 8
0
 def add_header(self, text, im):
     """Insert a header to the HTML file
     Parameters:
         text (str) -- the header text
     """
     with self.doc:
         h3(text)
         with a(href=im):
             img(style="width:1024px", src=im)
def main(argv):
  # Authenticate and construct service.
  service, flags = sample_tools.init(
      argv,
      'androidpublisher',
      'v2',
      __doc__,
      __file__,
      parents=[argparser],
      scope='https://www.googleapis.com/auth/androidpublisher')

  # Process flags and read their values.
  package_name = flags.package_name

  try:

    edit_request = service.edits().insert(body={}, packageName=package_name)
    result = edit_request.execute()
    edit_id = result['id']

    apks_result = service.edits().apks().list(
        editId=edit_id, packageName=package_name).execute()

    version_codes = [apk['versionCode'] for apk in apks_result['apks']]

    doc = dominate.document(title="Build Up The Base! Changelog")
    with doc.head:
        tags.script(type='text/javascript', src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js')
        tags.link(rel='stylesheet', href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css')
        tags.script(type='text/javascript', src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js')
        tags.script("""
        $(function(){
            $('#change_log').accordion();
        });
        """,type='text/javascript')

    with doc:
        with tags.div(id="change_log"):
            for version in version_codes[::-1]:
                listings_result = service.edits().apklistings().list(
                        editId=edit_id, packageName=package_name, apkVersionCode=version
                    ).execute()

                tags.h3("VERSION %s" % version, id="version_%s"%version)
                with tags.div():
                    if 'listings' in listings_result:
                        for line in  listings_result['listings'][0]['recentChanges'].splitlines():
                            tags.div(line)
                    else:
                        tags.div("No listing found")

    print doc

  except client.AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
Ejemplo n.º 10
0
def make_email_body(issues):
    title = 'BETA:\nPlease update, close or change the priority of the following issues so your team knows what is going on.'
    d = dominate.document(title=title)
    with d.body:
        h3(title)
        with table(border='1', width='1024', cellpadding='10').add(tbody()):
            report.make_table_header()
            decorated_issues = report.build_decorated_issues(issues)
            decorated_issues.sort(key=lambda issue: issue.priority)
            for decorated_issue in decorated_issues:
                report.make_table_row(decorated_issue)
    return str(d)
Ejemplo n.º 11
0
 def add_text_sep(self, txts, width=400):
     self.add_table()
     with self.t:
         with tr():
             for txt in txts:
                 with td(style="word-wrap: break-word;",
                         halign="center",
                         valign="top"):
                     with p(style="width:%dpx" % width):
                         splitted = txt.split(',')
                         if len(splitted) > 1:
                             for h in splitted:
                                 p(h3(h))
                         else:
                             p(h3(txt))
Ejemplo n.º 12
0
    def _add_item(self, pocket_item: PocketItem) -> None:
        """Add a pocket item to the HTML report page

        Args:
            pocket_item (PocketItem):

        Returns:
            None
        """
        self.doc.add(tags.h3(pocket_item.title, cls="defaultfontfamily"))

        # Add bullets
        pocket_item_description = tags.ul()

        pocket_item_description += tags.li(
            "Link: ",
            tags.a(pocket_item.url, href=pocket_item.url),
            cls="defaultfontfamily",
        )
        pocket_item_description += tags.li(
            "Tags: ",
            ", ".join([elem for elem in pocket_item.tags]),
            cls="defaultfontfamily",
        )
        pocket_item_description += tags.li(
            "Time added: ",
            pocket_item.convert_datetime_to_string(pocket_item.time_added),
            cls="defaultfontfamily",
        )

        self.doc.add(pocket_item_description)
Ejemplo n.º 13
0
    def project_html(self, ref_name, prof_name):

        tags.h3("ATR comparison results")
        tags.p("This module compares ATR of the smart cards "
               "and searches database of known smart cards "
               "for additional information.")

        tags.h4("ATR:")
        table([[ref_name + " (reference)", self.ref_atr],
               [prof_name + " (profiled)", self.prof_atr]],
              header=["Card", "ATR"])

        if self.ref_atr == self.prof_atr:
            tags.p("The ATR of tested card matches the reference. "
                   "This would suggest the same smart card model.")
        else:
            tags.p("The ATR of tested card does not match the reference. "
                   "This would suggest different smart card models.")

        tags.h4("Additional info from smart card database")

        tags.p("This information was taken from database of known "
               "smart cards, distributed under GNU GPLv2.")
        tags.p("For complete list, check:")
        tags.a(config.URL.SMARTCARD_LIST, href=config.URL.SMARTCARD_LIST)

        if self.ref_info:
            tags.p("The reference card (" + ref_name +
                   ") was found in the database:")
            with tags.div():
                for i in self.ref_info:
                    tags.p(i)
        else:
            tags.p("The reference card (" + ref_name +
                   ") was not found in the database.")
        if self.prof_info:
            tags.p("The profiled card (" + prof_name +
                   ") was found in the database:")
            with tags.div():
                for i in self.prof_info:
                    tags.p(i)
        else:
            tags.p("The profiled card (" + prof_name +
                   ") was not found in the database.")
Ejemplo n.º 14
0
 def add_text(self, txts, width=400):
     self.add_table()
     with self.t:
         with tr():
             for txt in txts:
                 with td(style="word-wrap: break-word;",
                         halign="center",
                         valign="top"):
                     with p(style="width:%dpx" % width):
                         p(h3(txt))
Ejemplo n.º 15
0
 def webpageContent(self):
     """
     Make some HTML for the webpage.
     """
     return div(
         h2("Analysis"),
         h3(f"Pagerank"),
         p(self.formatPageRank()),
         # p(self.formatKEdges()),
         id="analysis")
Ejemplo n.º 16
0
def write_ephemeris(doc: dominate.document):
    """
    Write ephemeris in HTML document
    :param doc: Dominate document
    """
    ephemeris = Ephemeris('data\\ephemeris-fr.json')
    today_eph = ephemeris.get_today_ephemeris()
    string_eph = today_eph[1] + ' ' + today_eph[0] if today_eph[
        1] else today_eph[0]
    doc.add(tags.h3(string_eph))
Ejemplo n.º 17
0
 def __init__(self, vids, *args, **kwargs):
     kwargs.setdefault('order', [[2, "asc"]])
     super().__init__(*args, **kwargs)
     with self.head:
         tags.th("Date", _class="dt-head-left")
         tags.th("Series", _class="dt-head-left")
         tags.th("Lesson", _class="dt-head-left")
         tags.th("Duration", _class="dt-head-left")
     with self.body:
         if len(vids) == 0:
             tags.h3("No connection to videos, try again later...")
         else:
             for vid in vids:
                 try:
                     if vid in vid.series.videos:
                         self._make_table_row(vid)
                 except Exception as e:
                     print(f"Removing {vid.name} because: {e}")
                     vid.delete()
Ejemplo n.º 18
0
    def project_html(self, ref_name: str, prof_name: str) -> None:
        tags.h3("CPLC comparison results")
        tags.p("This module compares CPLC of smart cards. "
               "Bear in mind that the CPLC data is static and could be faked. "
               "Therefore, matching result does not guarantee match. "
               "However, mismatch in CPLC data is highly suspicious.")

        tags.h4("CPLC:")

        if self.get_state() == ContrastState.MATCH:
            tags.p("CPLC data seems to match between cards.")
        elif self.get_state() == ContrastState.WARN:
            tags.p("There are missing CPLC fields in results for one of the "
                   "cards. This could be due to error in measurement, but "
                   "it could suggest suspicious difference.")
        else:
            tags.p("There are differences in CPLC fields. The cards probably "
                   "don't match, or differ in hardware or software revision.")

        self.output_table(ref_name, prof_name)
Ejemplo n.º 19
0
def render_summary(repo: Path, digest: Changes[Any], rendered: Path) -> Path:
    rtype = get_result_type(repo)  # TODO ??
    # ODO just get trait for type??

    Cumulative = CumulativeBase.for_(rtype)

    NOW = datetime.now()
    name = repo.stem

    everything = flatten([ch for ch in digest.changes.values()])

    before = len(everything)

    grouped = group_by_key(everything, key=Cumulative.cumkey)
    print(f'before: {before}, after: {len(grouped)}')

    cumulatives = list(map(Cumulative, grouped.values()))
    cumulatives = list(sorted(cumulatives, key=Cumulative.sortkey))

    doc = dominate.document(
        title=f'axol results for {name}, rendered at {fdate(NOW)}')
    with doc.head:
        T.style(STYLE)
        raw_script(JS)
    with doc:
        T.h3("This is axol search summary")
        T.div(
            "You can use 'hide' function in JS (chrome debugger) to hide certain tags/subreddits/users"
        )
        T.h4("Sources summary")
        # TODO wrap in div?
        with T.div():
            Cumulative.sources_summary(everything)
        for cc in cumulatives:
            T.div(cc.format(), cls='item')

    rendered.mkdir(exist_ok=True, parents=True)
    sf = rendered.joinpath(name + '.html')
    with sf.open('w') as fo:
        fo.write(str(doc))
    return sf
Ejemplo n.º 20
0
def _notice_to_html(the_notice, ctx, with_anchor=False):
    anchor = {'id': six.text_type(the_notice.id)} if with_anchor else {}
    with H.div(_class=u'notice %s' % the_notice.severity, **anchor):
        with H.h3():
            # See above regarding spaces.
            H.abbr(the_notice.severity_short, _class=u'severity',
                   title=the_notice.severity)
            H.span(six.text_type(the_notice.id), _class=u'ident')
            with H.span():
                _piece_to_html(the_notice.title, ctx)
        for piece in the_notice.explanation:
            _piece_to_html(piece, ctx)
Ejemplo n.º 21
0
    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()
Ejemplo n.º 22
0
    def get_html_string(style: Style) -> document:
        """Creates a HTML string for generating the summary file."""
        utc_time = datetime.datetime.utcfromtimestamp(style.timestamp)
        style_attributes = [
            ('code', style.code),
            ('number', style.number),
            ('precinct', style.precinct),
            ('built at', f'{utc_time.strftime("%Y-%m-%d %H:%M:%S")}'),
            ('built from number of ballots', style.build_from_count),
        ]

        script_abs_path = os.path.abspath('assets/copy_to_clipboard.js')
        version = utils.show_version()
        doc = document(title='Audit Engine version: ' + version)
        with doc.head:
            link(
                rel='stylesheet',
                href=
                'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css',
                integrity=
                "sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T",
                crossorigin="anonymous",
            )
            script(type='text/javascript', src=script_abs_path)

        with doc:
            with div(cls='container'):
                with div(cls='jumbotron'):
                    h1('Audit Engine: {version} - style summary'.format(
                        version=version))
                    build_time = datetime.datetime.now(datetime.timezone.utc)
                    p(f'Summary built at: {build_time.strftime("%Y-%m-%d %H:%M:%S")}',
                      cls='lead')
                with div(cls='col pl-3 mt-1') as style_details_column:
                    for style_key, style_value in style_attributes:
                        style_details_column.add(
                            StyleSummary.get_details_row(
                                style_key, str(style_value)))
                h3('Contests', cls='mb-0 mt-1')
                with div(cls='col pl-3') as contest_details_column:
                    for style_contest in style.contests:
                        contest_details_column.add(
                            StyleSummary.get_contest_details(style_contest))
                h3('Built from ballots', cls='mb-3 mt-1')
                with div(cls='col pl-3'):
                    with div(cls='row flex-wrap') as images_column:
                        for ballot_id in style.build_from_ballots:
                            images = StyleSummary.get_ballot_images_path(
                                ballot_id, style.code)
                            images_column.add(
                                StyleSummary.get_ballot_images_div(
                                    ballot_id, images))
                h3('Style weighted images', cls='mb-3 mt-1')
                with div():
                    for image in StyleSummary.get_style_images(style.code):
                        a(img(src=os.path.basename(image),
                              cls='img-thumbnail',
                              alt='File not found'),
                          href=image)
        return doc
Ejemplo n.º 23
0
def _notice_to_html(the_notice, ctx, with_anchor=False):
    anchor = {'id': str(the_notice.id)} if with_anchor else {}
    with H.div(_class=u'notice %s' % the_notice.severity.name, **anchor):
        with H.h3():
            # See above regarding spaces.
            H.abbr(the_notice.severity_short,
                   _class=u'severity',
                   title=the_notice.severity.name)
            H.span(str(the_notice.id), _class=u'ident')
            with H.span(__pretty=False):
                _piece_to_html(the_notice.title, ctx)
        for piece in the_notice.explanation:
            _piece_to_html(piece, ctx)
Ejemplo n.º 24
0
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
Ejemplo n.º 25
0
    def get_html(self, ):
        """Generates room html"""
        rows = self.get_display_data()

        room_container = div(cls="well", id='room' + str(self.id))
        room_name = h3(self.name, cls="text-center")
        room_container.add(room_name)
        for row in rows:
            r = div(cls='row')
            with r:
                for group in row:
                    div(cls="col-sm-3 group").add(group.get_html())
            room_container.add(r)
        return room_container.render()
Ejemplo n.º 26
0
    def get_html(self, ):
        """Generates room html"""
        rows = self.get_display_data()

        room_container = div(cls = "well", id='room' + str(self.id))
        room_name = h3(self.name, cls="text-center")
        room_container.add(room_name)
        for row in rows:            
            r = div(cls='row')
            with r:
                for group in row:
                    div(cls="col-sm-3 group").add(group.get_html())
            room_container.add(r)
        return room_container.render()
Ejemplo n.º 27
0
def _render_message(msg):
    _render_header_entries(msg.annotated_header_entries)

    body, transforms = _displayable_body(msg)
    if body != u'':
        with H.div(**_for_object(msg.body, u'body-display')):
            if body is None:
                H.h3(u'Body is unknown')
            elif body is Unavailable:
                H.h3(u'Body is present, but not available for inspection')
            else:
                if transforms:
                    H.h3(u'Body after %s' % nicely_join(transforms))
                H.pre(body)

    if msg.trailer_entries:
        with H.div(_class=u'trailer'):
            H.h3(u'Headers from the trailer part')
            _render_header_entries(msg.annotated_trailer_entries)
Ejemplo n.º 28
0
def _render_message(msg):
    _render_header_entries(msg.annotated_header_entries)

    body, transforms = msg.displayable_body
    if body != u'':
        with H.div(**_for_object(msg.displayable_body, u'body-display')):
            if body is None:
                H.h3(u'Body is unknown')
            elif isinstance(body, Unavailable):
                H.h3(u'Body is present, but not available for inspection')
            else:
                if transforms:
                    H.h3(u'Body after %s' % nicely_join(transforms))
                H.pre(body)

    if msg.trailer_entries:
        with H.div(_class=u'trailer'):
            H.h3(u'Headers from the trailer part')
            _render_header_entries(msg.annotated_trailer_entries)
Ejemplo n.º 29
0
 def add_images(self, ims, txts, links, width=400):
     self.add_table()
     with self.t:
         with tr():
             for im, txt, link in zip(ims, txts, links):
                 with td(style="word-wrap: break-word;",
                         halign="center",
                         valign="top"):
                     with p():
                         with a(href=link):
                             img(style="width:%dpx" % width, src=link)
                         br()
                         splitted = txt.split(',')
                         if len(splitted) > 1:
                             for h in splitted:
                                 p(h)
                         else:
                             p(h3(txt))
Ejemplo n.º 30
0
    def index():
        doc = BootstrapDocument()
        # add socket-io client to the doc and our custom js.
        doc.scripts.add(script(
            src='//cdn.socket.io/socket.io-1.4.5.js',
            type='text/javascript'),
            script(src='/static/my.js',
                type='text/javascript'))

        doc.body.children.insert(0, Div(h1('Advanced Example'), 
            Div(h3('Flashes'), Div(id='flashes')))) 
        
        # add buttons below the content of the document
        doc.body.add(Button(
            'Table',
            onclick="user_socket.emit('table');"),
            Button('Form',
                onclick="user_socket.emit('form');"))

        return doc.render()
Ejemplo n.º 31
0
    def save_feed_to_html(self):
        """Creating an html file, using curent datetime as a filename"""
        logging.info('Started saving feed to html file')
        time_now = str(datetime.datetime.now())
        time_for_path = time_now[:-16] + '_' + time_now[
            -15:-13] + '-' + time_now[-12:-10] + '-' + time_now[-9:-7]
        html = dominate.document(title="HTML RSS feed")
        with html.head:
            dtags.meta(charset='utf-8')
        html += dtags.h1(self.feed_name)
        for article_number, article in enumerate(self.articles):
            html += dtags.br()

            date = article.published
            str_date = f'{date.tm_year}/{date.tm_mon}/{date.tm_mday} {date.tm_hour}:{date.tm_min}'

            html += dtags.h2(f'{article_number + 1}.  {article.title}')
            html += dtags.h3(f'   {str_date}')

            html += dtags.a(f'Link: {article.link}')
            html += dtags.br()

            with html:
                if check.internet_connection_check():
                    # if have internet access, downloading images and pasting in a html file
                    for link in article.media:
                        dtags.img(src=link['url'])
                else:
                    # if no, paste links of these images
                    dtags.a('Image links:')
                    for link_number, link in enumerate(article.media):
                        img_url = link['url']
                        dtags.a(f'{link_number + 1}. {img_url}', href=link)
            html += dtags.p(article.summary)
            html += dtags.br()
        with open('html_feeds/' + time_for_path + ' RSS_feeds.html',
                  'w') as html_file:
            html_file.write(str(html))
        logging.info('Finished saving feed to html file')
Ejemplo n.º 32
0
def cli(source_dir, destination):
    root = pathlib.Path(source_dir)
    container = div(id='publications')
    for source in sorted(root.glob('*-*')):
        topic_title = source.name.split('-')[1]
        topic_title = topic_title.replace('_', ' ')
        topic_section = section()
        topic_section.add(h2(topic_title))
        paper_list = ul()
        topic_section.add(paper_list)
        with source.open() as f:
            data = bibtexparser.load(f)
        for entry in data.entries:
            list_item = li()
            paper_list.add(list_item)
            paper_title = h3(entry['title'])
            list_item.add(paper_title)
            authors = p(entry['author'])
            list_item.add(authors)
            if 'journal' in entry:
                journal = p(entry['journal'])
                list_item.add(journal)
        container.add(topic_section)
    destination.write(str(container))
Ejemplo n.º 33
0
def _generate_html_email_body(title: str, new_songs: Iterable[Track],
                              playlist: PlayList) -> str:
    link_style = 'color: #373737;'

    # Generate links to the artists
    artists_spans = []
    for track in new_songs:
        artists = []
        for artist in track['track']['artists']:
            name = artist['name']
            url = '#'
            if ('external_urls' in artist
                    and 'spotify' in artist['external_urls']):
                url = artist['external_urls']['spotify']
                artists.append(a(name, href=url, style=link_style))
            else:
                artists.append(name)
        first = True
        artists_span = span()
        for artist_entry in artists:
            if not first:
                artists_span += ', '
            artists_span += artist_entry
            first = False
        artists_spans.append(artists_span)

    # Generate document
    doc = dominate.document(title=title)
    with doc:
        with div(style=('font-family: arial, serif;border: 1px solid #99ff99; '
                        'padding: 3px; width: 600px; margin: auto; '
                        'background-color: #99ff99;')):
            with table():
                with tr():
                    with td():
                        with a(href=playlist['external_urls']['spotify']):
                            img(src=playlist['images'][0]['url'],
                                width='200px',
                                height='200px')
                    with td(style=('vertical-align: text-top; '
                                   'padding-left: 10px;')):
                        div('New music was added to',
                            style='text-align: center;')
                        with h2():
                            a(playlist['name'],
                              href=playlist['external_urls']['spotify'],
                              style=link_style)
                        h3(playlist['description'],
                           style='text-align: center;')
            hr(size='1', color='black', width='90%')
            div('The following tracks where added:',
                style='margin-top: 10px; margin-bottom: 10px;')

            for track, artists_span in zip(new_songs, artists_spans):
                with table(style=('border: 1px solid black; width:100%; '
                                  'margin-bottom: 10px; font-size: 14px;')):
                    with td(width='100px;', style='width: 100px;'):
                        a(img(src=track['track']['album']['images'][2]['url']),
                          href=track['track']['external_urls']['spotify'])
                    with td():
                        with table():
                            with tr():
                                td('Artist(s):',
                                   style=('text-align: right; '
                                          'padding-right: 5px;'))
                                td(artists_span)
                            with tr():
                                td('Title:',
                                   style='text-align: right; '
                                   'padding-right: 5px;')
                                td(
                                    a(track['track']['name'],
                                      href=track['track']['external_urls']
                                      ['spotify'],
                                      style=link_style))
                            with tr():
                                td('Album:',
                                   style='text-align: right; '
                                   'padding-right: 5px;')
                                td(
                                    a(track['track']['album']['name'],
                                      href=track['track']['album']
                                      ['external_urls']['spotify'],
                                      style=link_style))

    return doc.render(pretty=False)
Ejemplo n.º 34
0
 def add_header(self, str):
     with self.doc:
         h3(str)
Ejemplo n.º 35
0
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()
Ejemplo n.º 36
0
 def append_h3(self, text):
     with self.doc.body:
         h3(text)