Ejemplo n.º 1
0
 def genrow(self):
     """Generate the html row."""
     tags.td(tags.code(self.format, self.version),
             align='center',
             __pretty=False)
     tags.td(tags.i(raw(self.hexport)), align='center', __pretty=False)
     tags.td(tags.code(self.himport), align='center', __pretty=False)
Ejemplo n.º 2
0
    def fence(self, tokens, idx, options, env):
        token = tokens[idx]
        # TODO : Later, add correct highlights for languages
        # info = unescapeAll(token.info).strip() if token.info else ""
        # langName = ""

        # if info:
        #     langName = info.split()[0]

        highlighted = escapeHtml(token.content)

        if token.attrs:
            return pre(code(highlighted), **token.attr)
        else:
            return pre(code(highlighted))
Ejemplo n.º 3
0
def construct_list_items(violations) -> Iterable[li]:
    """Construct list items."""
    for violation in violations:
        yield li(
            strong(code(violation['code'])),
            a(violation['title'], href=violation['url']),
        )
Ejemplo n.º 4
0
def _render_header_entries(annotated_entries):
    for entry, annotated in annotated_entries:
        with H.pre(**_for_object(entry, 'header-entry')), H.code():
            # Dominate defaults to ``__pretty=False`` for ``pre``.
            _render_known(entry.name)
            text_node(u': ')
            _render_annotated(annotated)
Ejemplo n.º 5
0
def _render_header_entries(annotated_entries):
    for entry, annotated in annotated_entries:
        with H.pre(**_for_object(entry, 'header-entry')), H.code():
            # Dominate defaults to ``__pretty=False`` for ``pre``.
            _render_known(entry.name)
            text_node(u': ')
            _render_annotated(annotated)
Ejemplo n.º 6
0
def _render_header_entries(annotated_entries):
    for entry, annotated in annotated_entries:
        with H.pre(**_for_object(entry, 'header-entry')), H.code():
            # Dominate (at least as of 2.2.0)
            # automatically inlines all descendants of ``pre``.
            # https://github.com/Knio/dominate/issues/68
            _render_known(entry.name)
            H.span(u': ')
            _render_annotated(annotated)
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
    def report_code_section(self, title, code, **kwargs):
        """
        This section can use used to add code containers that will be lexed and highlighted using highlight.js

        :param str title: Title of the code section.
        :param str code: Code. Use pre and code tags so multiline code is fine
        :param bool section: Kwarg Set to True to append the cards section to the preceding section. Default is false
        :param tuple alert: Kwarg Create a dismissable alert box. First value of tuple is the color, and the second is the message
        :param tuple reference: Kwarg Adds a small button which hrefs to a user supplied link. Is a tuple. First value is color, second is link
        :param dict badge: Kwarg Adds badges. Key is the color, and value is the message.
        :param dict modal: Create a modal. Is a dictionary. Valid keys are button, title and content
        :return: a string code section
        :raises ObjectNotInitiated: Raises exception when the correct flags are not set in ReportWriter

        Example of how to get code from file:
            >>> with open('somefile.py', 'r') as f:
            >>>     data = f.read()
            >>> r += report.report_code_section('my py code', data)
        """
        if not self.code:
            raise rng.ObjectNotInitiated(
                'To integrate code highlighting, set code=True in ReportWriter'
            )
        if 'section' in kwargs:
            style = rng.CSSControl.sticky_section_css
        else:
            style = rng.CSSControl.not_sticky_section
        with tag.div(_class=
                     "jumbotron container context reportng-code-section-class",
                     style=style) as c:  # padding mods
            t = tag.h1(title,
                       id="%s" % rng.HelperFunctions.id_with_random(5, title))
            if 'reference' in kwargs:
                t.add(rng.HelperFunctions.ref_button(kwargs.get('reference')))
            # create dismissable alert box
            if 'alert' in kwargs:
                rng.HelperFunctions.make_alert(kwargs.get('alert'))
            with tag.div(
                    _class="container",
                    style="max-height: 70%; overflow: auto; margin-bottom: 20"
            ):
                tag.pre().add(tag.code(code))
                if 'badge' in kwargs:
                    rng.HelperFunctions.create_badges(kwargs.get('badge'))
            if 'modal' in kwargs:
                if isinstance(kwargs.get('modal'), dict):
                    rng.HelperFunctions.make_modals(title.replace(' ', ''),
                                                    kwargs.get('modal'))
        return str(c)
Ejemplo n.º 9
0
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)
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
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)
Ejemplo n.º 12
0
class LinkToADR(Facet):
    """Link to an ADR document."""

    sparql = '''
    SELECT * WHERE {
        ?page
            octa:url ?url ;
            octa:title ?label ;
            adr:number ?number .

        OPTIONAL {
            ?page adr:status / octa:symbol ?symbol .
        }
    } ORDER BY ?number LIMIT 1
    '''

    def render(self):
        """As an HTML link."""
        descriptions = self.query(
            self.sparql,
            page=self.iri,
        )

        try:
            location = first(descriptions)
        except ValueError as err:
            raise ADRNotFound(iri=self.iri) from err

        number = location['number'].value

        if not isinstance(number, int):
            raise ADRNumberInvalid(
                number=number,
                page=self.uriref,
            )

        readable_number = f'ADR{number:03}'

        if symbol := location.get('symbol'):
            readable_number = f'{symbol} {readable_number}'

        return a(
            code(readable_number),
            ' ',
            location['label'],
            href=location['url'],
        )
Ejemplo n.º 13
0
def _render_request(req):
    with H.section():
        with H.div(_class=u'message-display'):
            if req.remark:
                H.p(printable(req.remark), _class=u'message-remark')
            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(__pretty=False, **_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)
Ejemplo n.º 14
0
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)
Ejemplo n.º 15
0
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)
Ejemplo n.º 16
0
    def construct_content(self) -> Iterable[html_tag]:
        """Construct release description."""
        rows = self.query(
            self.sparql,
            release=self.iri,
        )

        row = first(rows)

        date_value = row.get('date')

        if date_value is not None:
            date_value = date_value.value

            if isinstance(date_value, datetime):
                date_value = date_value.date()

            yield code(str(date_value))
            yield br()

        yield a(
            row['name'],
            href=row['release'],
        )
Ejemplo n.º 17
0
        label = f'{symbol} {label}'

    defined_by_label = status.get('defined_by_label')

    if defined_by_url := status.get('defined_by_url'):
        defined_by = a(
            defined_by_label or defined_by_url,
            href=defined_by_url,
            target='_blank',
        )

    elif defined_by_label:
        defined_by = defined_by_label

    else:
        defined_by = code(status['defined_by_iri'])

    return tr(td(code(raw)), td(label), td(defined_by or ''))


def status_class(octiron: Octiron, iri: URIRef):
    """Visualize all available status values as a table."""
    choices = octiron.query('''
        SELECT
            ?status ?label ?symbol
            ?defined_by_iri ?defined_by_url ?defined_by_label
        WHERE {
            ?status a adr:Status .

            GRAPH ?defined_by_iri {
                ?status rdfs:label ?label .
Ejemplo n.º 18
0
def getHTML(title,
            info=None,
            body=None,
            style=None,
            state=None,
            theme=None,
            icon=None):
    """Provide HTML object

    :param str title: short name of the notification, e.g.: server error
    :param str info: some short description if needed, e.g.: It looks like the server is not responding
    :param body: it can be string or dominate tag object, e.g.:
                 from dominate import tags as dom
                 return getHTML('server error', body=dom.pre(dom.code(result['Message']))
    :param str style: additional css style if needed, e.g.: '.card{color:red;}'
    :param int state: response state code, if needed, e.g.: 404
    :param str theme: message color theme, the same that in bootstrap 5, e.g.: 'warning'
    :param str icon: awesome icon name, e.g.: 'users'

    :return: str -- HTML document
    """
    html = document("DIRAC - %s" % title)

    # select the color to the state code
    if state in [400, 401, 403, 404]:
        theme = theme or "warning"
    elif state in [500]:
        theme = theme or "danger"
    elif state in [200]:
        theme = theme or "success"

    # select the icon to the theme
    if theme in ["warning", "warn"]:
        theme = "warning"
        icon = icon or "exclamation-triangle"
    elif theme == "info":
        icon = icon or "info"
    elif theme == "success":
        icon = icon or "check"
    elif theme in ["error", "danger"]:
        theme = "danger"
        icon = icon or "times"
    else:
        theme = theme or "secondary"
        icon = icon or "flask"

    # If body is text wrap it with tags
    if body and isinstance(body, six.string_types):
        body = dom.pre(
            dom.code(traceback.format_exc() if body == "traceback" else body),
            cls="mt-5")

    try:
        diracLogo = collectMetadata(ignoreErrors=True).get("logoURL", "")
    except Exception:
        diracLogo = ""

    # Create head
    with html.head:
        # Meta tags
        dom.meta(charset="utf-8")
        dom.meta(name="viewport",
                 content="width=device-width, initial-scale=1")
        # Favicon
        dom.link(rel="shortcut icon",
                 href="/static/core/img/icons/system/favicon.ico",
                 type="image/x-icon")
        # Provide awesome icons
        # https://fontawesome.com/v4.7/license/
        dom.script(
            src=
            "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/js/all.min.js"
        )
        # Enable bootstrap 5
        # https://getbootstrap.com/docs/5.0/getting-started/introduction/
        # https://getbootstrap.com/docs/5.0/about/license/
        dom.link(
            rel="stylesheet",
            integrity=
            "sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC",
            href=
            "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css",
            crossorigin="anonymous",
        )
        dom.script(
            src=
            "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js",
            integrity=
            "sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM",
            crossorigin="anonymous",
        )
        # Provide additional css
        style = ".card{transition:.3s;}.card:hover{transform:scale(1.03);}" + (
            style or "")
        dom.style(style)

    # Create body
    with html:
        # Background image
        dom.i(
            cls="position-absolute bottom-0 start-0 translate-middle-x m-5 fa "
            "fa-%s text-%s" % (icon, theme),
            style="font-size:40vw;z-index:-1;",
        )

        # A4 page with align center
        with dom.div(
                cls=
                "row vh-100 vw-100 justify-content-md-center align-items-center m-0"
        ):
            with dom.div(cls="container", style="max-width:600px;") as page:
                # Main panel
                with dom.div(cls="row align-items-center"):
                    # Logo
                    dom.div(dom.img(src=diracLogo, cls="card-img px-2"),
                            cls="col-md-6 my-3")
                    # Information card
                    with dom.div(cls="col-md-6 my-3"):

                        # Show response state number
                        if state and state != 200:
                            dom.div(dom.h1(
                                state,
                                cls="text-center badge bg-%s text-wrap" %
                                theme),
                                    cls="row py-2")

                        # Message title
                        with dom.div(cls="row"):
                            dom.div(dom.i(cls="fa fa-%s text-%s" %
                                          (icon, theme)),
                                    cls="col-auto")
                            dom.div(title, cls="col-auto ps-0 pb-2 fw-bold")

                        # Description
                        if info:
                            dom.small(dom.i(cls="fa fa-info text-info"))
                            dom.small(info, cls="ps-1")

            # Add content
            if body:
                page.add(body)

    return html.render()
Ejemplo n.º 19
0
                cls="text-muted")

            tags.h2("Video-to-speech", id="video-to-speech", cls="mt-3")
            raw("<p>We show results for the <em>seen</em> scenario, in which we consider videos from four speakers encountered at training. "
                "We have randomly selected 12 video samples and show the synthesized audio for our baseline method (denoted by B in the paper) and for the work of <a href='https://www.isca-speech.org/archive/Interspeech_2019/pdfs/1445.pdf'>Vougioukas et al. (Interspeech, 2019)</a> (denoted by V2S GAN). "
                "The videos are cropped around the lips, corresponding to the input to our network. "
                "These results correspond to section 4.1 in our paper.</p>")

            data1 = load_results_1()
            for row in partition_all(6, data1):
                with tags.div(cls="row mt-2 align-items-end"):
                    for col in row:
                        with tags.div(cls="col-2 text-center"):
                            with tags.div():
                                tags.span(col["speaker"], cls="text-muted")
                                tags.code(col["sample-id"], cls="ml-1")
                            tags.span(col["text"], cls="font-italic")
                            with tags.video(controls=True,
                                            cls="embed-responsive"):
                                tags.source(src=col["video-path"],
                                            type="video/webm")
                            tags.span("Ours")
                            with tags.audio(controls=True,
                                            cls="embed-responsive"):
                                tags.source(src=col["audio-path-ours"],
                                            type="audio/wav")
                            tags.span("V2S GAN")
                            with tags.audio(controls=True,
                                            cls="embed-responsive"):
                                tags.source(src=col["audio-path-theirs"],
                                            type="audio/wav")