Esempio n. 1
0
    def render(self):
        """Print unique values for a column."""
        rows: List[Row] = self.query(
            query_text=self.legend_query,
            column=self.iri,
        )

        table_rows = [
            tr(
                td(
                    raw(
                        render(
                            node=row['prov_value'],
                            octiron=self.octiron,
                            environments=[
                                TABLE.td,
                                IOLANTA.html,
                            ],
                        ) if row['prov_value'] is not None else '', ), ),
                td(*self.render_comment(row)),
                td(row['count']),
            ) for row in rows
        ]

        return table(
            thead(
                tr(
                    # These are hard coded, and I cannot change that. See the
                    # docstring for details.
                    th('Value'),
                    th('Description'),
                    th('Count'),
                ), ),
            tbody(*table_rows),
        )
def diff(master_screens_path, current_screens_path, test_name, master_hash,
         current_hash):
    doc = dominate.document(title=test_name)
    master_screens = sorted(master_screens_path.iterdir())
    current_screens = sorted(current_screens_path.iterdir())

    with doc:
        h1(test_name)
        p("This UI test differs from master.",
          style="color: grey; font-weight: bold;")
        with table():
            with tr():
                td("Master:")
                td(master_hash, style="color: red;")
            with tr():
                td("Current:")
                td(current_hash, style="color: green;")
        hr()

        with table(border=1, width=600):
            with tr():
                th("Master")
                th("Current branch")

            html.diff_table(master_screens, current_screens)

    return html.write(REPORTS_PATH / "diff", doc, test_name + ".html")
Esempio n. 3
0
def failed(fixture_test_path, test_name, actual_hash, expected_hash):
    doc = dominate.document(title=test_name)
    recorded_path = fixture_test_path / "recorded"
    actual_path = fixture_test_path / "actual"

    if not recorded_path.exists():
        recorded_path.mkdir()
    download.fetch_recorded(expected_hash, recorded_path)

    recorded_screens = sorted(recorded_path.iterdir())
    actual_screens = sorted(actual_path.iterdir())

    if not recorded_screens:
        return

    with doc:
        _header(test_name, expected_hash, actual_hash)

        with table(border=1, width=600):
            with tr():
                th("Expected")
                th("Actual")

            for recorded, actual in zip_longest(recorded_screens, actual_screens):
                if recorded and actual and filecmp.cmp(actual, recorded):
                    background = "white"
                else:
                    background = "red"
                with tr(bgcolor=background):
                    _image(recorded)
                    _image(actual)

    return _write(REPORTS_PATH / "failed", doc, test_name + ".html")
Esempio n. 4
0
def failed(fixture_test_path, test_name, actual_hash, expected_hash):
    doc = dominate.document(title=test_name)
    recorded_path = fixture_test_path / "recorded"
    actual_path = fixture_test_path / "actual"

    download_failed = False

    if not recorded_path.exists():
        recorded_path.mkdir()
    try:
        download.fetch_recorded(expected_hash, recorded_path)
    except Exception:
        download_failed = True

    recorded_screens = sorted(recorded_path.iterdir())
    actual_screens = sorted(actual_path.iterdir())

    with doc:
        _header(test_name, expected_hash, actual_hash)

        if download_failed:
            with p():
                strong("WARNING:")
                text(" failed to download recorded fixtures. Is this a new test case?")

        with table(border=1, width=600):
            with tr():
                th("Expected")
                th("Actual")

            html.diff_table(recorded_screens, actual_screens)

    return html.write(REPORTS_PATH / "failed", doc, test_name + ".html")
Esempio n. 5
0
def table(
        data: List[List[str]],
        header: Optional[List[str]] = None,
        green_value: Optional[str] = None,
        red_value: Optional[str] = None,
        red_predicate: Optional[Callable] = None
) -> None:
    """
    Print table to HTML output
    :param data: List of lines, each containing list of cell data
    :param header: optional list of header cells, no header if None or empty
    :param green_value: cell value content to highlight in green
    :param red_value: cell value content to highlight in red
    :param red_predicate: predicate on line to highlight in red
    """

    with tags.table():

        if header:
            with tags.tr():
                for cell in header:
                    tags.th(cell)

        for line in data:
            with tags.tr():
                for cell in line:
                    color = "var(--main-color)"
                    if green_value and green_value in cell:
                        color = "var(--green-color)"
                    if red_value and red_value in cell:
                        color = "var(--red-color)"
                    if red_predicate and red_predicate(line):
                        color = "var(--red-color)"
                    tags.td(cell, style="color:" + color)
Esempio n. 6
0
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 .

                OPTIONAL {
                   ?status octa:symbol ?symbol .
                }
            }

            OPTIONAL {
                ?defined_by_iri octa:url ?defined_by_url .
            }

            OPTIONAL {
                ?defined_by_iri rdfs:label ?defined_by_label .
            }
        } ORDER BY ?label
        ''')

    rows = map(build_table_row, choices)

    return table(thead(tr(
        th('Code'),
        th('Label'),
        th('Defined By'),
    )), tbody(*rows))
Esempio n. 7
0
    def build_header(l_cols):
        html_head = thead()
        with html_head:
            with tr():
                for c in l_cols:
                    th(c if isinstance(c, (unicode, str)) else str(c))

        return html_head
Esempio n. 8
0
    def set_header(self, *args, **kwargs):
        self.header = self.parse_args(*args, **kwargs)

        with self.t:
            with tr():
                for k in self.header:
                    th(k)
        return self
def make_table_header():
    h = thead()
    with h:
        r = tr()
        r.add(th('NUMBER'))
        r.add(th('TITLE'))
        r.add(th('ASSIGNEES'))
        r.add(th('PRIORITY'))
        r.add(th('LAST COMMENT'))
Esempio n. 10
0
def _report_links(tests):
    if not tests:
        i("None!")
        return
    with table(border=1):
        with tr():
            th("Link to report")
        for test in sorted(tests):
            with tr():
                path = test.relative_to(REPORTS_PATH)
                td(a(test.name, href=path))
Esempio n. 11
0
def make_html(pixdir, route_name, results):

    title = "Pictures from %s" % route_name

    document = dominate.document(title=title)

    with document.head:
        meta(charset="UTF-8")
        style("""
        table { page-break-inside:auto; border-spacing:3px; padding:3px; }
        table { margin-left:auto; margin-right:auto; }
        table, td, th, tr { border:1px solid green; }
        th { background-color: green; color: white; }
        th.tiny { width:3%; }
        th.narrow { width:47%; }
        th.wide { width:50%; }
        tr { page-break-inside:avoid; page-break-after:auto; }
        tr.center { margin-left:auto; margin-right:auto; }
        tr.alt { background-color: #f0f0f0; }
        caption { background-color: #c0c040; font-size: 16px; \
font-family: "Courier New"; }
        body { font-size: 16px; }
        @media print {
            body { font-size: 8px; font-family: "Courier New" }
            caption { font-size: 10px }
            a {
            text-decoration: none; font-style: italic; font-weight: bold}
            th { background-color: white; color: black; }
        }
        """)

    with document.body:

        with table():

            caption(route_name)

            tr(th("Name"), th("Description"), th("Imagefile"))

            for time, filename, gc, tp in results:

                pathname = os.path.join(pixdir, filename)

                gcname, gcdesc = map(str, gc[1:])
                gclink = "http://coord.info/%s" % quote(gcname)

                with tr():

                    td(a(gcname, href=gclink))
                    td(gcdesc)
                    td(a(filename, href=quote(pathname)))

    print >> open("make_html.html", "w"), document
Esempio n. 12
0
def report_links(tests, reports_path, actual_hashes=None):
    if actual_hashes is None:
        actual_hashes = {}

    if not tests:
        i("None!")
        return
    with table(border=1):
        with tr():
            th("Link to report")
        for test in sorted(tests):
            with tr(data_actual_hash=actual_hashes.get(test.stem, "")):
                path = test.relative_to(reports_path)
                td(a(test.name, href=path))
def getDescriptionPills(statistics):
    statistics = np.round(statistics, 1)

    statisticstable = table(cls='table')
    table_header_row = tr()
    table_header_row.appendChild(th('Measurements count'))
    table_header_row.appendChild(th('Mean error'))
    table_header_row.appendChild(th('Standard Error dev'))
    table_header_row.appendChild(th('Min error measured'))
    table_header_row.appendChild(th('First quartile (25%)'))
    table_header_row.appendChild(th('Median (50%)'))
    table_header_row.appendChild(th('Third quartile (75%)'))
    table_header_row.appendChild(th('Max error measured'))

    table_row = tr()
    table_row.appendChild(td(str(statistics[0])))
    table_row.appendChild(td(str(statistics[1])))
    table_row.appendChild(td(str(statistics[2])))
    table_row.appendChild(td(str(statistics[3])))
    table_row.appendChild(td(str(statistics[4])))
    table_row.appendChild(td(str(statistics[5])))
    table_row.appendChild(td(str(statistics[6])))
    table_row.appendChild(td(str(statistics[7])))

    statisticstable.appendChild(thead(table_header_row))
    statisticstable.appendChild(tbody(table_row))
    return statisticstable
Esempio n. 14
0
    def get_html(self):
        """Generates html for displaying all metadata elements associated with this logical file.
        Subclass must override to include additional html for additional metadata it supports.
        """

        root_div = div()
        dataset_name_div = div(cls="col-xs-12 content-block")
        if self.logical_file.dataset_name:
            with dataset_name_div:
                legend("Title")
                p(self.logical_file.dataset_name)

        keywords_div = div()
        if self.keywords:
            keywords_div = div(cls="col-sm-12 content-block")
            with keywords_div:
                legend('Keywords')
                with div(cls="tags"):
                    with ul(id="list-keywords-file-type",
                            cls="tag-list custom-well"):
                        for kw in self.keywords:
                            with li():
                                a(kw, cls="tag")

        extra_metadata_div = div()
        if self.extra_metadata:
            extra_metadata_div = div(cls="col-sm-12 content-block")
            with extra_metadata_div:
                legend('Extended Metadata')
                with table(cls="table table-striped funding-agencies-table",
                           style="width: 100%"):
                    with tbody():
                        with tr(cls="header-row"):
                            th("Key")
                            th("Value")
                        for k, v in self.extra_metadata.iteritems():
                            with tr(data_key=k):
                                td(k)
                                td(v)

        if self.logical_file.dataset_name:
            root_div.add(dataset_name_div)
        if self.keywords:
            root_div.add(keywords_div)
        if self.extra_metadata:
            root_div.add(extra_metadata_div)

        return root_div.render()
Esempio n. 15
0
def failed(fixture_test_path: Path, test_name: str, actual_hash: str,
           expected_hash: str) -> Path:
    ACTUAL_HASHES[test_name] = actual_hash

    doc = document(title=test_name, actual_hash=actual_hash)
    recorded_path = fixture_test_path / "recorded"
    actual_path = fixture_test_path / "actual"

    download_failed = False

    if not recorded_path.exists():
        recorded_path.mkdir()
    try:
        download.fetch_recorded(expected_hash, recorded_path)
    except Exception:
        download_failed = True

    recorded_screens = sorted(recorded_path.iterdir())
    actual_screens = sorted(actual_path.iterdir())

    with doc:
        _header(test_name, expected_hash, actual_hash)

        with div(id="markbox", _class="script-hidden"):
            p("Click a button to mark the test result as:")
            with div(id="buttons"):
                t.button("OK", id="mark-ok", onclick="markState('ok')")
                t.button("BAD", id="mark-bad", onclick="markState('bad')")

        if download_failed:
            with p():
                strong("WARNING:")
                text(
                    " failed to download recorded fixtures. Is this a new test case?"
                )

        with table(border=1, width=600):
            with tr():
                th("Expected")
                th("Actual")

            html.diff_table(
                recorded_screens,
                actual_screens,
                SCREENSHOTS_WIDTH_PX_TO_DISPLAY[test_name[:2]],
            )

    return html.write(REPORTS_PATH / "failed", doc, test_name + ".html")
Esempio n. 16
0
    def writeContent(self):
        self.writeln('<h1>Using Webware with Dominate</h1>')
        self.writeln(
            '<p>Dominate is a Python library that can be used in Webware'
            ' applications to generate HTML programmatically.</p>')
        if not dominate:
            self.writeln(
                f'<p>Please install <a href="{self.homepage}">Dominate</a>'
                ' in order to view this demo.</p>')
            return

        content = div(id='content')
        with content:
            h2('Hello World!')
            with table(cls="NiceTable").add(tbody()):
                tr(th('Demo table', colspan=3))
                r = tr()
                r += td('One')
                r.add(td('Two'))
                with r:
                    td('Three')
            para = p(__pretty=False)
            with para:
                text('This content has been produced with ')
                a('Dominate', href=self.homepage)
                text(' programmatically.')
        self.write(content)
Esempio n. 17
0
    def _create_table(self, rows):
        columns = []
        for row in rows:
            for column in row.keys():
                if column in columns:
                    continue
                columns.append(column)

        # Create table
        table = tags.table()

        thead = tags.thead()
        tr = tags.tr()
        for column in columns:
            tr += tags.th(raw(column))
        thead += tr

        tbody = tags.tbody()
        for row in rows:
            tr = tags.tr()
            for column in columns:
                tr += tags.td(row.get(column, ''))
            tbody += tr

        table += thead
        table += tbody

        return table
Esempio n. 18
0
def create_table(table_rows, *content):
    html_table = table(cellspacing="0",
                       cellpadding="5",
                       width="100%",
                       margin="0 auto",
                       border="1",
                       style="white-space:nowrap;")
    with html_table.add(thead()).add(tr()):
        for val in [
                "name", "purchase_price", "purchase_level", "min_price",
                "min_level", "min_profit", "min_percent", "relevant_price",
                "relevant_level", "relevant_profit", "relevant_percent"
        ]:
            th(val)
    with html_table:
        tbody(table_rows)
    return html(body(table(tr(td(html_table, *content)))))
Esempio n. 19
0
def recorded(fixture_test_path: Path, test_name: str,
             actual_hash: str) -> Path:
    doc = document(title=test_name)
    actual_screens = sorted(fixture_test_path.iterdir())

    with doc:
        _header(test_name, actual_hash, actual_hash)

        with table(border=1):
            with tr():
                th("Recorded")

            for screen in actual_screens:
                with tr():
                    html.image(screen,
                               SCREENSHOTS_WIDTH_PX_TO_DISPLAY[test_name[:2]])

    return html.write(REPORTS_PATH / "passed", doc, test_name + ".html")
Esempio n. 20
0
def passed(fixture_test_path, test_name, actual_hash):
    copy_tree(str(fixture_test_path / "actual"), str(fixture_test_path / "recorded"))

    doc = dominate.document(title=test_name)
    actual_path = fixture_test_path / "actual"
    actual_screens = sorted(actual_path.iterdir())

    with doc:
        _header(test_name, actual_hash, actual_hash)

        with table(border=1):
            with tr():
                th("Recorded")

            for screen in actual_screens:
                with tr():
                    html.image(screen)

    return html.write(REPORTS_PATH / "passed", doc, test_name + ".html")
Esempio n. 21
0
def failed(fixture_test_path, test_name, actual_hash, expected_hash):
    doc = dominate.document(title=test_name)
    recorded_path = fixture_test_path / "recorded"
    actual_path = fixture_test_path / "actual"

    download_failed = False

    if not recorded_path.exists():
        recorded_path.mkdir()
    try:
        download.fetch_recorded(expected_hash, recorded_path)
    except Exception:
        download_failed = True

    recorded_screens = sorted(recorded_path.iterdir())
    actual_screens = sorted(actual_path.iterdir())

    with doc:
        _header(test_name, expected_hash, actual_hash)

        if download_failed:
            with p():
                strong("WARNING:")
                text(
                    " failed to download recorded fixtures. Is this a new test case?"
                )

        with table(border=1, width=600):
            with tr():
                th("Expected")
                th("Actual")

            for recorded, actual in zip_longest(recorded_screens,
                                                actual_screens):
                if recorded and actual and filecmp.cmp(actual, recorded):
                    background = "white"
                else:
                    background = "red"
                with tr(bgcolor=background):
                    _image(recorded)
                    _image(actual)

    return _write(REPORTS_PATH / "failed", doc, test_name + ".html")
Esempio n. 22
0
 def get_key_value_metadata_html(self):
     """generates html for viewing key/vale extra metadata"""
     extra_metadata_div = div()
     if self.extra_metadata:
         extra_metadata_div = div(cls="col-sm-12 content-block")
         with extra_metadata_div:
             legend('Extended Metadata')
             with table(cls="hs-table table dataTable no-footer",
                        style="width: 100%"):
                 with thead():
                     with tr(cls="header-row"):
                         th("Key")
                         th("Value")
                 with tbody():
                     for k, v in self.extra_metadata.iteritems():
                         with tr(data_key=k):
                             td(k)
                             td(v)
     return extra_metadata_div
Esempio n. 23
0
    def _write_header(self):
        if not self.is_write_header:
            return

        tr_tag = tags.tr()
        for header in self.header_list:
            tr_tag += tags.th(header)

        thead_tag = tags.thead()
        thead_tag += tr_tag

        self._table_tag += thead_tag
def added(screens_path, test_name):
    doc = dominate.document(title=test_name)
    screens = sorted(screens_path.iterdir())

    with doc:
        h1(test_name)
        p(
            "This UI test has been added to fixtures.json.",
            style="color: green; font-weight: bold;",
        )
        hr()

        with table(border=1):
            with tr():
                th("Added files")

            for screen in screens:
                with tr():
                    html.image(screen)

    return html.write(REPORTS_PATH / "added", doc, test_name + ".html")
Esempio n. 25
0
def grid_table(data: Grid, rows: List[str], columns: List[str]):

    assert data.dimensions == 2
    assert data.size(0) == len(rows) and data.size(1) == len(columns)

    with table() as element:
        with thead():
            with tr():
                th()
                [th(table_cell(column)) for column in columns]
        with tbody():
            for i, row in enumerate(rows):
                with tr():
                    th(table_cell(row))
                    for value in data.row(i):
                        if isinstance(value, tuple):
                            if len(value) == 1:
                                value = value[0]
                        insert_cell(value, None)

    return element
def mount_ballots_to_table(cmpcvr_df: pd.DataFrame) -> tuple:
    cmpcvr_df.dropna(subset=['disagreed_info'], inplace=True)
    index = 1
    for _, row in cmpcvr_df.iterrows():
        head_row = tr(cls='',
                      data_toggle='collapse',
                      data_target=f'#collapse{index}')
        head_row += th(index), td(row['ballot_id']), td(row['style'])
        collapse_row = tr(id=f'collapse{index}', cls='collapse')
        collapse_row += td(), get_ballot_details_td(row)
        index += 1
        yield head_row, collapse_row
Esempio n. 27
0
    def _write_header(self):
        if not self.is_write_header:
            return

        tr_tag = tags.tr()
        for header in self.header_list:
            tr_tag += tags.th(header)

        thead_tag = tags.thead()
        thead_tag += tr_tag

        self._table_tag += thead_tag
Esempio n. 28
0
    def get_extra_metadata_html_form(self):
        def get_add_keyvalue_button():
            add_key_value_btn = a(cls="btn btn-success",
                                  type="button",
                                  data_toggle="modal",
                                  data_target="#add-keyvalue-filetype-modal",
                                  style="margin-bottom:20px;")
            with add_key_value_btn:
                with span(cls="glyphicon glyphicon-plus"):
                    span("Add Key/Value", cls="button-label")
            return add_key_value_btn

        if self.extra_metadata:
            root_div_extra = div(cls="col-xs-12", id="filetype-extra-metadata")
            with root_div_extra:
                legend('Extended Metadata')
                get_add_keyvalue_button()
                with table(cls="table table-striped funding-agencies-table",
                           style="width: 100%"):
                    with tbody():
                        with tr(cls="header-row"):
                            th("Key")
                            th("Value")
                            th("Edit/Remove")
                        counter = 0
                        for k, v in self.extra_metadata.iteritems():
                            counter += 1
                            with tr(data_key=k):
                                td(k)
                                td(v)
                                with td():
                                    a(data_toggle="modal",
                                      data_placement="auto",
                                      title="Edit",
                                      cls=
                                      "glyphicon glyphicon-pencil icon-button icon-blue",
                                      data_target="#edit-keyvalue-filetype-modal"
                                      "-{}".format(counter))
                                    a(data_toggle="modal",
                                      data_placement="auto",
                                      title="Remove",
                                      cls=
                                      "glyphicon glyphicon-trash icon-button btn-remove",
                                      data_target=
                                      "#delete-keyvalue-filetype-modal"
                                      "-{}".format(counter))

                self._get_add_key_value_modal_form()
                self._get_edit_key_value_modal_forms()
                self._get_delete_key_value_modal_forms()
            return root_div_extra
        else:
            root_div_extra = div(cls="row", id="filetype-extra-metadata")
            with root_div_extra:
                with div(cls="col-lg-12 content-block"):
                    legend('Extended Metadata')
                    get_add_keyvalue_button()
                    self._get_add_key_value_modal_form()
            return root_div_extra
Esempio n. 29
0
 def __get__(self, obj: Table, objtype: Any = None) -> html_tag:
     thead_ = thead(_class="bg-primary text-white")
     if obj.columns:
         tr_ = tr(_class="bg-dark text-white")
         for column in obj.columns:
             span_ = span(column, _title=column)
             class_ = "whitespace-nowrap py-2 resize-x truncate min-w-2"
             width = obj.column_width.get(column)
             style = "" if not width else f"width: {width}"
             th_ = th(span_, _class=class_, _style=style)
             tr_.add(th_)
         thead_.add(tr_)
     return thead_
Esempio n. 30
0
def create_html(prem, vip):
    keys = list(prem.keys())
    keys.sort()

    prem_table = table(style='border: 1px solid black')
    prem_table += tr(th("Currency"), th("Buy"), th("Sell"), th("Hold"))
    for key in keys:

        # hold
        if prem[key] == 0:
            prem_table += tr(td(key), td(" "), td(" "), td("Hold"))

            # buy
        elif prem[key] == 1:
            prem_table += tr(td(key), td("Buy"),
                             td(" "), td(" "))

            # sell
        else:
            prem_table += tr(td(key), td(" "), td("Sell"),
                             td(" "))

    with open('prem_table.html', 'w') as f:
        f.write(prem_table.render())

    keys_vip = list(vip.keys())
    keys_vip.sort()

    vip_table = table(style='border: 1px solid black')
    vip_table += tr(th("Currency"), th("Buy"), th("Sell"), th("Hold"))
    for key in keys_vip:

        # hold
        if vip[key] == 0:
            vip_table += tr(td(key), td(" "), td(" "), td("Hold"))

            # buy
        elif vip[key] == 1:
            vip_table += tr(td(key), td("Buy"),
                            td(" "), td(" "))

            # sell
        else:
            vip_table += tr(td(key), td(" "), td("Sell"),
                            td(" "))

    with open('vip_table.html', 'w') as f:
        f.write(vip_table.render())
Esempio n. 31
0
    def _get_field_informations_html(self):
        root_div = div(cls="content-block")
        with root_div:
            legend('Field Information')
            with table(style="width: 100%;"):
                with tbody():
                    with tr(cls='row'):
                        th('Name')
                        th('Type')
                        th('Width')
                        th('Precision')

                    for field_info in self.fieldinformations.all():
                        field_info.get_html(pretty=False)

        return root_div.render()
Esempio n. 32
0
    def _get_field_informations_html(self):
        root_div = div(cls="content-block")
        with root_div:
            legend('Field Information')
            with table(style="width: 100%;"):
                with tbody():
                    with tr(cls='row'):
                        th('Name')
                        th('Type')
                        th('Width')
                        th('Precision')

                    for field_info in self.fieldinformations.all():
                        field_info.get_html(pretty=False)

        return root_div.render()
 def get_student_grades_html(self):
     import dominate
     from dominate import tags
     page = dominate.document(title='Final Grades')
     with page:
         with tags.table(border="1"):
             number_of_assignments = self.get_number_of_assignments()
             with tags.tr():
                 tags.th("First Name")
                 tags.th("Last Name")
                 tags.th("Overall Average")
                 tags.th("Letter Grade")
                 tags.th("Scores", colspan=str(number_of_assignments))
             for student in self.sorted_students():
                 with tags.tr():
                     grade_average = student.grade_average(number_of_assignments)
                     tags.td(student.name.first)
                     tags.td(student.name.last)
                     tags.td(grade_average)
                     tags.td(self._grade_tiers.letter(grade_average))
                     for score in student.sorted_scores():
                         tags.td(score)
     return str(page)
Esempio n. 34
0
    def _write_header(self):
        tags = _get_tags_module()

        if not self.is_write_header:
            return

        if typepy.is_empty_sequence(self.headers):
            raise EmptyHeaderError("headers is empty")

        tr_tag = tags.tr()
        for header in self.headers:
            tr_tag += tags.th(MultiByteStrDecoder(header).unicode_str)

        thead_tag = tags.thead()
        thead_tag += tr_tag

        self._table_tag += thead_tag
Esempio n. 35
0
    def add(self, *items):
        """ Adds items to the table row, items are wrapped in a <td> tag if self.header is
            False, else they are wrapped in a <th> tag.
        """
        added = []
        items = parse_into_single_tuple(items)
        for item in items:
            if isinstance(item, th) or isinstance(item, td):
                added.append(super().add(item))
            elif self.header is True:
                added.append(super().add(th(item)))
            else:
                added.append(super().add(td(item)))

        if len(added) == 1:
            return added[0]
        else:
            return added
Esempio n. 36
0
def landing_page(request, page):
    content_model = page.get_content_model()
    edit_resource = page_processors.check_resource_mode(request)

    if not edit_resource:  # non-edit mode
        # get the context from hs_core
        context = page_processors.get_page_context(page, request.user, resource_edit=edit_resource,
                                                   extended_metadata_layout=None, request=request)
        extended_metadata_exists = False

        if content_model.metadata.originalcoverage:
            extended_metadata_exists = True

        context['extended_metadata_exists'] = extended_metadata_exists

        # add the original coverage context
        geom_info_for_view = {}
        geom_info = content_model.metadata.geometryinformation
        if geom_info:
            geom_info_for_view['geometryType'] = geom_info.geometryType
            geom_info_for_view['featureCount'] = geom_info.featureCount
            context['geometry_information'] = geom_info_for_view

        ori_cov_dict = {}
        ori_cov_obj = content_model.metadata.originalcoverage
        if ori_cov_obj:
            ori_cov_dict['northlimit'] = ori_cov_obj.northlimit
            ori_cov_dict['eastlimit'] = ori_cov_obj.eastlimit
            ori_cov_dict['southlimit'] = ori_cov_obj.southlimit
            ori_cov_dict['westlimit'] = ori_cov_obj.westlimit
            ori_cov_dict['projection_string'] = ori_cov_obj.projection_string
            ori_cov_dict['projection_name'] = ori_cov_obj.projection_name
            ori_cov_dict['datum'] = ori_cov_obj.datum
            ori_cov_dict['unit'] = ori_cov_obj.unit
            context['original_coverage'] = ori_cov_dict

        field_info_list = content_model.metadata.fieldinformations.all()
        field_info_list_context = []
        for field_info in field_info_list:
            field_info_dict_item = {}
            field_info_dict_item["fieldName"] = field_info.fieldName
            field_info_dict_item["fieldType"] = field_info.fieldType
            field_info_dict_item["fieldTypeCode"] = field_info.fieldTypeCode
            field_info_dict_item["fieldWidth"] = field_info.fieldWidth
            field_info_dict_item["fieldPrecision"] = field_info.fieldPrecision
            field_info_list_context.append(field_info_dict_item)
        context['field_information'] = field_info_list_context

    else:  # editing mode
        # now editing is allowed for resource specific metadata
        geom_info_for_view = {}
        geom_info = content_model.metadata.geometryinformation
        if geom_info:
            geom_info_for_view['geometryType'] = geom_info.geometryType
            geom_info_for_view['featureCount'] = geom_info.featureCount

        geom_information_form = GeometryInformationForm(initial=geom_info_for_view,
                                                        res_short_id=content_model.short_id,
                                                        allow_edit=False,
                                                        element_id=geom_info.id
                                                        if geom_info else None)

        geom_information_layout = HTML('<div class="form-group col-lg-6 col-xs-12" '
                                       'id="geometryinformation">'
                                       '{% load crispy_forms_tags %}'
                                       '{% crispy geom_information_form %}'
                                       '</div>')

        # origina coverage_form
        ori_cov_obj = content_model.metadata.originalcoverage
        ori_coverage_data_dict = {}
        if ori_cov_obj:
            ori_coverage_data_dict['projection_string'] = ori_cov_obj.projection_string
            ori_coverage_data_dict['projection_name'] = ori_cov_obj.projection_name
            ori_coverage_data_dict['datum'] = ori_cov_obj.datum
            ori_coverage_data_dict['unit'] = ori_cov_obj.unit
            ori_coverage_data_dict['northlimit'] = ori_cov_obj.northlimit
            ori_coverage_data_dict['eastlimit'] = ori_cov_obj.eastlimit
            ori_coverage_data_dict['southlimit'] = ori_cov_obj.southlimit
            ori_coverage_data_dict['westlimit'] = ori_cov_obj.westlimit

        ori_coverage_form = OriginalCoverageForm(initial=ori_coverage_data_dict,
                                                 res_short_id=content_model.short_id,
                                                 allow_edit=False,
                                                 element_id=ori_cov_obj.id
                                                 if ori_cov_obj else None)
        ori_coverage_layout = HTML('<div class="form-group col-lg-6 '
                                   'col-xs-12" id="originalcoverage"> '
                                   '{% load crispy_forms_tags %} '
                                   '{% crispy ori_coverage_form %} '
                                   '</div>')
        root_div = div(cls="col-md-12 col-sm-12 pull-left", style="margin-bottom:40px;")
        with root_div:
            legend('Field Information')
            with table(style="width: 100%;"):
                with tbody():
                    with tr(cls='row'):
                        th('Name')
                        th('Type')
                        th('Width')
                        th('Precision')

                    for field_info in content_model.metadata.fieldinformations.all():
                        field_info.get_html(pretty=False)

        ext_md_layout = Layout(geom_information_layout,
                               ori_coverage_layout,
                               HTML(root_div.render()))

        context = page_processors.get_page_context(page,
                                                   request.user,
                                                   resource_edit=edit_resource,
                                                   extended_metadata_layout=ext_md_layout,
                                                   request=request)
        context['ori_coverage_form'] = ori_coverage_form
        context['geom_information_form'] = geom_information_form

    context['edit_mode'] = edit_resource
    hs_core_context = add_generic_context(request, page)
    context.update(hs_core_context)

    return context
Esempio n. 37
0
 def get_th(heading_name):
     return th(heading_name, cls="text-muted")