Ejemplo n.º 1
0
def makeHtml(path, fileName, sitename, authorname, usecss, usejs):
    doc = dominate.document(title=sitename)

    with doc.head:
        if (usecss.lower() == "y"):
            link(rel='stylesheet', href='style.css')
        if (usejs.lower() == "y"):
            script(type='text/javascript', src='script.js')
        with meta():
            attr(author=authorname)

    with doc:
        with div(id='header').add(ol()):
            for i in ['home', 'about', 'contact']:
                li(a(i.title(), href='/%s.html' % i))

        with div():
            attr(cls='body')
            p('Lorem ipsum..')

    if not os.path.exists("./" + path):
        os.makedirs("./" + path)

    f = open("./" + path + "/" + fileName, 'w+')
    f.write(str(doc))
    f.close()

    if (usejs.lower() == "y"):
        if not os.path.exists("./" + sitename + "/js"):
            os.makedirs("./" + sitename + "/js")
    if (usecss.lower() == "y"):
        if not os.path.exists("./" + sitename + "/css"):
            os.makedirs("./" + sitename + "/css")
def report_head(doc):
    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",
        )
        link(
            rel='stylesheet',
            href='https://use.fontawesome.com/releases/v5.7.0/css/all.css',
            integrity=
            'sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ',
            crossorigin="anonymous",
        )
        script(
            src="https://code.jquery.com/jquery-3.4.1.slim.min.js",
            integrity=
            "sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n",
            crossorigin="anonymous")
        script(
            src=
            "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js",
            integrity=
            "sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6",
            crossorigin="anonymous")
Ejemplo n.º 3
0
def add_head_style(this_urlpath=""):
    """Adds <link> tags for style files, assuming <head> context."""

    tags.meta(charset="utf-8")
    tags.meta(name="viewport", content="width=device-width, initial-scale=1.0")

    emoji = urls.link(this_urlpath, "NotoColorEmoji.ttf")
    tags.style(f"""
        @font-face {{
            font-family: 'Noto Color Emoji';
            src: local('Noto Color Emoji'), url({emoji}) format("truetype");'
        }}
    """)

    tags.link(
        rel="icon",
        type="image/png",
        sizes="32x32",
        href=urls.link(this_urlpath, "favicon-32x32.png"),
    )
    tags.link(
        rel="icon",
        type="image/png",
        sizes="16x16",
        href=urls.link(this_urlpath, "favicon-16x16.png"),
    )
    tags.link(
        rel="stylesheet",
        type="text/css",
        href=urls.link(this_urlpath, "style.css"),
    )
    tags.script(src=urls.link(this_urlpath, "video.js"))
    tags.script(src="https://kit.fontawesome.com/7e1cde4d00.js",
                crossorigin="anonymous")
Ejemplo n.º 4
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.º 5
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.º 6
0
def quiz(ws_url, db_handler, html_function):
    d = _doc('Quiz')
    with d:
        with t.fieldset(cls='small_fieldset'):
            # Content container - filtered results themselves will be fed into here, via websocket (see _js_socket_quiz_manager):
            t.div(
                id='content', cls='quiz_content'
            )  # Note: this container will contain another div of the same class, in which everything "real" will go; see _multi_choice_question
            t.button('Go', id="go", cls='quiz_button')

        with t.fieldset(cls='small_fieldset'):
            _dropdown(
                t.div(cls='dropdown'), 'choose_subject',
                (('Timeline (sequence)', _gurl(settings.k_history_sequence)),
                 ('Science grammar', _gurl(settings.k_science_grammar)),
                 ('English vocabulary', _gurl(settings.k_english_vocabulary)),
                 ('English grammar', _gurl(settings.k_english_grammar)),
                 ('Latin vocabulary', _gurl(settings.k_latin_vocabulary))),
                True, 'Subjects...')
            _dropdown(t.div(cls='dropdown'), 'cycle_dropdown',
                      (('Cycle 1', 'bogus'), ('Cycle 2', 'bogus'),
                       ('Cycle 3', 'bogus'), ('All Cycles', 'bogus'),
                       ('My Cycle', 'bogus')), True, 'Cycles...')
            _dropdown(t.div(cls='dropdown'), 'weeks_dropdown',
                      (('...', 'bogus'), ('All Weeks', 'bogus')), True,
                      'Weeks...')
            _dropdown(t.div(cls='dropdown'), 'difficulty_dropdown',
                      (('Easy', 'bogus'), ('Medium', 'bogus'),
                       ('Difficult', 'bogus')), True, 'Difficulty...')

        # JS (intentionally at bottom of file; see https://faqs.skillcrush.com/article/176-where-should-js-script-tags-be-linked-in-html-documents and many stackexchange answers):
        t.script(_js_socket_quiz_manager(ws_url, db_handler, html_function))
        t.script(_js_dropdown())
    return d.render()
Ejemplo n.º 7
0
def page():
    doc = document()
    with doc.head:
        link_("https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css")
        link_("https://extra-uru1z3cxu.now.sh/css/extra.css")
        link_("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.css")
        dom.script(src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js')

    with doc.body:
        with dom.div(cls=CENTER_FRAME)as CenterFrame:
            with dom.div(cls=CARD) as Card:
                with dom.form(cls=UPLOAD_FORM) as UploadForm:
                    dom.i(cls=UPLOAD_ICON,onclick=''' $('#fileupload').click()''')
                    dom.p("Find File",id =1,cls="text-gray-500 mt-4")
                    dom.button("Upload",cls=BUTTON)
                    dom.input(cls='hidden',type="file",id="fileupload",onchange=''' $('#1').text(this.value.split("\\\\").pop(-1))''')
            with dom.div(cls=RESULT_CONTAINER) as ResultContainer:
                for _ in range(4):
                    with dom.div(cls=RESULT_ITEM) as ResultItem:
                        dom.p("filename.jpg",cls="text-xl text-gray-400")
                        dom.i(cls="fas fa-download text-xl text-gray-400")

            with dom.div() as ResultContainer:
                pass
    return doc.render()
Ejemplo n.º 8
0
    def __init__(self, title, css='splendor'):
        self.doc = dominate.document(title=title)
        self.has_widgets = False
        self.has_tables = False

        with self.doc.head:
            link(rel='stylesheet', href=Journal.css[css], type='text/css')

            # bokeh css/js
            link_href, js_src = bu.get_bokeh_src()
            link(rel='stylesheet', href=link_href, type="text/css")
            script(type='text/javascript', src=js_src)

            # css to center the bokeh plots
            style("""
            div.bk-grid {
                margin: auto;
                width: 50%;
            }

            div.bk-plot-layout {
                margin: auto;
                width: 50%;
            }

            div.bk-root {
                margin: auto;
                width: 50%;
            }

            div.bk-canvas-wrapper {
                margin: auto;
                width: 50%;
            }
            """)
Ejemplo n.º 9
0
 def add_script(name, linked=False):
     if linked:
         script(type='text/javascript',
                src='file://' +
                os.path.join(os.path.dirname(__file__), name))
     else:
         with script(type='text/javascript'):
             raw("//<![CDATA[\n" + read_resource(name) + "\n//]]>")
Ejemplo n.º 10
0
def user_summary_for(rtype, storages, output_path: Path):
    ustats = {}

    def reg(user, query, stats):
        if user not in ustats:
            ustats[user] = {}
        ustats[user][query] = stats

    with ProcessPoolExecutor() as pp:
        digests = pp.map(get_digest, [s.path for s in storages])

    for s, digest in zip(storages, digests):
        everything = flatten([ch for ch in digest.changes.values()])
        for user, items in group_by_key(everything,
                                        key=lambda x: x.user).items():
            reg(user, s.name, len(items))

    now = datetime.now()
    doc = dominate.document(
        title=
        f'axol tags summary for {[s.name for s in storages]}, rendered at {fdate(now)}'
    )
    with doc.head:
        T.style(STYLE)
        raw_script(JS)  # TODO necessary?

        # TODO FIXME can't inline due to some utf shit
        sortable_js = Path(__file__).absolute().parent / 'js' / 'sorttable.js'
        T.script(src=str(sortable_js))

    ft = FormatTrait.for_(rtype)
    with doc.body:
        with T.table(cls='sortable'):
            emitted_head = False
            for user, stats in sorted(ustats.items(),
                                      key=lambda x: (-len(x[1]), x)):
                if not emitted_head:
                    with T.thead():
                        T.td('user')
                        for q, _ in stats.items():
                            T.td(q)
                    emitted_head = True

                with T.tr():
                    T.td(ft.user_link(user))
                    for q, st in stats.items():
                        with T.td(sorttable_customkey=str(st)):
                            # TODO I guess unclear which tag to choose though.
                            T.a(
                                q, href=f'summary/{q}.html'
                            )  # TODO link to source in index? or on pinboard maybe
                            # TODO also project onto user's tags straight away
                            T.sup(
                                str(st) if st < 5 else T.b(
                                    T.font(str(st), color='red')))  # TODO css

    output_path.write_text(str(doc))
    logger.info('Dumped user summary to %s', output_path)
Ejemplo n.º 11
0
    def report_asciinema(self, asciinema_link, title='', **kwargs):
        """
        Section creates a jumbotron to house an asciinema

        :param str asciinema_link: Link to asciinema. Could be http/s or local files
        :param str title: Set the title of the asciinema. If set, it will create its own section. If not, it will append to previous section
        :param tuple alert: Kwarg Create a dismissable alert box. First value of tuple is the color, and the second is the message
        :param bool section: Kwarg Set to True to append the cards section to the preceding section. Default is false
        :raises ObjectNotInitiated: Raises exception when the correct flags are not set in ReportWriter

        Example:
            >>> r += report.report_asciinema('https://asciinema.org/a/XvEb7StzQ3C1BAAlvn9CDvqLR', title='asciinema')
        """
        logging.warning(
            'This method only works with asciinema links because of the way\n \
            browsers enforce CORS')
        # checks to see if asciinema has been intialized
        if not self.asciinema:
            raise rng.ObjectNotInitiated(
                'To integrate asciinema, set asciinema=True in ReportWriter')

        # TODO: write a check here that validates the asciinema url

        # hacky way to bypass the CORS problem
        try:
            url = get('%s.json' % asciinema_link).url
        except:
            logging.warning('Need internet to get the proper url for %s' %
                            asciinema_link)

        # controls if sticky or not
        if 'section' in kwargs:
            style = rng.CSSControl.sticky_section_css
        else:
            style = rng.CSSControl.not_sticky_section

        with tag.div(
                _class=
                "jumbotron jumbomargin container reportng-acsiinema-class",
                style=style) as a:
            if title != '':
                tag.h1(title,
                       id="%s" % rng.HelperFunctions.id_with_random(5, title))
            # create dismissable alert box
            if 'alert' in kwargs:
                rng.HelperFunctions.make_alert(kwargs.get('alert'))
            with tag.div(_class="container",
                         style="text-align: center;" + style):
                raw('<asciinema-player src="%s"></asciinema-player>' % url)
                tag.script(src=rng.JSCSS.asciinema_js)
                tag.a('Asciinema link',
                      _class=
                      "btn btn-secondary row justify-content-center btn-sm",
                      role="button",
                      href=asciinema_link,
                      target="_blank")
        return str(a)
Ejemplo n.º 12
0
def new_user(form, ws_url, errors=None):
    title = 'New User'
    d = _doc(title)
    with d:
        with t.form(action=form.action, method='post'):
            with t.fieldset():
                t.legend(title)
                _errors(errors)
                with t.ol(cls='step_numbers'):
                    with t.li():
                        t.p('First, create a one-word username for yourself (lowercase, no spaces)...'
                            )
                        _text_input(
                            *form.nv('new_username'),
                            ('required', 'autofocus'), {
                                'pattern': valid.re_username,
                                'oninput': 'check_username(this.value)'
                            }, 'Type new username here',
                            _invalid(valid.inv_username,
                                     form.invalid('new_username')))
                        _invalid(valid.inv_username_exists, False,
                                 'username_exists_message')
                    with t.li():
                        t.p("Next, invent a password; type it in twice to make sure you've got it..."
                            )
                        _text_input('password',
                                    None, ('required', ),
                                    {'pattern': valid.re_password},
                                    'Type new password here',
                                    _invalid(valid.inv_password,
                                             form.invalid('password')),
                                    type_='password')
                        _text_input('password_confirmation',
                                    None, ('required', ),
                                    None,
                                    'Type password again for confirmation',
                                    _invalid(
                                        valid.inv_password_confirmation,
                                        form.invalid('password_confirmation'),
                                        'password_match_message'),
                                    type_='password')
                    with t.li():
                        t.p("Finally, type in an email address that can be used if you ever need a password reset (optional, but this may be very useful someday!)..."
                            )
                        _text_input(
                            *form.nv('email'), None,
                            {'pattern': valid.re_email},
                            'Type email address here',
                            _invalid(valid.inv_email, form.invalid('email')))
                t.input_(type="submit", value="Done!")
        t.script(_js_validate_new_user_fields())
        t.script(_js_check_username(ws_url))
    return d.render()
Ejemplo n.º 13
0
def dump_html_standalone(snippets, fname, webpage_style, include_banner,
                         include_vernums, html_assets, html_classes):
    from dominate import tags, document
    from dominate.util import raw
    from . import GENERATOR
    from .core import SerAPI
    from .html import gen_banner, wrap_classes, ASSETS
    from .pygments import HTML_FORMATTER

    doc = document(title=fname)
    doc.head.add(tags.meta(charset="utf-8"))
    doc.head.add(tags.meta(name="generator", content=GENERATOR))
    doc.set_attribute("class", "alectryon-standalone")

    for css in ASSETS.ALECTRYON_CSS:
        doc.head.add(tags.link(rel="stylesheet", href=css))
    for link in (ASSETS.IBM_PLEX_CDN, ASSETS.FIRA_CODE_CDN):
        doc.head.add(raw(link))
    for js in ASSETS.ALECTRYON_JS:
        doc.head.add(tags.script(src=js))

    html_assets.extend(ASSETS.ALECTRYON_CSS)
    html_assets.extend(ASSETS.ALECTRYON_JS)

    pygments_css = HTML_FORMATTER.get_style_defs('.highlight')
    doc.head.add(tags.style(pygments_css, type="text/css"))

    cls = wrap_classes(webpage_style, *html_classes)
    root = doc.body.add(tags.article(cls=cls))
    if include_banner:
        root.add(raw(gen_banner(SerAPI.version_info(), include_vernums)))
    for snippet in snippets:
        root.add(snippet)

    return doc.render(pretty=False)
Ejemplo n.º 14
0
def select_user(url):
    d = _doc('Select User')
    with d:
        _text_input('search',
                    None, ('autofocus', ), {
                        'autocomplete': 'off',
                        'oninput': 'search(this.value)'
                    },
                    'Search',
                    type_='search')
        t.div(
            id='search_result'
        )  # filtered results themselves are added here, in this `result` div, via websocket, as search text is typed (see javascript)
        # JS (intentionally at bottom of file; see https://faqs.skillcrush.com/article/176-where-should-js-script-tags-be-linked-in-html-documents and many stackexchange answers):
        t.script(_js_filter_list(url))
    return d.render()
Ejemplo n.º 15
0
 def render(self, values, with_script_tag=True):
     template = CustomTemplate(self.js_source)
     rendered = raw(template.substitute(values).strip())
     if with_script_tag:
         return script(rendered, type="text/javascript")
     else:
         return rendered
Ejemplo n.º 16
0
    def render(self, posts_per_page=25):
        pages_count = (len(self.rendered_items) + posts_per_page - 1) // posts_per_page
        page_names = ["%d.html" % i for i in range(pages_count)]

        nav_section = T.nav(
            *[T.a(str(i), href=page_names[i], target=_PAGE_FRAME) for i in range(pages_count)]
        )

        index = T.html(
            T.head(
                T.meta(charset='utf-8'),
                stylesheet(_STYLE_CSS),
                stylesheet(_NAVBAR_CSS),
                T.script(src=_JQUERY_URL),
                inline_script_from(get_resource(Path(_SELECTED_JS)))
            ),
            T.body(
                nav_section,
                T.iframe(name=_PAGE_FRAME, src=page_names[0] if pages_count > 0 else 'none', width='100%', height='100%', style='border:none')
            )
        )
        self.pages['index.html'] = index

        for page_index in range(pages_count):
            page_items = self.rendered_items[page_index * posts_per_page: (page_index + 1) * posts_per_page]
            chunk_html = T.html(
                T.head(stylesheet('page.css')),
                T.body(
                    T.div(*page_items, id=ID_CONTAINER)
                )
            )
            self.pages[page_names[page_index]] = chunk_html
Ejemplo n.º 17
0
def form(form):
    return Div(QuickForm(form),
            Button('Submit',
                primary=True,
                onclick="submitUserForm()"),
            script(src='/static/submitUserForm.js',
                type='text/javascript'))
Ejemplo n.º 18
0
def inline_script(base_path, script_path):
    comment = ("\n// %s\n" % script_path if script_path else "")

    with open(os.path.join(base_path, script_path)) as ifs:
        with script() as result:
            raw(comment + ifs.read())
        return result
Ejemplo n.º 19
0
def create_page_index():
    doc = dominate.document(title="Phone alignments")
    lexicon = load_lexicon()

    with doc.head:
        T.meta(**{'content': 'text/html;charset=utf-8', 'http-equiv': 'Content-Type'})
        T.meta(**{'content': 'utf-8', 'http-equiv': 'encoding'})
        T.link(rel='stylesheet', href='../style.css')
        T.script(
            src="https://code.jquery.com/jquery-3.4.1.min.js",
            integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=",
            crossorigin="anonymous",
        )
        T.script(type='text/javascript', src='../script.js')

    with doc:
        T.p("""
            The web-pages linked below show alignments of phones with lip movement.
            The data is a subset of 2000 utterances from the Grid corpus.
            We picked a selection of phones and for each of them we randomly selected at most 128 pairs.
        """)

        with T.ul():
            for k, g in itertools.groupby(SELECTED_PHONES, key=lambda w: w[0]):
                with T.li():
                    for i in g:
                        T.a(i, href=i + "/index.html")

        T.p("""Mean duration (s) of each phone:""")
        T.pre("""
AA 0.154
AE 0.066
AH 0.060
AO 0.143
AW 0.277
AY 0.142
EH 0.091
EY 0.124
IH 0.068
IY 0.113
OW 0.123
UW 0.152
            """, style="font-family: Courier")

    path = "www/index.html"
    with open(path, "w") as f:
        f.write(doc.render())
Ejemplo n.º 20
0
def page():
    doc = document()
    with doc.head:
        link_("https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css")
        link_("https://extra-uru1z3cxu.now.sh/css/extra.css")
        link_(
            "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.css"
        )
        dom.script(
            src=
            'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js'
        )

    with doc.body:
        with dom.div(cls=CENTER_FRAME) as CenterFrame:
            with dom.form(action='/file',
                          method='post',
                          enctype='multipart/form-data'):
                with dom.div(cls=LABEL_CARD):
                    dom.label('Write down your mark here',
                              cls="text-white text-xl")
                    dom.input(cls=LABEL_INPUT,
                              type='text',
                              placeholder='your watermark text here',
                              name='mk-text')
                with dom.div(cls=IMG_CARD):
                    with dom.div(cls=IMG_FORM):
                        dom.i(cls=UPLOAD_ICON,
                              onclick='''$('#fileupload').click()''')
                        dom.p("Find File", id="file", cls="text-gray-500 mt-4")
                        dom.input(
                            cls="hidden",
                            type="file",
                            name='bg-img',
                            id="fileupload",
                            onchange=
                            '''$('#file').text(this.value.split("\\\\").pop(-1))'''
                        )
                        dom.button('Upload', cls=BUTTON, type='submit')

            with dom.div(cls=RESULT_CONTAINER) as ResultContainer:
                for _ in range(4):
                    with dom.div(cls=RESULT_ITEM) as ResultItem:
                        dom.p("filename.jpg", cls="text-xl text-gray-400")
                        dom.i(cls="fas fa-download text-xl text-gray-400")

    return doc.render()
Ejemplo n.º 21
0
 def body_(self, contents, scriptData=""):
     """ The HTML <body> contents """
     return (div(self.topNav(),
                 div(div(contents, _class="column col-12"),
                     _class="columns"),
                 _class="container",
                 style="width: 55em; margin: 0 auto;"),
             script(raw(scriptData)))
Ejemplo n.º 22
0
    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 get_cmpcvr_doc(cmpcvr_df: pd.DataFrame) -> dominate.document:
    version = utils.show_version()
    doc = dominate.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(
            src="https://code.jquery.com/jquery-3.4.1.slim.min.js",
            integrity=
            "sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n",
            crossorigin="anonymous")
        script(
            src=
            "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js",
            integrity=
            "sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6",
            crossorigin="anonymous")
    with doc:
        with div(cls='container'):
            with div(cls='jumbotron'):
                h1('Audit Engine: {version} - vote records 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')
            get_summary_table(cmpcvr_df)
            with table(cls='table table-hover'):
                with thead():
                    with tr():
                        th('#', scope="col")
                        th('Ballot ID', scope="col")
                        th('Style', scope="col")
                table_body = tbody()
                table_body += mount_ballots_to_table(cmpcvr_df)

    return doc
Ejemplo n.º 24
0
def inline_script(base_path, script_path):
    comment = (
        "\n// %s\n" % script_path
        if script_path else
        ""
    )

    with open(os.path.join(base_path, script_path)) as ifs:
        with script() as result:
            raw(comment + ifs.read())
        return result
Ejemplo n.º 25
0
def login(action, error=None):
    d = _doc('OHS-Test Login')
    with d:
        with t.form(action=action, method='post'):
            with t.fieldset(cls='small_fieldset'):
                t.legend('Log in...')
                _error(error)
                t.div(_text_input('username',
                                  None, ('required', 'autofocus'),
                                  {'pattern': valid.re_username},
                                  invalid_div=_invalid(valid.inv_username,
                                                       False)),
                      cls='field')
                t.div(_text_input('password',
                                  None, ('required', ),
                                  type_='password'),
                      cls='field')
                t.div(t.input_(type="submit", value="Log in!"), cls='field')
        t.script(_js_validate_login_fields())
    return d.render()
Ejemplo n.º 26
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.º 27
0
    def __init__(self, *args, \
            bootstrap_url='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6', \
            jquery_url='https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js',
            static_folder=None,
            **kwargs):

        super().__init__(**kwargs)
        self.navbar = None

        self.meta = self.head.add(
            meta(
                name='viewport',
                content='width=device-width, initial-scale=1.0'
            )
        )
        self.head.add(comment('Latest compiled and minified CSS'))
        if static_folder is not None:
            bootstrap_url = static_folder

        self.head.add(
            link(
                rel='stylesheet',
                href=bootstrap_url + '/css/bootstrap.min.css'
            ),
        )
        self.content = self.body.add(Div(id='content'))
        self.scripts = self.body.add(Div(id='scripts'))
        self.scripts.add(comment('jQuery library'))

        if static_folder is not None:
            jquery_url = static_folder + '/js/jquery.min.js'

        self.scripts.add(
            script(src=jquery_url)
        )
        self.scripts.add(comment('Latest compiled JavaScript'))
        self.scripts.add(
            script(src=bootstrap_url + '/js/bootstrap.min.js')
        )

        self.add(*args)
Ejemplo n.º 28
0
def html_report(exchanges, buf):
    """Generate an HTML report with check results.

    :param exchanges:
        An iterable of :class:`~httpolice.Exchange` objects.
        They must be already processed by :func:`~httpolice.check_exchange`.

    :param buf:
        The file (or file-like object) to which the report will be written.
        It must be opened in binary mode (not text).

    """
    title = u'HTTPolice report'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.head:
        H.script(type=u'text/javascript').add_raw_string(js_code)
    with document:
        H.h1(title)
        _render_exchanges(exchanges)
    buf.write(document.render().encode('utf-8'))
Ejemplo n.º 29
0
    def html(self):
        """ Method to get the `dominate` HTML of the page. This HTML needs to be
        rendered.

        Returns:
            dominate.document: HTML document corresponding to the page.
        """
        doc = dominate.document(title=self.title)

        # Add favicon
        if self.favicon is not None:
            with doc.head:
                link(rel='icon', href=self.favicon)

        # Add external files (Skin)
        if self.skin is not None:
            with doc.head:
                for ref in self.skin.libs:  # Libs
                    link(rel='stylesheet', crossorigin='anonymous', href=ref)

                for ref in self.skin.fonts:  # Fonts
                    link(rel='stylesheet', type='text/css', href=ref)

                if self.skin.rules != "":
                    style(raw(self.skin.rules))

        # Add Widgets HTML to the page
        main_div = div(cls="container")
        for w in self.widgets:
            main_div.add(w.html())
            main_div.add(br())
        doc.add(main_div)

        # Add Javascript code to the page
        js_str = "\n\n".join([a.js() for a in self.ajax()])
        if js_str != '':
            doc.add(script(src=JQUERY_CDN))
            doc.add(script(raw(js_str + "\n\n" + COMMON_JS)))

        return doc
Ejemplo n.º 30
0
def site():
    base = Path('website')
    with (base/'content'/'index.toml').open() as toml, \
         (base/'style'/'index.css').open() as css:
        data = loads(toml.read())

        with html(lang='en') as document:

            with head():
                meta(charset='utf-8')
                meta(name='description',
                     content=f'{SHARED.info.person_name} (engineer|designer)')
                meta(name='keywords', content=','.join(SHARED.meta.keywords))
                meta(name='author', content=f'{SHARED.info.person_name}')
                title(SHARED.info.person_name)
                link(rel='shortcut icon',
                     type='image/x-icon',
                     href='favicon.ico')
                link(rel='icon', type='image/x-icon', href='favicon.ico')
                style(raw(css.read()))
                script(src='website/js/anim.js')
                script(src='website/js/index.js')

            with body():
                _block('engineer', data['engineer'])
                _block('designer', data['designer'])
                with div(id='handler'):
                    div(raw('&laquo;&raquo;'))
                script('main();', type='text/javascript')

    copyright = comment(f'Copyright (C) 2015 - {datetime.now().year} '
                        f'{SHARED.info.person_name}. '
                        'All rights reserved.')
    return f'<!DOCTYPE html>{copyright}{document.render(pretty=False)}'
Ejemplo n.º 31
0
    def integrate(self, tag, container=None):
        """Integrates the given tag into the page using container

            Integration means merging the DOM content of the tag itself into
            the given container which defaults to the Page's internal content
            element,
        """
        if container is None: container = self.content
        container.add(tags.a(name=tag.id), tag)
        with self.doc.head:
            if hasattr(tag, 'cssfiles'):
                for css in tag.cssfiles:
                    self._link_css(css)
            if hasattr(tag, 'scripturls'):
                for script in tag.scripturls:
                    tags.script(crossorigin="anonymous", src=script)
        if hasattr(tag, "scriptage"):
            self.scriptage.append(tag.scriptage)
        if hasattr(tag, "on_ready_scriptage"):
            self.on_ready_scriptage.append(tag.on_ready_scriptage)
        setattr(self, tag.__class__.__name__, tag)
        return tag
Ejemplo n.º 32
0
def html_report(exchanges, buf):
    """Generate an HTML report with check results.

    :param exchanges:
        An iterable of :class:`~httpolice.Exchange` objects.
        They must be already processed by :func:`~httpolice.check_exchange`.

    :param buf:
        The file (or file-like object) to which the report will be written.
        It must be opened in binary mode (not text).

    """
    # We don't want to hold the entire report in memory before printing it,
    # because that would mean unbounded memory growth with more input.
    # But Dominate obviously doesn't have a streaming mode, so we do this
    # manually. We create our document, but instead of the actual exchanges,
    # we insert a separator string that allows us to split it into a prologue
    # and an epilogue.
    separator = u'---- CUT HERE ----'

    title = u'HTTPolice report'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.head:
        H.script(type=u'text/javascript').add_raw_string(js_code)
    with document.body:
        H.attr(_class=u'report')
    with document:
        H.h1(title)
        H.hr()
        text_node(separator)

    (prologue, epilogue) = document.render().split(separator)

    buf.write(prologue.encode('utf-8'))
    for div in _generate_exchange_divs(exchanges):
        buf.write(div.render().encode('utf-8'))
    buf.write(epilogue.encode('utf-8'))
Ejemplo n.º 33
0
def html_report(exchanges, buf):
    """Generate an HTML report with check results.

    :param exchanges:
        An iterable of :class:`~httpolice.Exchange` objects.
        They must be already processed by :func:`~httpolice.check_exchange`.

    :param buf:
        The file (or file-like object) to which the report will be written.
        It must be opened in binary mode (not text).

    """
    # We don't want to hold the entire report in memory before printing it,
    # because that would mean unbounded memory growth with more input.
    # But Dominate obviously doesn't have a streaming mode, so we do this
    # manually. We create our document, but instead of the actual exchanges,
    # we insert a separator string that allows us to split it into a prologue
    # and an epilogue.
    separator = u'---- CUT HERE ----'

    title = u'HTTPolice report'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.head:
        H.script(type=u'text/javascript').add_raw_string(js_code)
    with document.body:
        H.attr(_class=u'report')
    with document:
        H.h1(title)
        H.hr()
        text_node(separator)

    (prologue, epilogue) = document.render().split(separator)

    buf.write(prologue.encode('utf-8'))
    for div in _generate_exchange_divs(exchanges):
        buf.write(div.render().encode('utf-8'))
    buf.write(epilogue.encode('utf-8'))
Ejemplo n.º 34
0
def html_report(exchanges, buf):
    """Generate an HTML report with check results.

    :param exchanges:
        An iterable of :class:`~httpolice.Exchange` objects.
        They must be already processed by :func:`~httpolice.check_exchange`.

    :param buf:
        The file (or file-like object) to which the report will be written.
        It must be opened in binary mode (not text).

    """
    title = u'HTTPolice report'
    document = dominate.document(title=title)
    _common_meta(document)
    with document.head:
        H.script(type=u'text/javascript').add_raw_string(js_code)
    with document.body:
        H.attr(_class=u'report')
    with document:
        H.h1(title)
        _render_exchanges(exchanges)
    buf.write(document.render().encode('utf-8'))
Ejemplo n.º 35
0
Archivo: app.py Proyecto: i-v-s/car-ctl
async def index(request: Request):
    doc = document(title='Онлайн')
    with doc.head:
        meta(charset="utf-8")
        meta(http_equiv="X-UA-Compatible", content="IE=edge")
        meta(name="viewport", content="width=device-width, initial-scale=1")
    with doc:
        div(id='main', style='width: 100vw; height: 100vh;')
        script(
            raw('''
            const main = document.getElementById('main');
            let x = null, y = null;
            main.onmousedown = e => {
                x = e.screenX;
                y = e.screenY;
            }
            main.onmouseup = e => {
                x -= e.screenX;
                y -= e.screenY;
                fetch('/go?x=' + encodeURIComponent(-x) + '&y=' + encodeURIComponent(y), {method: 'PUT'});
            }
        '''))
    return Response(body=str(doc), content_type='text/html')
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.º 37
0
def document(title, actual_hash=None, index=False):
    doc = dominate.document(title=title)
    style = t.style()
    style.add_raw_string(STYLE)
    script = t.script()
    script.add_raw_string(SCRIPT)
    doc.head.add(style, script)

    if actual_hash is not None:
        doc.body["data-actual-hash"] = actual_hash

    if index:
        doc.body["data-index"] = True

    return doc
Ejemplo n.º 38
0
def make_page(app, uri):
    doc = dominate.document()
    inline = False
    doc.head += tags.script(util.include(root / 'domx' / 'domx.js'))
    doc.head += tags.style(util.include(root / 'domx' / 'domx.css'))
    page = app(doc)
    try:
        # router
        for p in uri.path.split('/'):
            if p == '':
                continue
            if p == '_domx':
                inline = True
                continue
            page = getattr(page, p)
    except AttributeError:
        raise ValueError(404)
    # render page
    tags.pre(repr(page))
    with doc:
        page()

    # dxify
    def walk(node):
        for i in node.children:
            if not isinstance(i, tags.dom_tag):
                continue
            if not isinstance(i, x):
                walk(i)
                continue
            # it's a x() marker
            # todo onsubmit, etc for different types
            node['onclick'] = "dx.replace('{}', '{}');".format(
                i['target'],
                '/_domx' + i['get'],
            )
            node.children.remove(i)

    walk(doc.body)
    if inline:
        return doc.body.children[0]
    else:
        return doc
Ejemplo n.º 39
0
def open_html_doc(name, letter=None):
    html_doc = dominate.document(title=u"מילון הראיה")
    html_doc['dir'] = 'rtl'
    with html_doc.head:
        with tags.meta():
            tags.attr(charset="utf-8")
        with tags.meta():
            tags.attr(name="viewport", content="width=device-width, initial-scale=1")

        tags.script(src="jquery/dist/jquery.min.js")
        tags.link(rel='stylesheet', href='bootstrap-3.3.6-dist/css/bootstrap.min.css')
        tags.link(rel='stylesheet', href='style.css')
        tags.script(src="bootstrap-3.3.6-dist/js/bootstrap.min.js")
        tags.link(rel='stylesheet', href="bootstrap-rtl-3.3.4/dist/css/bootstrap-rtl.css")
        tags.link(rel='stylesheet', href='html_demos-gh-pages/footnotes.css')
        tags.script(src="milon.js")
        tags.script(src="html_demos-gh-pages/footnotes.js")
        tags.script(src="subjects_db.json")




    html_doc.footnote_ids_of_this_html_doc = []
    html_doc.name = name
    if letter:
        html_doc.letter = letter
        html_doc.section = html_docs_l[-1].section
    else:
        html_doc.section = name

    html_doc.index = len(html_docs_l) + 1
    with html_doc.body:
        with tags.div():
            tags.attr(cls="container-fluid")
            # TODO: call page_loaded to update saved URL also in other links
            tags.script("page_loaded('%s.html')" % html_doc.index)

            with tags.div():
                tags.attr(cls="fixed_top_left", id="menu_bar")
                with tags.div():
                    with tags.button(type="button"):
                        tags.attr(id="search_icon_button", type="button", cls="btn btn-default")
                        with tags.span():
                            tags.attr(cls="glyphicon glyphicon-search")
                    with tags.span():
                        tags.attr(cls="dropdown")
                        with tags.button(type="button", cls="btn btn-primary") as b:
                            tags.attr(href="#") #, cls="dropdown-toggle")
                            with tags.span():
                                tags.attr(cls="glyphicon glyphicon-menu-hamburger")
                                # b['data-toggle'] = "dropdown"
                        with tags.ul():
                            tags.attr(cls="dropdown-menu dropdown-menu-left scrollable-menu")





    return html_doc
Ejemplo n.º 40
0
def inline_script(script: str) -> T.script:
    s = T.script()
    s.add_raw_string(script)
    return s