Пример #1
0
    def run(self):
        header = self.options.get('header').split(',')
        lines = self._get_lines()
        regex = self.options.get('regex')
        max_cols = len(header)

        table = nodes.table()
        tgroup = nodes.tgroup(max_cols)
        table += tgroup

        col_widths = self.get_column_widths(max_cols)
        tgroup.extend(nodes.colspec(colwidth=col_width) for
                      col_width in col_widths)

        thead = nodes.thead()
        tgroup += thead
        thead += self.create_table_row(header)

        tbody = nodes.tbody()
        tgroup += tbody

        for row in lines:
            matched = re.search(regex, row)
            if matched:
                tbody += self.create_table_row(matched.groups())

        return [table]
Пример #2
0
 def build_table_from_list(self, table_data, col_widths, header_rows, stub_columns):
     table = nodes.table()
     tgroup = nodes.tgroup(cols=len(col_widths))
     table += tgroup
     for col_width in col_widths:
         colspec = nodes.colspec(colwidth=col_width)
         if stub_columns:
             colspec.attributes['stub'] = 1
             stub_columns -= 1
         tgroup += colspec
     rows = []
     for row in table_data:
         row_node = nodes.row()
         for cell in row:
             entry = nodes.entry()
             entry += cell
             row_node += entry
         rows.append(row_node)
     if header_rows:
         thead = nodes.thead()
         thead.extend(rows[:header_rows])
         tgroup += thead
     tbody = nodes.tbody()
     tbody.extend(rows[header_rows:])
     tgroup += tbody
     return table
Пример #3
0
 def build_table_from_list(self, table_data, col_widths, header_rows, stub_columns):
     table = nodes.table()
     if self.widths == 'auto':
         table['classes'] += ['colwidths-auto']
     elif self.widths: # "grid" or list of integers
         table['classes'] += ['colwidths-given']
     tgroup = nodes.tgroup(cols=len(col_widths))
     table += tgroup
     for col_width in col_widths:
         colspec = nodes.colspec()
         if col_width is not None:
             colspec.attributes['colwidth'] = col_width
         if stub_columns:
             colspec.attributes['stub'] = 1
             stub_columns -= 1
         tgroup += colspec
     rows = []
     for row in table_data:
         row_node = nodes.row()
         for cell in row:
             entry = nodes.entry()
             entry += cell
             row_node += entry
         rows.append(row_node)
     if header_rows:
         thead = nodes.thead()
         thead.extend(rows[:header_rows])
         tgroup += thead
     tbody = nodes.tbody()
     tbody.extend(rows[header_rows:])
     tgroup += tbody
     return table
Пример #4
0
    def _description_table(self, descriptions, widths, headers):
        # generate table-root
        tgroup = nodes.tgroup(cols=len(widths))
        for width in widths:
            tgroup += nodes.colspec(colwidth=width)
        table = nodes.table()
        table += tgroup

        # generate table-header
        thead = nodes.thead()
        row = nodes.row()
        for header in headers:
            entry = nodes.entry()
            entry += nodes.paragraph(text=header)
            row += entry
        thead += row
        tgroup += thead

        # generate table-body
        tbody = nodes.tbody()
        for desc in descriptions:
            row = nodes.row()
            for attr in desc:
                entry = nodes.entry()
                if not isinstance(attr, string_types):
                    attr = str(attr)
                self.state.nested_parse(ViewList([attr], source=attr),
                                        0, entry)
                row += entry
            tbody += row
        tgroup += tbody

        return table
Пример #5
0
def gen_table(columns, data):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=len(columns))
        table += tgroup
        for column in columns:
            tgroup += nodes.colspec(colwidth=1)
        thead = nodes.thead()
        tgroup += thead
        headrow = nodes.row()
        for column in columns:
            entry = nodes.entry()
            para = nodes.paragraph()
            entry += para
            header = column.header()
            para += nodes.Text(header, header)
            headrow += entry
        thead += headrow
        tbody = nodes.tbody()
        tgroup += tbody
        for obj in data:
            row = nodes.row()
            for column in columns:
                entry = nodes.entry()
                para = nodes.paragraph()
                entry += para
                para += column.data(obj)
                row += entry
            tbody += row
        return [table]
Пример #6
0
    def build_table(self):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=len(self.headers))
        table += tgroup

        # TODO(sdague): it would be really nice to figure out how not
        # to have this stanza, it kind of messes up all of the table
        # formatting because it doesn't let tables just be the right
        # size.
        tgroup.extend(
             nodes.colspec(colwidth=col_width, colname='c' + str(idx))
             for idx, col_width in enumerate(self.col_widths)
        )

        thead = nodes.thead()
        tgroup += thead

        row_node = nodes.row()
        thead += row_node
        row_node.extend(nodes.entry(h, nodes.paragraph(text=h))
                        for h in self.headers)

        tbody = nodes.tbody()
        tgroup += tbody

        rows, groups = self.collect_rows()
        tbody.extend(rows)
        table.extend(groups)

        return table
Пример #7
0
    def build_table(self, table_data):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=len(self.headers))
        table += tgroup

        tgroup.extend(
            nodes.colspec(colwidth=col_width, colname='c' + str(idx))
            for idx, col_width in enumerate(self.col_widths)
        )

        thead = nodes.thead()
        tgroup += thead

        row_node = nodes.row()
        thead += row_node
        row_node.extend(nodes.entry(h, nodes.paragraph(text=h))
                        for h in self.headers)

        tbody = nodes.tbody()
        tgroup += tbody

        rows, groups = self.get_rows(table_data)
        tbody.extend(rows)
        table.extend(groups)

        return table
Пример #8
0
    def create_table(self, data, num_headers=1):
        table_node = nodes.table()

        if len(data) > 0:
            tgroup_node = nodes.tgroup(cols=len(data[0]))
            table_node += tgroup_node

            col_width = 100 // len(data[0])
            for col_index in range(len(data[0])):
                colspec_node = nodes.colspec(colwidth=col_width)
                tgroup_node += colspec_node

            thead = nodes.thead()
            tgroup_node += thead
            tbody = nodes.tbody()
            tgroup_node += tbody
            for row_index, row in enumerate(data):
                row_node = nodes.row()
                for col_index, cell_item in enumerate(row):
                    row_node += self.create_cell(col_index, cell_item, row_index < num_headers)
                if row_index < num_headers:
                    thead += row_node
                else:
                    tbody += row_node

        return table_node
Пример #9
0
    def create_cross_table(self, app, docname, node, matrix, options):
        table = nodes.table()
        table["classes"].append("traceables-crosstable")
        tgroup = nodes.tgroup(cols=len(matrix.secondaries), colwidths="auto")
        table += tgroup

        # Add column specifications.
        tgroup += nodes.colspec(colwidth=1)
        for column in matrix.secondaries:
            tgroup += nodes.colspec(colwidth=1)

        # Add heading row.
        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        thead += row
        entry = nodes.entry()
        row += entry
        for secondary in matrix.secondaries:
            entry = nodes.entry()
            row += entry
            container = nodes.container()
            entry += container
            inline = nodes.inline()
            container += inline
            paragraph = nodes.paragraph()
            inline += paragraph
            paragraph += secondary.make_reference_node(app.builder, docname)

        # Add table body.
        tbody = nodes.tbody()
        tgroup += tbody
        for primary in matrix.primaries:
            row = nodes.row()
            tbody += row
            entry = nodes.entry()
            row += entry
            paragraph = nodes.paragraph()
            entry += paragraph
            paragraph += primary.make_reference_node(app.builder, docname)

            for is_related in matrix.get_boolean_row(primary):
                entry = nodes.entry()
                row += entry
                if is_related:
                    checkmark = traceable_checkmark()
                    entry += checkmark
                    checkmark += nodes.inline(u"\u2714", u"\u2714")
                else:
                    continue

        container = traceable_matrix_crosstable()
        container += table
        container["traceables-matrix"] = matrix
#        backward = matrix.backward_relationship.capitalize()
#        forward = matrix.forward_relationship.capitalize()
#        container["relationships"] = (forward, backward)
#        container["boolean_matrix"] = 0#boolean_matrix
#        container["secondaries"] = matrix.secondaries
        return container
 def build_table_from_list(self, table_data, num_cols, col_widths, header_rows, stub_columns):
     table = nodes.table()
     tgroup = nodes.tgroup(cols=len(col_widths))
     table += tgroup
     for col_width in col_widths:
         colspec = nodes.colspec(colwidth=col_width)
         if stub_columns:
             colspec.attributes['stub'] = 1
             stub_columns -= 1
         tgroup += colspec
     rows = []
     for row in table_data:
         row_node = nodes.row()
         for cell_index, cell in enumerate(row):
             entry = nodes.entry()
             entry += cell
             row_node += entry
             if self.bias == "left" and not cell_index:
                 remainder = num_cols - len(row)
                 if remainder:
                     entry["morecols"] = remainder
             if self.bias == "right" and cell_index == len(row) - 1:
                 remainder = num_cols - (cell_index + 1)
                 if remainder:
                     entry["morecols"] = remainder
         rows.append(row_node)
     if header_rows:
         thead = nodes.thead()
         thead.extend(rows[:header_rows])
         tgroup += thead
     tbody = nodes.tbody()
     tbody.extend(rows[header_rows:])
     tgroup += tbody
     return table
def description_table(descriptions, widths, headers):
    # generate table-root
    tgroup = nodes.tgroup(cols=len(widths))
    for width in widths:
        tgroup += nodes.colspec(colwidth=width)
    table = nodes.table()
    table += tgroup

    # generate table-header
    thead = nodes.thead()
    row = nodes.row()
    for header in headers:
        entry = nodes.entry()
        entry += nodes.paragraph(text=header)
        row += entry
    thead += row
    tgroup += thead

    # generate table-body
    tbody = nodes.tbody()
    for desc in descriptions:
        row = nodes.row()
        for col in desc:
            entry = nodes.entry()
            if not isinstance(col, basestring):
                col = str(col)
            paragraph = nodes.paragraph()
            paragraph += nodes.Text(col)
            entry += paragraph
            row += entry
        tbody += row
    tgroup += tbody

    return table
Пример #12
0
    def create_progtable(self, **attrs):
        _attrs = {
            'classes': ['progress', 'outer', 'docutils', 'field-list'],
            'colwidths': [20, 80]
        }
        _attrs.update(attrs)

        # create container elements
        node = nodes.table(classes=_attrs['classes'])
        tgroup = nodes.tgroup(cols=2)
        thead = thead = nodes.thead()
        thead += self.create_headrow()
        tbody = nodes.tbody()

        # tgroup gets:
        #  - colspec
        #  - thead
        #  - tbody
        for w in _attrs['colwidths']:
            tgroup += nodes.colspec(colwidth=w)

        # assemble the hierarchy
        tgroup += thead
        tgroup += tbody
        node += tgroup

        # return the table
        return node
Пример #13
0
def build_table(row_nodes, colwidth_list, headrow_data=None):
    """
    Creates new rst table node tree.

    Args:
        row_nodes (list): list of docutils.nodes.row nodes,
            contains actual content of the rst table
        colwidth_list (list): list of width percentages for each column,
            eg.: use [10, 90] for 2 columns, 1st has 10% width, 2nd the rest

    Returns:
        docutils.nodes.table: rst table node tree which contains given rows
    """
    table = nodes.table()
    tgroup = nodes.tgroup(cols=len(colwidth_list))
    table += tgroup
    for colwidth in colwidth_list:
        colspec = nodes.colspec(colwidth=colwidth)
        tgroup += colspec
    if headrow_data is not None:
        thead = nodes.thead()
        tgroup += thead
        head_row_node = build_row(headrow_data)
        thead += head_row_node
    tbody = nodes.tbody()
    tgroup += tbody
    for row in row_nodes:
        tbody += row
    return table
    def run(self):
        table = nodes.table('')

        ## Create table
        group = nodes.tgroup('', cols=3)
        table.append(group)
        
        for colwidth in 10,40,5:
            group.append(nodes.colspec('', colwidth=colwidth))

        head = nodes.thead('')
        group.append(head)

        body = nodes.tbody('')
        group.append(body)

        def add_row(target, *column_texts):
            row = nodes.row('')
            for text in column_texts:
                if text == None:
                    text = ""
                node = nodes.paragraph('')
                vl = ViewList()
                vl.append(text, '<autosummary>')
                self.state.nested_parse(vl, 0, node)
                try:
                    if isinstance(node[0], nodes.paragraph):
                        node = node[0]
                except IndexError:
                    pass
                row.append(nodes.entry('', node))
            target.append(row)

        def get_symbol(s):
            parametertable_path = s.split('.')
            
            for i in reversed(range(len(parametertable_path))):
                module = '.'.join(parametertable_path[:i])
                symbol = parametertable_path[i:]

                try:
                    m = __import__(str(module), fromlist='true')
                except ImportError:
                    continue
                else:
                    break

            parent = m
            for sym in symbol:
                parent = getattr(parent, sym)

            return parent

        add_row(head, 'Parameter', 'Description' , 'Unit')

        for param in get_symbol(self.arguments[0]):
            add_row(body, param.name, param.desc, param.unit)

        return [table]
Пример #15
0
def envy_resolve(app, doctree, fromdocname):
    objects = app.env.domaindata['envy']['objects']

    # add uplink info
    for holder in doctree.traverse(uplink_placeholder):
        obj = objects[holder.name]
        links = []
        for sp, pos, name, variants in obj.uplinks:
            signode = addnodes.desc_signature('', '')
            signode['first'] = False
            signode += make_refnode(app.builder, fromdocname, sp.docname, sp.iname + '-' + sp.name, addnodes.desc_addname(sp.name, sp.name), sp.name)
            text = ' {}: {}'.format(pos, name)
            signode += addnodes.desc_name(text, text)
            if variants is not None:
                text = ' [{}]'.format(variants)
                signode += addnodes.desc_annotation(text, text)
            links.append(signode)
        holder.replace_self(links)

    # add subnode list
    for holder in doctree.traverse(sub_placeholder):
        obj = objects[holder.name]
        add_variant = False
        for pos, name, child, variants in obj.subs:
            if variants is not None:
                add_variant = True
        table = nodes.table()
        headers = [(1, 'Address'), (1, 'Name'), (10, 'Description')]
        if add_variant:
            headers.insert(1, (1, 'Variants'))
        tgroup = nodes.tgroup(cols=len(headers))
        table += tgroup
        for colwidth, header in headers:
            tgroup += nodes.colspec(colwidth=colwidth)
        thead = nodes.thead()
        tgroup += thead
        headrow = nodes.row()
        for colwidth, header in headers:
            entry = nodes.entry()
            para = nodes.paragraph()
            entry += para
            para += nodes.Text(header, header)
            headrow += entry
        thead += headrow
        tbody = nodes.tbody()
        tgroup += tbody
        for pos, name, child, variants in obj.subs:
            row = nodes.row()
            row += wrap_text_entry(pos)
            if add_variant:
                row += wrap_text_entry('all' if variants is None else variants)
            row += wrap_text_entry(name)
            entry = nodes.entry()
            para = nodes.paragraph()
            entry += para
            para += make_refnode(app.builder, fromdocname, child.docname, child.iname + '-' + child.name, nodes.Text(child.brief, child.brief), obj.brief)
            row += entry
            tbody += row
        holder.replace_self([table])
Пример #16
0
    def build_links_table(self, resource):
        is_list = "is-list" in self.options

        table = nodes.table()

        tgroup = nodes.tgroup(cols=3)
        table += tgroup

        tgroup += nodes.colspec(colwidth=25)
        tgroup += nodes.colspec(colwidth=15)
        tgroup += nodes.colspec(colwidth=60)

        thead = nodes.thead()
        tgroup += thead
        append_row(thead, ["Name", "Method", "Resource"])

        tbody = nodes.tbody()
        tgroup += tbody

        request = DummyRequest()

        if is_list:
            child_resources = resource.list_child_resources
        else:
            child_resources = resource.item_child_resources

        names_to_resource = {}

        for child in child_resources:
            names_to_resource[child.name_plural] = (child, True)

        if not is_list and resource.model:
            child_keys = {}
            create_fake_resource_path(request, resource, child_keys, True)
            obj = resource.get_queryset(request, **child_keys)[0]
        else:
            obj = None

        related_links = resource.get_related_links(request=request, obj=obj)

        for key, info in related_links.iteritems():
            if "resource" in info:
                names_to_resource[key] = (info["resource"], info.get("list-resource", False))

        links = resource.get_links(child_resources, request=DummyRequest(), obj=obj)

        for linkname in sorted(links.iterkeys()):
            info = links[linkname]
            child, is_child_link = names_to_resource.get(linkname, (resource, is_list))

            paragraph = nodes.paragraph()
            paragraph += get_ref_to_resource(child, is_child_link)

            append_row(tbody, [nodes.strong(text=linkname), info["method"], paragraph])

        return table
Пример #17
0
    def create_list_table(self, matrix, options, docname):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=2, colwidths="auto")
        table += tgroup

        # Add column specifications.
        tgroup += nodes.colspec(colwidth=50)
        tgroup += nodes.colspec(colwidth=50)

        # Add heading row.
        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        thead += row
        entry = nodes.entry()
        row += entry
        backward_relationship = matrix.backward_relationship.capitalize()
        entry += nodes.paragraph(backward_relationship,
                                 backward_relationship)
        entry = nodes.entry()
        row += entry
        forward_relationship = matrix.forward_relationship.capitalize()
        entry += nodes.paragraph(forward_relationship,
                                 forward_relationship)

        # Add table body.
        tbody = nodes.tbody()
        tgroup += tbody
        for traceable in matrix.primaries:
            relatives = matrix.get_relatives(traceable)

            # Create first row with a first column.
            row = nodes.row()
            entry = nodes.entry(morerows=len(relatives) - 1)
            row += entry
            paragraph = nodes.paragraph()
            entry += paragraph
            paragraph += traceable.make_reference_node(
                self.app.builder, docname)

            for relative in relatives:
                if not row:
                    # Create subsequent rows without a first column.
                    row = nodes.row()
                tbody += row

                entry = nodes.entry()
                row += entry
                paragraph = nodes.paragraph()
                entry += paragraph
                paragraph += relative.make_reference_node(
                    self.app.builder, docname)

                row = None

        return table
Пример #18
0
    def genetic_maps_table(self, species):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=3)
        colspec = nodes.colspec(colwidth=1)
        tgroup.append(colspec)
        colspec = nodes.colspec(colwidth=1)
        tgroup.append(colspec)
        colspec = nodes.colspec(colwidth=1)
        tgroup.append(colspec)

        table += tgroup

        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        entry = nodes.entry()
        entry += nodes.paragraph(text="ID")
        row += entry
        entry = nodes.entry()
        entry += nodes.paragraph(text="Year")
        row += entry
        entry = nodes.entry()
        entry += nodes.paragraph(text="Description")
        row += entry

        thead.append(row)

        rows = []
        for genetic_map in species.genetic_maps:
            row = nodes.row()
            rows.append(row)

            map_id = self.get_genetic_map_id(species, genetic_map)
            entry = nodes.entry()
            para = nodes.paragraph()
            entry += para
            para += nodes.reference(internal=True,
                                    refid=map_id,
                                    text=genetic_map.id)
            row += entry

            entry = nodes.entry()
            entry += nodes.paragraph(text=genetic_map.citations[0].year)
            row += entry

            entry = nodes.entry()
            para = nodes.paragraph()
            entry += nodes.paragraph(text=genetic_map.description)
            row += entry

        tbody = nodes.tbody()
        tbody.extend(rows)
        tgroup += tbody

        return table
Пример #19
0
    def run(self):
        items = []

        data = list(csv.reader(self.content))
        for row in data:
            if not row:
                continue
            if len(row) == 3:
                items.append((row[0], row[1], True))
            else:
                items.append((row[0], row[1], False))

        col_widths = self.get_column_widths(2)
        title, messages = self.make_title()
        table = nodes.table()

        # Set up column specifications based on widths
        tgroup = nodes.tgroup(cols=2)
        table += tgroup
        tgroup.extend(
            nodes.colspec(colwidth=col_width) for col_width in col_widths)

        thead = nodes.thead()
        tgroup += thead
        trow = nodes.row()
        thead += trow
        trow.extend(
            nodes.entry(h, nodes.paragraph(text=h))
            for h in ("Pin", "Function"))

        tbody = nodes.tbody()
        tgroup += tbody
        for name, func, important in items:
            trow = nodes.row()
            entry = nodes.entry()
            para = nodes.paragraph()
            para += nodes.literal(text=name)
            entry += para
            trow += entry

            entry = nodes.entry()
            if important:
                para = nodes.paragraph()
                para += nodes.strong(text=func)
            else:
                para = nodes.paragraph(text=func)
            entry += para
            trow += entry
            tbody += trow

        self.add_name(table)
        if title:
            table.insert(0, title)

        return [table] + messages
Пример #20
0
def make_stat_table(nb_execution_data):

    key2header = {
        "mtime": "Modified",
        "method": "Method",
        "runtime": "Run Time (s)",
        "succeeded": "Status",
    }

    key2transform = {
        "mtime": lambda x: datetime.fromtimestamp(x).strftime("%Y-%m-%d %H:%M")
        if x
        else "",
        "method": str,
        "runtime": lambda x: "-" if x is None else str(round(x, 2)),
        "succeeded": lambda x: "✅" if x is True else "❌",
    }

    # top-level element
    table = nodes.table()
    table["classes"] += ["colwidths-auto"]
    # self.set_source_info(table)

    # column settings element
    ncols = len(key2header) + 1
    tgroup = nodes.tgroup(cols=ncols)
    table += tgroup
    colwidths = [round(100 / ncols, 2)] * ncols
    for colwidth in colwidths:
        colspec = nodes.colspec(colwidth=colwidth)
        tgroup += colspec

    # header
    thead = nodes.thead()
    tgroup += thead
    row = nodes.row()
    thead += row

    for name in ["Document"] + list(key2header.values()):
        row.append(nodes.entry("", nodes.paragraph(text=name)))

    # body
    tbody = nodes.tbody()
    tgroup += tbody

    for docname in sorted(nb_execution_data.keys()):
        data = nb_execution_data[docname]
        row = nodes.row()
        tbody += row
        row.append(nodes.entry("", nodes.paragraph(text=docname)))
        for name in key2header.keys():
            text = key2transform[name](data[name])
            row.append(nodes.entry("", nodes.paragraph(text=text)))

    return table
Пример #21
0
    def format(self, app, docname, node, matrix, options):
        #        env = app.builder.env

        table = nodes.table()
        tgroup = nodes.tgroup(cols=2, colwidths="auto")
        table += tgroup

        # Add column specifications.
        tgroup += nodes.colspec(colwidth=50)
        tgroup += nodes.colspec(colwidth=50)

        # Add heading row.
        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        thead += row
        entry = nodes.entry()
        row += entry
        backward_relationship = matrix.backward_relationship.capitalize()
        entry += nodes.paragraph(backward_relationship, backward_relationship)
        entry = nodes.entry()
        row += entry
        forward_relationship = matrix.forward_relationship.capitalize()
        entry += nodes.paragraph(forward_relationship, forward_relationship)

        # Add table body.
        tbody = nodes.tbody()
        tgroup += tbody
        for traceable in matrix.primaries:
            relatives = matrix.get_relatives(traceable)

            # Create first row with a first column.
            row = nodes.row()
            entry = nodes.entry(morerows=len(relatives) - 1)
            row += entry
            paragraph = nodes.paragraph()
            entry += paragraph
            paragraph += traceable.make_reference_node(app.builder, docname)

            for relative in relatives:
                if not row:
                    # Create subsequent rows without a first column.
                    row = nodes.row()
                tbody += row

                entry = nodes.entry()
                row += entry
                paragraph = nodes.paragraph()
                entry += paragraph
                paragraph += relative.make_reference_node(app.builder, docname)

                row = None

        return table
Пример #22
0
 def make_seq_table(self, title, data):
     hdr = 'Repeats A B C D A B C D Time A B C D E F Time A B C D E F'
     hdr = hdr.split()
     col_widths = [len(x) for x in hdr]
     ncols = len(col_widths)
     table = nodes.table()
     # set the column width specs
     tgroup = nodes.tgroup(cols=ncols)
     table += tgroup
     for col_width in col_widths:
         tgroup += nodes.colspec(colwidth=col_width)
     # add the header
     thead = nodes.thead()
     tgroup += thead
     thead += self.make_row([title], [ncols - 1])
     h1_text = [
         "#", "Use Input", "Input Val", "Ph1", "Ph1 Outputs", "Ph2",
         "Ph2 Outputs"
     ]
     h1_more = [None, 3, 3, None, 5, None, 5]
     thead += self.make_row(h1_text, h1_more)
     thead += self.make_row(hdr)
     tbody = nodes.tbody()
     tgroup += tbody
     # Add each row
     for frame in range(len(data) / 4):
         row = []
         # First we get n repeats
         rpt = data[0 + frame * 4]
         row.append(rpt)
         # Then the input use
         inMask = (data[1 + frame * 4] >> 28) & 0xF
         for i in range(4):
             row.append(inMask >> i & 1)
         # Then the input values
         inCond = (data[1 + frame * 4] >> 24) & 0xF
         for i in range(4):
             row.append(inCond >> i & 1)
         # Then the phase 1 time
         p1Len = data[2 + frame * 4]
         row.append(p1Len)
         # Then the phase 1 outputs
         p1Out = (data[1 + frame * 4] >> 16) & 0x3F
         for i in range(6):
             row.append(p1Out >> i & 1)
         # Then the phase 2 time
         p2Len = data[3 + frame * 4]
         row.append(p2Len)
         # Finally the phase 2 outputs
         p2Out = (data[1 + frame * 4] >> 8) & 0x3F
         for i in range(6):
             row.append(p2Out >> i & 1)
         tbody += self.make_row(row)
     return table
Пример #23
0
def build_table_from_list(
        table_data,
        # col_widths,
        header_rows,
        stub_columns=0,
        widths="auto"):
    """
    :param table_data: list of lists giving table data
    :param header_rows: list of header rows
    :param stub_columns: number of columns to mark as "stubs"
    """

    table = nodes.table()

    max_cols = len(table_data[0])
    col_widths = [100 // max_cols] * max_cols
    # if widths == 'auto':
    #     table['classes'] += ['colwidths-auto']
    # elif widths: # "grid" or list of integers
    #     table['classes'] += ['colwidths-given']
    table['classes'] += ['colwidths-auto']

    tgroup = nodes.tgroup(cols=max_cols)
    table += tgroup

    for col_width in col_widths:
        colspec = nodes.colspec()
        # if col_width is not None:
        #     colspec.attributes['colwidth'] = col_width
        if stub_columns:
            colspec.attributes['stub'] = 1
            stub_columns -= 1
        tgroup += colspec

    rows = []
    for row in table_data:
        row_node = nodes.row()
        for cell in row:
            entry = nodes.entry()
            entry += cell
            row_node += entry
        rows.append(row_node)

    if header_rows:
        thead = nodes.thead()
        thead.extend(rows[:header_rows])
        tgroup += thead

    tbody = nodes.tbody()
    tbody.extend(rows[header_rows:])
    tgroup += tbody

    return table
Пример #24
0
def resolve_devindex(app, doctree, fromdocname):
    env = app.builder.env

    for indexnode in doctree.traverse(device_index):
        table = nodes.table('')
        group = nodes.tgroup('',
                             nodes.colspec('', colwidth=30),
                             nodes.colspec('', colwidth=30),
                             nodes.colspec('', colwidth=30),
                             cols=3)
        table.append(group)

        group.append(
            nodes.thead(
                '',
                nodes.row(
                    '',
                    nodes.entry('', nodes.paragraph('', 'Class')),
                    nodes.entry('', nodes.paragraph('', 'Module')),
                    nodes.entry('', nodes.paragraph('', 'Description')),
                )))

        body = nodes.tbody('')
        group.append(body)

        for entry in sorted(itervalues(env.nicos_all_devices),
                            key=lambda v: v['name']):
            if not entry['module'].startswith('nicos.devices.'):
                continue
            row = nodes.row('')

            reftgt = '%s.%s' % (entry['module'], entry['name'])
            node = nodes.paragraph(
                '', '',
                addnodes.pending_xref('',
                                      nodes.Text(entry['name']),
                                      refdomain='py',
                                      reftype='class',
                                      reftarget=reftgt))
            env.resolve_references(node, fromdocname, app.builder)
            row.append(nodes.entry('', node))

            row.append(
                nodes.entry(
                    '',
                    nodes.paragraph('', '',
                                    nodes.literal('', entry['module'][6:]))))

            row.append(nodes.entry('', nodes.paragraph('', entry['blurb'])))

            body.append(row)
        indexnode.replace_self([table])
Пример #25
0
    def population_table(self, model):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=4)
        for _ in range(4):
            colspec = nodes.colspec(colwidth=1)
            tgroup.append(colspec)

        table += tgroup

        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        entry = nodes.entry()
        entry += nodes.paragraph(text="Index")
        row += entry
        entry = nodes.entry()
        entry += nodes.paragraph(text="ID")
        row += entry
        entry = nodes.entry()
        entry += nodes.paragraph(text="Sampling time")
        row += entry
        entry = nodes.entry()
        entry += nodes.paragraph(text="Description")
        row += entry
        thead.append(row)

        rows = []
        for index, population in enumerate(model.populations):
            row = nodes.row()
            rows.append(row)

            entry = nodes.entry()
            entry += nodes.paragraph(text=str(index))
            row += entry

            entry = nodes.entry()
            entry += nodes.paragraph(text=population.id)
            row += entry

            entry = nodes.entry()
            entry += nodes.paragraph(
                text=f"{population.default_sampling_time}")
            row += entry

            entry = nodes.entry()
            entry += nodes.paragraph(text=population.description)
            row += entry
        tbody = nodes.tbody()
        tbody.extend(rows)
        tgroup += tbody
        return table
Пример #26
0
    def model_parameter_table(self, species, model):
        path = pathlib.Path(f"parameter_tables/{species.id}/{model.id}.csv")
        if not path.exists():
            message = f"Skipping model parameters for {model.id} due to missing table"
            print(message)
            logger.warn(message)
            return None

        with open(path) as csv_file:
            reader = csv.reader(csv_file)
            data = list(reader)

        table = nodes.table()
        tgroup = nodes.tgroup(cols=3)
        colspec = nodes.colspec(colwidth=1)
        tgroup.append(colspec)
        colspec = nodes.colspec(colwidth=1)
        tgroup.append(colspec)
        colspec = nodes.colspec(colwidth=1)
        tgroup.append(colspec)

        table += tgroup

        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        entry = nodes.entry()
        entry += nodes.paragraph(text="Parameter Type (units)")
        row += entry
        entry = nodes.entry()
        entry += nodes.paragraph(text="Value")
        row += entry
        entry = nodes.entry()
        entry += nodes.paragraph(text="Description")
        row += entry
        thead.append(row)

        rows = []
        for row_data in data:
            row = nodes.row()
            rows.append(row)
            for entry_data in row_data:
                entry = nodes.entry()
                entry += nodes.paragraph(text=entry_data)
                row += entry

        tbody = nodes.tbody()
        tbody.extend(rows)
        tgroup += tbody

        return table
Пример #27
0
    def run(self):
        artifact_path = os.environ.get('DOCS_ROOT', './.doc')
        full_path = '{}.json'.format(
            os.path.join('../', artifact_path, self.arguments[0]))
        with open(full_path) as f:
            obj_data = json.load(f)

        p_fields = (SerializerField(f, self).process()
                    for f in obj_data['fields'])

        class_name = obj_data['class_name']

        table_fields = nodes.tbody('')
        table_fields.extend(p_fields)

        name = nodes.title('', '{}'.format(class_name))
        table_head = nodes.thead(
            '',
            nodes.row(
                '',
                nodes.entry('', p('name')),
                nodes.entry('', p('type')),
                nodes.entry('', p('description')),
            ),
        )
        tbl = nodes.table()
        tg = nodes.tgroup()
        tbl.append(tg)
        tg.append(nodes.colspec(colwidth=1))
        tg.append(nodes.colspec(colwidth=8))
        tg.append(nodes.colspec(colwidth=8))
        tg.append(table_head)
        tg.append(table_fields)

        class_descr = 'Class: *{}.{}*'.format(obj_data['class_module'],
                                              class_name)
        filter_field_param = 'Filter field: *{}*'.format(
            obj_data['field_param'])
        description = (obj_data.get('class_doc', '') or '').strip()
        full_name = self.parse(class_descr)
        filter_param = self.parse(filter_field_param)

        sections = ['', name]
        if description:
            sections.append(self.parse(description))
        sections.extend([full_name, filter_param, p('', nodes.topic('', tbl))])

        raw = nodes.section(*sections)

        target = self.parse('.. _{name}:'.format(name=class_name))
        return [target, raw]
Пример #28
0
    def build_table_from_list(self, table_data, col_widths, header_rows,
                              stub_columns):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=len(col_widths))
        table += tgroup
        for col_width in col_widths:
            colspec = nodes.colspec(colwidth=col_width)
            if stub_columns:
                colspec.attributes['stub'] = 1
                stub_columns -= 1
            tgroup += colspec
        rows = []

        # Append first row
        header_text = ['Parameter', 'Type', 'Description']
        header_row_node = nodes.row()
        for text in header_text:
            entry = nodes.entry()
            entry += [nodes.paragraph(text=text)]
            header_row_node += entry
        rows.append(header_row_node)

        for row in table_data:
            row_node = nodes.row()
            for i, cell in enumerate(row):
                entry = nodes.entry()

                # force the first column to be write in paramtype style
                if i == 0:
                    rst = ViewList()
                    rst.append(
                        """:paramtype:`{name}`""".format(name=str(cell[0][0])),
                        "", 0)
                    parsed_node = nodes.section()
                    parsed_node.document = self.state.document
                    nested_parse_with_titles(self.state, rst, parsed_node)

                    entry += [parsed_node[0]]
                else:
                    entry += cell

                row_node += entry
            rows.append(row_node)
        if header_rows:
            thead = nodes.thead()
            thead.extend(rows[:header_rows])
            tgroup += thead
        tbody = nodes.tbody()
        tbody.extend(rows[header_rows:])
        tgroup += tbody
        return table
Пример #29
0
    def build_table(self, table_data, col_widths, headers):
        table = nodes.table()

        # Set up the column specifications
        # based on the widths.
        tgroup = nodes.tgroup(cols=len(col_widths))
        table += tgroup
        tgroup.extend(
            nodes.colspec(colwidth=col_width) for col_width in col_widths
        )

        # Set the headers
        thead = nodes.thead()
        tgroup += thead
        row_node = nodes.row()
        thead += row_node
        row_node.extend(
            nodes.entry(h, nodes.paragraph(text=h)) for h in headers
        )

        # The body of the table is made up of rows.
        # Each row contains a series of entries,
        # and each entry contains a paragraph of text.
        tbody = nodes.tbody()
        tgroup += tbody
        rows = []

        for row in table_data:
            trow = nodes.row()

            for cell in row:
                rst = ViewList()
                entry = nodes.entry()
                para = nodes.paragraph()

                for elm in cell:
                    rst.append(elm, 'schema.rst', 0)

                nested_parse_with_titles(
                    self.state, rst, para
                )  # parse rst markup
                entry += para
                trow += entry

            rows.append(trow)

        tbody.extend(rows)

        # print table
        return table
Пример #30
0
    def _build_markup(self, notifications):
        content = []
        cols = ['Notification class', 'Payload class', 'Sample file link']
        table = nodes.table()
        content.append(table)
        group = nodes.tgroup(cols=len(cols))
        table.append(group)

        head = nodes.thead()
        group.append(head)

        for i in range(len(cols)):
            group.append(nodes.colspec(colwidth=1))

        body = nodes.tbody()
        group.append(body)

        # fill the table header
        row = nodes.row()
        body.append(row)
        for col_name in cols:
            col = nodes.entry()
            row.append(col)
            text = nodes.strong(text=col_name)
            col.append(text)

        # fill the table content, one notification per row
        for name, payload, sample in notifications:
            row = nodes.row()
            body.append(row)
            col = nodes.entry()
            row.append(col)
            text = nodes.literal(text=name)
            col.append(text)

            col = nodes.entry()
            row.append(col)
            text = nodes.literal(text=payload)
            col.append(text)

            col = nodes.entry()
            row.append(col)
            ref = nodes.reference(refuri=self.LINK_PREFIX +
                                  self.SAMPLE_ROOT + sample)
            txt = nodes.inline()
            col.append(txt)
            txt.append(ref)
            ref.append(nodes.literal(text=sample))

        return content
Пример #31
0
 def get_attr_table(self):
     atable = nodes.table()
     atgroup = build_node(
         nodes.tgroup('', cols=5), nodes.colspec(colwidth=10),
         nodes.colspec(colwidth=50), nodes.colspec(colwidth=20),
         nodes.colspec(colwidth=10), nodes.colspec(colwidth=10),
         nodes.thead(
             '',
             build_table_row("Name", "Description", "Values", "Required",
                             "Default")))
     atable.append(atgroup)
     atable_body = nodes.tbody()
     atgroup.append(atable_body)
     return (atable, atable_body)
Пример #32
0
def process_indigo_option_nodes(app, doctree, fromdocname):
    env = app.builder.env

    for node in doctree.traverse(optionslist):
        content = []

        tbl = nodes.table()
        tgroup = nodes.tgroup(cols=4)
        tbl += tgroup

        tgroup += nodes.colspec(colwidth=35)
        tgroup += nodes.colspec(colwidth=9)
        tgroup += nodes.colspec(colwidth=9)
        tgroup += nodes.colspec(colwidth=73)

        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        thead += row
        row += createRowEntryText('Name')
        row += createRowEntryText('Type')
        row += createRowEntryText('Default')
        row += createRowEntryText('Short description')

        tbody = nodes.tbody()
        tgroup += tbody

        content.append(tbl)

        sorted_options = sorted(env.indigo_options, key=lambda o:o['name'])

        for opt_info in sorted_options:
            row = nodes.row()
            tbody += row

            # Create a reference
            newnode = nodes.reference('', '')
            innernode = nodes.Text(opt_info['name'], opt_info['name'])
            newnode['refdocname'] = opt_info['docname']
            newnode['refuri'] = app.builder.get_relative_uri(
                fromdocname, opt_info['docname'])
            newnode['refuri'] += '#' + normalize_name(opt_info['name'])
            newnode.append(innernode)

            row += createRowEntry(newnode)
            row += createRowEntryText(opt_info['type'])
            row += createRowEntryText(opt_info['default'])
            row += createRowEntryText(opt_info['short'])

        node.replace_self(content)
Пример #33
0
    def create_table(self):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=2)
        table += tgroup
        for colwidth in (30, 70):
            tgroup += nodes.colspec(colwidth=colwidth)

        thead = nodes.thead()
        tgroup += thead
        # thead += self.create_table_row(('Topic','summary'))

        tbody = nodes.tbody()
        tgroup += tbody
        return table, tbody
Пример #34
0
    def format(self, app, docname, node, traceables, options):
        additional_attributes = options.get("attributes") or []
        columns = ["tag", "title"] + additional_attributes

        table = nodes.table()
        table["classes"].append("traceables-listtable")
        tgroup = nodes.tgroup(cols=len(columns), colwidths="auto")
        table += tgroup

        # Add column specifications.
        for attribute_name in columns:
            tgroup += nodes.colspec(colwidth=1)

        # Add heading row.
        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        thead += row
        for attribute_name in columns:
            entry = nodes.entry()
            row += entry
            container = nodes.container()
            entry += container
            text = attribute_name.capitalize()
            inline = nodes.inline(text, text)
            container += inline

        # Add table body.
        tbody = nodes.tbody()
        tgroup += tbody
        for traceable in traceables:
            row = nodes.row()
            tbody += row

            for attribute_name in columns:
                entry = nodes.entry()
                row += entry
                if attribute_name == "tag":
                    inline = nodes.inline()
                    inline += traceable.make_reference_node(
                        app.builder, docname)
                elif attribute_name == "title":
                    text = traceable.title if traceable.has_title else ""
                    inline = nodes.inline(text, text)
                else:
                    text = traceable.attributes.get(attribute_name, "")
                    inline = nodes.inline(text, text)
                entry += inline

        return table
Пример #35
0
def process_indigo_option_nodes(app, doctree, fromdocname):
    env = app.builder.env

    for node in doctree.traverse(optionslist):
        content = []

        tbl = nodes.table()
        tgroup = nodes.tgroup(cols=4)
        tbl += tgroup

        tgroup += nodes.colspec(colwidth=35)
        tgroup += nodes.colspec(colwidth=9)
        tgroup += nodes.colspec(colwidth=9)
        tgroup += nodes.colspec(colwidth=73)

        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        thead += row
        row += createRowEntryText('Name')
        row += createRowEntryText('Type')
        row += createRowEntryText('Default')
        row += createRowEntryText('Short description')

        tbody = nodes.tbody()
        tgroup += tbody

        content.append(tbl)

        sorted_options = sorted(env.indigo_options, key=lambda o: o['name'])

        for opt_info in sorted_options:
            row = nodes.row()
            tbody += row

            # Create a reference
            newnode = nodes.reference('', '')
            innernode = nodes.Text(opt_info['name'], opt_info['name'])
            newnode['refdocname'] = opt_info['docname']
            newnode['refuri'] = app.builder.get_relative_uri(
                fromdocname, opt_info['docname'])
            newnode['refuri'] += '#' + normalize_name(opt_info['name'])
            newnode.append(innernode)

            row += createRowEntry(newnode)
            row += createRowEntryText(opt_info['type'])
            row += createRowEntryText(opt_info['default'])
            row += createRowEntryText(opt_info['short'])

        node.replace_self(content)
Пример #36
0
    def format(self, app, docname, node, traceables, options):
        additional_attributes = options.get("attributes") or []
        columns = ["tag", "title"] + additional_attributes

        table = nodes.table()
        table["classes"].append("traceables-listtable")
        tgroup = nodes.tgroup(cols=len(columns), colwidths="auto")
        table += tgroup

        # Add column specifications.
        for attribute_name in columns:
            tgroup += nodes.colspec(colwidth=1)

        # Add heading row.
        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        thead += row
        for attribute_name in columns:
            entry = nodes.entry()
            row += entry
            container = nodes.container()
            entry += container
            text = attribute_name.capitalize()
            inline = nodes.inline(text, text)
            container += inline

        # Add table body.
        tbody = nodes.tbody()
        tgroup += tbody
        for traceable in traceables:
            row = nodes.row()
            tbody += row

            for attribute_name in columns:
                entry = nodes.entry()
                row += entry
                if attribute_name == "tag":
                    inline = nodes.inline()
                    inline += traceable.make_reference_node(
                        app.builder, docname)
                elif attribute_name == "title":
                    text = traceable.title if traceable.has_title else ""
                    inline = nodes.inline(text, text)
                else:
                    text = traceable.attributes.get(attribute_name, "")
                    inline = nodes.inline(text, text)
                entry += inline

        return table
Пример #37
0
    def run(self):
        tree = self.state.document.settings.env.app.doxyxml

        table = nodes.table()
        tgroup = nodes.tgroup(cols=2)

        tgroup += nodes.colspec(colwidth=50)
        tgroup += nodes.colspec(colwidth=50)

        # header
        tgroup += nodes.thead(
            '',
            nodes.row(
                '', *[
                    nodes.entry('', nodes.line(text=c))
                    for c in ["Function", "Description"]
                ]))

        # rows
        tbody = nodes.tbody()
        for c in self.content:
            name = c.strip()
            query = name.replace("&", " &")

            for elem in tree.findall(
                    "./compounddef/sectiondef/memberdef/[name='%s']" % query):
                args = ', '.join(e.text
                                 for e in elem.findall("./param/declname"))

                ref = addnodes.pending_xref('',
                                            refdomain='cpp',
                                            refexplicit=False,
                                            reftype='func',
                                            reftarget='kitty::' + name)
                ref += nodes.literal(text='%s(%s)' % (name, args))

                reft = nodes.paragraph()
                reft.extend([ref])

                func = nodes.entry('', reft)
                desc = nodes.entry(
                    '',
                    nodes.line(text=elem.findtext("./briefdescription/para")))

                tbody += nodes.row('', func, desc)

        tgroup += tbody
        table += tgroup
        return [table]
Пример #38
0
    def _build_grade_listing(self, matrix, content):

        summarytitle = nodes.subtitle(text="Grades")
        content.append(nodes.raw(text="Grades", attributes={'tagname': 'h2'}))
        content.append(summarytitle)
        table = nodes.table()
        table.set_class("table")
        table.set_class("table-condensed")
        grades = matrix.grades

        tablegroup = nodes.tgroup(cols=2)
        summarybody = nodes.tbody()
        summaryhead = nodes.thead()

        for i in range(2):
            tablegroup.append(nodes.colspec(colwidth=1))
        tablegroup.append(summaryhead)
        tablegroup.append(summarybody)
        table.append(tablegroup)
        content.append(table)

        header = nodes.row()
        blank = nodes.entry()
        blank.append(nodes.strong(text="Grade"))
        header.append(blank)

        blank = nodes.entry()
        blank.append(nodes.strong(text="Description"))
        header.append(blank)

        summaryhead.append(header)

        for grade in grades:
            item = nodes.row()
            namecol = nodes.entry()
            class_name = "label-%s" % grade.css_class
            status_text = nodes.paragraph(text=grade.title)
            status_text.set_class(class_name)
            status_text.set_class("label")
            namecol.append(status_text)
            item.append(namecol)

            notescol = nodes.entry()
            notescol.append(nodes.paragraph(text=grade.notes))
            item.append(notescol)

            summarybody.append(item)

        return content
Пример #39
0
def process_sublist(app, doctree, fromdocname):
    """Find all sub-list directives and fill it with all substitutions."""
    env = app.builder.env
    if not hasattr(env, 'substitute_all_subs'):
        env.substitute_all_subs = {}
    for node in doctree.traverse(sublist):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=3)
        table += tgroup

        # This is apparently required, the default is to divide 100
        # evenly by number of columns.
        col_widths = [33, 33, 33]
        for col_width in col_widths:
            colspec = nodes.colspec(colwidth=col_width)
            tgroup += colspec

        # Construct header row
        thead = nodes.thead()
        header = ["ID", "Original", "Replacement"]
        row_node = nodes.row()
        for cell in header:
            entry = nodes.entry()
            #entry += nodes.Text(cell)
            entry += nodes.paragraph(text=cell)
            row_node += entry
        thead.extend([row_node])
        tgroup += thead

        # Construct all rows
        rows = []
        #for id_, (original, replacement) in sorted(USED_SUBSTITUTIONS.items()):
        for id_, data in sorted(env.substitute_all_subs.items()):
            original = data['original']
            replacement = data['replacement']
            row = [id_, original, replacement]
            row_node = nodes.row()
            for cell in row:
                entry = nodes.entry()
                if cell:
                    #entry += nodes.Text(cell)
                    entry += nodes.paragraph(text=cell)
                row_node += entry
            rows.append(row_node)
        tbody = nodes.tbody()
        tbody.extend(rows)
        tgroup += tbody

        node.replace_self([table])
Пример #40
0
    def _build_grade_listing(self, matrix, content):

        summarytitle = nodes.subtitle(text="Grades")
        content.append(nodes.raw(text="Grades", attributes={'tagname': 'h2'}))
        content.append(summarytitle)
        table = nodes.table()
        table.set_class("table")
        table.set_class("table-condensed")
        grades = matrix.grades

        tablegroup = nodes.tgroup(cols=2)
        summarybody = nodes.tbody()
        summaryhead = nodes.thead()

        for i in range(2):
            tablegroup.append(nodes.colspec(colwidth=1))
        tablegroup.append(summaryhead)
        tablegroup.append(summarybody)
        table.append(tablegroup)
        content.append(table)

        header = nodes.row()
        blank = nodes.entry()
        blank.append(nodes.strong(text="Grade"))
        header.append(blank)

        blank = nodes.entry()
        blank.append(nodes.strong(text="Description"))
        header.append(blank)

        summaryhead.append(header)

        for grade in grades:
            item = nodes.row()
            namecol = nodes.entry()
            class_name = "label-%s" % grade.css_class
            status_text = nodes.paragraph(text=grade.title)
            status_text.set_class(class_name)
            status_text.set_class("label")
            namecol.append(status_text)
            item.append(namecol)

            notescol = nodes.entry()
            notescol.append(nodes.paragraph(text=grade.notes))
            item.append(notescol)

            summarybody.append(item)

        return content
Пример #41
0
    def __init__(
        self,
        state,
        state_machine,
        table_classes: typing.List[str]=['colwidths-auto'],
    ):
        self.table_node = nodes.table('', classes = table_classes)

        # state and state_machine are required by the _create_row method taken from sphinx
        self.state_machine = state_machine
        self.state = state

        self.head = nodes.thead('')
        self.body = nodes.tbody('')
        self.groups = None
Пример #42
0
 def create_table(self, head, body, colspec=None):
     table = nodes.table()
     tgroup = nodes.tgroup()
     table.append(tgroup)
     if colspec is None:
         colspec = [1 for n in range(len(head))]
     for width in colspec:
         tgroup.append(nodes.colspec(colwidth=width))
     thead = nodes.thead()
     thead.append(self.row(head))
     tgroup.append(thead)
     tbody = nodes.tbody()
     tbody.extend([self.row(r) for r in body])
     tgroup.append(tbody)
     return table
Пример #43
0
def build_table(elements, colwidths, head_rows=0, stub_columns=0, attrs={}):
    """build_table bulid table node from elements list of list.

    :param elements:
       [[col11, col12, col13], [col21, col22, col23], ...]: col is node.
    :type elements: list of list of node
    :param heads: header line nodes
    :type heads: list of node
    :param attrs: all entry node aim attrs
    """
    cols = len(colwidths)
    table = nodes.table()
    tgroup = nodes.tgroup(cols=cols)
    table += tgroup

    #colspec
    for colwidth in colwidths:
        colspec = nodes.colspec(colwidth=colwidth)
        if stub_columns:
            colspec['stub'] = 1
            stub_columns -= 1
        tgroup += colspec

    #head
    if head_rows:
        thead = nodes.thead()
        tgroup += thead
        head_elements, elements = elements[:head_rows], elements[head_rows:]
        for heads in head_elements:
            row = nodes.row()
            for cell in heads:
                entry = nodes.entry(**attrs)
                entry += cell
                row += entry
            thead += row

    #body
    tbody = nodes.tbody()
    tgroup += tbody
    for row_cells in elements:
        row = nodes.row()
        for cell in row_cells:
            entry = nodes.entry(**attrs)
            entry += cell
            row += entry
        tbody += row

    return table
Пример #44
0
 def get_attr_table(self):
     atable = nodes.table()
     atgroup = build_node(nodes.tgroup('', cols=5),
                          nodes.colspec(colwidth=10),
                          nodes.colspec(colwidth=50),
                          nodes.colspec(colwidth=20),
                          nodes.colspec(colwidth=10),
                          nodes.colspec(colwidth=10),
                          nodes.thead('',
                                      build_table_row("Name", "Description",
                                                      "Values", "Required",
                                                      "Default")))
     atable.append(atgroup)
     atable_body = nodes.tbody()
     atgroup.append(atable_body)
     return (atable, atable_body)
Пример #45
0
    def run(self):
        doc = ET.parse("doxyxml/xml/namespacetweedledum.xml")
        members = doc.findall("compounddef/sectiondef[@kind='func']/memberdef/detaileddescription/para/xrefsect/xrefdescription/[para='synthesis ']/../../../..")

        table = nodes.table()
        tgroup = nodes.tgroup(cols = 4)
        tgroup += nodes.colspec(colwidth = 50)
        tgroup += nodes.colspec(colwidth = 100)
        tgroup += nodes.colspec(colwidth = 50)
        tgroup += nodes.colspec(colwidth = 50)

        # header
        tgroup += nodes.thead('', nodes.row('', *[nodes.entry('', nodes.line(text = c)) for c in ["Function", "Description", "Expects", "Returns"]]))
        
        # body
        tbody = nodes.tbody()

        for member in members:
            text = member.find('name').text.strip()
            brief = member.find('briefdescription/para').text.strip()

            expects = "foo"
            returns = "bar"

            for e in member.findall('detaileddescription/para/xrefsect'):
                key = e.find('xreftitle').text.strip()
                value = e.find('xrefdescription/para').text.strip()

                if key == "algexpects":
                    expects = value
                elif key == "algreturns":
                    returns = value

            filename = os.path.basename(member.find('location').attrib['file'])[:-4]
            ref = nodes.reference('', text, internal = True)
            ref['refuri'] = 'synthesis/{}.html#{}'.format(filename, member.attrib["id"])
            reft = nodes.paragraph()
            reft.extend([ref])
            function = nodes.entry('', reft)
            description = nodes.entry('', nodes.line(text = brief))
            expects = nodes.entry('', nodes.line(text = expects))
            returns = nodes.entry('', nodes.line(text = returns))
            tbody += nodes.row('', function, description, expects, returns)

        tgroup += tbody
        table += tgroup
        return [table]
Пример #46
0
    def run(self):
        lverb = True
        env = self.state.document.settings.env
        src_dir = env.srcdir
        if lverb:
            print("PYTESTTABLE SRC_DIR {}".format(src_dir))
        argdct = getargs(self.arguments)
        if lverb:
            print("PYTESTTABLE ARGDCT {}".format(argdct))
        test_res_file = argdct[RESULT_FILE]
        test_file = argdct[TST_FILE]
        test_class = argdct.get(TST_CLASS, None)
        tup_lst = select_tuples(test_res_file, test_file, test_class)
        if lverb:
            print("test_file: {}, testclass: {}: got {} tests".format(
                test_file, test_class, len(tup_lst)))
        retlst = []
        my_section = nodes.section()
        table_title = argdct.get(TABLE_TITLE, None)
        if table_title is not None:
            my_section += nodes.title(text=table_title)
        my_table = nodes.table()
        my_section += my_table

        # make the table titles...
        tgroup = nodes.tgroup(cols=len(self.header))
        my_table += tgroup
        for colwidth in self.colwidths:
            tgroup += nodes.colspec(colwidth=colwidth)
        thead = nodes.thead()
        tgroup += thead
        # head row with column titles
        thead += self.make_row(self.header)

        # table body with test results
        tbody = nodes.tbody()
        tgroup += tbody
        for t in tup_lst:
            tt = (t[2] or "", nice_format(t[3] or ""), t[4] or "")
            if lverb:
                print("ROW: {}".format(tt))
            tbody += self.make_test_row(tt)
        # --
        retlst += my_section
        if lverb:
            print('returning {}'.format(retlst))
        return retlst
    def run(self):
        env = self.state.document.settings.env
        try:
            if self.arguments and self.content:
                raise self.warning('both argument and content. it is invalid')
            if self.arguments:
                dirname = os.path.dirname(env.doc2path(env.docname, base=None))
                relpath = os.path.join(dirname, self.arguments[0])
                abspath = os.path.join(env.srcdir, relpath)
                if not os.access(abspath, os.R_OK):
                    raise self.warning('JSON Schema file not readable: %s' %
                                       self.arguments[0])
                env.note_dependency(relpath)

                schema = JSONSchema.loadfromfile(abspath)
            else:
                schema = JSONSchema.loadfromfile(''.join(self.content))
        except ValueError as exc:
            raise self.error('Failed to parse JSON Schema: %s' % exc)

        headers = ['Name', 'Type', 'Description', 'Validations']
        widths = [1, 1, 1, 2]
        tgroup = nodes.tgroup(cols=len(headers))
        for width in widths:
            tgroup += nodes.colspec(colwidth=width)

        table = nodes.table('', tgroup)
        header_row = nodes.row()
        for header in headers:
            entry = nodes.entry('', nodes.paragraph(text=header))
            header_row += entry

        tgroup += nodes.thead('', header_row)
        tbody = nodes.tbody()
        tgroup += tbody
        for prop in schema:
            row = nodes.row()
            row += self.cell(prop.name)
            if prop.required:
                row += self.cell(prop.type + " (required)")
            else:
                row += self.cell(prop.type)
            row += self.cell(prop.description or '')
            row += self.cell('\n'.join(('* %s' % v for v in prop.validations)))
            tbody += row

        return [table]
Пример #48
0
def prepare_table_header(titles, widths):
    """Build docutil empty table """
    ncols = len(titles)
    assert len(widths) == ncols

    tgroup = nodes.tgroup(cols=ncols)
    for width in widths:
        tgroup += nodes.colspec(colwidth=width)
    header = nodes.row()
    for title in titles:
        header += nodes.entry('', nodes.paragraph(text=title))
    tgroup += nodes.thead('', header)

    tbody = nodes.tbody()
    tgroup += tbody

    return nodes.table('', tgroup), tbody
Пример #49
0
    def visit_table(self, element):
        headers = []
        rows = [[]]
        for ch_element in element.iter():
            if ch_element.tag == "th":
                headers.append(ch_element.text)
            elif ch_element.tag == "td":
                rows[-1].append(
                    (ch_element.text, ch_element.attrib.get("align")))
            elif ch_element.tag == "tr":
                if rows[-1]:
                    rows.append([])

        # Not: http://agateau.com/2015/docutils-snippets/
        table_node = nodes.table()
        tgroup_node = nodes.tgroup(cols=len(headers))
        table_node += tgroup_node

        # add colspec
        for x in range(len(headers)):
            tgroup_node += nodes.colspec(colwidth=1)

        # add thead
        thead_node = nodes.thead()
        tgroup_node += thead_node

        header_row_node = nodes.row()
        thead_node += header_row_node
        for header in headers:
            entry = nodes.entry()
            header_row_node += entry
            entry += nodes.paragraph(text=header)

        # add tbody
        tbody_node = nodes.tbody()
        tgroup_node += tbody_node
        for row in rows:
            row_node = nodes.row()
            for text, align in row:
                entry = nodes.entry()
                row_node += entry
                entry += nodes.paragraph(text=text, align=align)

            tbody_node += row_node

        return table_node
Пример #50
0
def prepare_table_header(titles, widths):
    """Build docutil empty table """
    ncols = len(titles)
    assert len(widths) == ncols

    tgroup = nodes.tgroup(cols=ncols)
    for width in widths:
        tgroup += nodes.colspec(colwidth=width)
    header = nodes.row()
    for title in titles:
        header += nodes.entry('', nodes.paragraph(text=title))
    tgroup += nodes.thead('', header)

    tbody = nodes.tbody()
    tgroup += tbody

    return nodes.table('', tgroup), tbody
Пример #51
0
    def run(self):
        """Generate a table summary of subcommands of a click group. 

        :param name: Name of group, as used on the command line
        :param subcommands: Display only listed subcommands or skip the section if
            empty
        :param column_names: The 
        :returns: A list with a docutil node, representing the resulting table.
        """
        self.env = self.state.document.settings.env

        command = self._load_module(self.arguments[0])

        if 'prog' not in self.options:
            raise self.error(':prog: must be specified')

        prog_name = self.options.get('prog')
        column_names = self.options.get(
            'column_names', 'Subcommand, Description')
        column_names = [s.strip() for s in column_names.split(',')]
        subcommands = self.options.get('subcommands')

        ctx = click.Context(command, info_name=prog_name)

        colwidths = [1, 2]

        table = nodes.table()

        tgroup = nodes.tgroup(cols=len(column_names))
        table += tgroup
        for colwidth in colwidths:
            tgroup += nodes.colspec(colwidth=colwidth)

        thead = nodes.thead()
        tgroup += thead
        thead += self._create_table_row(column_names)

        tbody = nodes.tbody()
        tgroup += tbody

        subcommands = _filter_commands(ctx, subcommands)
        for subcommand in subcommands:
            tbody += self._create_table_row(
                (subcommand.name, subcommand.short_help))

        return [table]
Пример #52
0
    def transform_content(self, contentnode: addnodes.desc_content) -> None:
        name = self.names[0]
        path = Path(name)
        js_path = path.with_suffix('.json')

        if not js_path.exists():
            w = self.state.reporter.warning(
                f'schema file {js_path} does not exist')
            contentnode += w
            return

        schema = json.loads(js_path.read_text())

        table = nodes.table(classes=['colwidths-auto'])
        tg = nodes.tgroup(cols=2)
        tg += nodes.colspec(colwidth=1)
        tg += nodes.colspec(colwidth=0)
        table += tg

        # set up the table heading
        head = nodes.thead()
        hrow = nodes.row()
        head += hrow
        hrow += nodes.entry('',
                            nodes.paragraph('', '', nodes.inline('', 'Field')))
        hrow += nodes.entry('',
                            nodes.paragraph('', '', nodes.inline('', 'Type')))
        tg += head

        # write the field table
        tb = nodes.tbody()
        tg += tb
        for field in schema.get('fields', []):
            row = nodes.row()
            row += nodes.entry(
                '', nodes.paragraph('', '', nodes.literal('', field['name'])))

            type = field['data_type']
            if field['nullable']:
                type += '?'
            row += nodes.entry(
                '', nodes.paragraph('', '', nodes.literal('', type)))
            tb += row

        contentnode += table
Пример #53
0
 def _make_enum_documentation(self, obj):
     def get_entry(node):
         para = addnodes.compact_paragraph()
         para += node
         entry = nodes.entry()
         entry += para
         return entry
     desc = addnodes.desc_signature()
     desc['ids'].append(obj.get_id())
     first = False
     desc += nodes.emphasis(text=u'enum')
     desc += nodes.Text(u' ')
     desc += addnodes.desc_name(text=obj.get_name())
     desc.attributes['first'] = True
     content = addnodes.desc_content()
     if obj.brief():
         para = nodes.paragraph()
         para += nodes.emphasis(text='Brief: ')
         para += nodes.Text(' '.join(obj.brief()))
         content += para
     table, body = nodes.table(), nodes.tbody()
     tgroup = nodes.tgroup(cols=3)
     thead = nodes.thead()
     for it in [20, 10, 70]:
         tgroup += nodes.colspec(colwidth=it)
     tgroup += thead
     tgroup += body
     table += tgroup
     head_row = nodes.row()
     for it in ['Name', 'Value', 'Brief']:
         head_row += get_entry(nodes.Text(it))
     thead += head_row
     for val in sorted(obj.values):
         row = nodes.row()
         row += get_entry(nodes.literal(text=val.name))
         tmp = [val.value if val.value is not None else '',
         ' '.join(val.brief())]
         for it in tmp:
             row += get_entry(nodes.Text(it))
         body += row
     content += table
     return (desc, content)
Пример #54
0
    def _build_grade_listing(self, matrix, content):

        summarytitle = nodes.title(text="Grades")
        content.append(summarytitle)
        table = nodes.table()
        grades = matrix.grades

        tablegroup = nodes.tgroup(cols=2)
        summarybody = nodes.tbody()
        summaryhead = nodes.thead()

        for i in range(2):
            tablegroup.append(nodes.colspec(colwidth=1))
        tablegroup.append(summaryhead)
        tablegroup.append(summarybody)
        table.append(tablegroup)
        content.append(table)

        header = nodes.row()
        blank = nodes.entry()
        blank.append(nodes.strong(text="Grade"))
        header.append(blank)

        blank = nodes.entry()
        blank.append(nodes.strong(text="Description"))
        header.append(blank)

        summaryhead.append(header)

        for grade in grades:
            item = nodes.row()
            namecol = nodes.entry()
            namecol.append(nodes.paragraph(text=grade.title))
            item.append(namecol)

            notescol = nodes.entry()
            notescol.append(nodes.paragraph(text=grade.notes))
            item.append(notescol)

            summarybody.append(item)

        return content
Пример #55
0
    def buildTableNode(self):

        colwidths    = self.directive.get_column_widths(self.max_cols)
        if isinstance(colwidths, tuple):
            # Since docutils 0.13, get_column_widths returns a (widths,
            # colwidths) tuple, where widths is a string (i.e. 'auto').
            # See https://sourceforge.net/p/docutils/patches/120/.
            colwidths = colwidths[1]
        stub_columns = self.directive.options.get('stub-columns', 0)
        header_rows  = self.directive.options.get('header-rows', 0)

        table = nodes.table()
        tgroup = nodes.tgroup(cols=len(colwidths))
        table += tgroup


        for colwidth in colwidths:
            colspec = nodes.colspec(colwidth=colwidth)
            # FIXME: It seems, that the stub method only works well in the
            # absence of rowspan (observed by the html buidler, the docutils-xml
            # build seems OK).  This is not extraordinary, because there exists
            # no table directive (except *this* flat-table) which allows to
            # define coexistent of rowspan and stubs (there was no use-case
            # before flat-table). This should be reviewed (later).
            if stub_columns:
                colspec.attributes['stub'] = 1
                stub_columns -= 1
            tgroup += colspec
        stub_columns = self.directive.options.get('stub-columns', 0)

        if header_rows:
            thead = nodes.thead()
            tgroup += thead
            for row in self.rows[:header_rows]:
                thead += self.buildTableRowNode(row)

        tbody = nodes.tbody()
        tgroup += tbody

        for row in self.rows[header_rows:]:
            tbody += self.buildTableRowNode(row)
        return table
Пример #56
0
 def get_rows(self, table_data):
     rows = []
     groups = []
     for row in table_data:
         sub_table_data = None
         if self.descend:
             for elem in row:
                 if isinstance(elem, list):
                     sub_table_data = row.pop(row.index(elem))
                     break
         trow = nodes.row()
         ncols = len(row)
         for idx, cell in enumerate(row):
             if self.spantolast and \
                     ncols < self.max_cols and idx == ncols - 1:
                 morecols = self.max_cols - ncols
                 entry = nodes.entry(morecols=morecols)
             else:
                 entry = nodes.entry()
             para = nodes.paragraph(text=unicode(cell))
             entry += para
             trow += entry
         if self.descend and sub_table_data:
             subtgroup = nodes.tgroup(cols=len(self.headers))
             subtgroup.extend(
                 nodes.colspec(
                     colwidth=col_width, colname='c' + str(idx)
                 ) for idx, col_width in enumerate(self.col_widths)
             )
             subthead = nodes.thead()
             subtgroup += subthead
             subthead += trow
             subtbody = nodes.tbody()
             subtgroup += subtbody
             sub_rows, sub_groups = self.get_rows(sub_table_data)
             subtbody.extend(sub_rows)
             groups.append(subtgroup)
             groups.extend(sub_groups)
         else:
             rows.append(trow)
     return rows, groups
Пример #57
0
    def build_table(self, table_data, col_widths):
        table = nodes.table()

        # Set up the column specifications
        # based on the widths.
        tgroup = nodes.tgroup(cols=len(col_widths))
        table += tgroup
        tgroup.extend(nodes.colspec(colwidth=col_width)
                      for col_width in col_widths)

        # Set the headers
        thead = nodes.thead()
        tgroup += thead
        row_node = nodes.row()
        thead += row_node
        row_node.extend(
            nodes.entry(h, nodes.paragraph(text=h))
            for h in self.HEADERS
        )

        # The body of the table is made up of rows.
        # Each row contains a series of entries,
        # and each entry contains a paragraph of text.
        tbody = nodes.tbody()
        tgroup += tbody
        rows = []
        for row in table_data:
            trow = nodes.row()
            # Iterate over the headers in the same order every time.
            for h in self.HEADERS:
                # Get the cell value from the row data, replacing None
                # in re match group with empty string.
                cell = row.get(self.HEADER_MAP[h]) or ''
                entry = nodes.entry()
                para = nodes.paragraph(text=unicode(cell))
                entry += para
                trow += entry
            rows.append(trow)
        tbody.extend(rows)

        return table
Пример #58
0
 def __make_list(self, obj, _lst, _type):
     def get_entry(node):
         para = addnodes.compact_paragraph()
         para += node
         entry = nodes.entry()
         entry += para
         return entry
     table, body, tgroup = nodes.table(), nodes.tbody(), nodes.tgroup(cols=2)
     thead = nodes.thead()
     tgroup += nodes.colspec(colwidth=20)
     tgroup += nodes.colspec(colwidth=80)
     tgroup += thead
     tgroup += body
     table += tgroup
     head_row = nodes.row()
     head_row += get_entry(nodes.Text('Name'))
     head_row += get_entry(nodes.Text('Brief'))
     thead += head_row
     kwargs = {
         'refdomain': 'cpp',
         'refexplicit': False,
         'reftype': _type,
     }
     for it in sorted(_lst):
         row = nodes.row()
         subobj = self._get_obj(unicode(it.get_name()))
         if subobj is not None:
             kwargs['reftarget'] = unicode(it.get_name())
             ref = addnodes.pending_xref('', **kwargs)
             ref += nodes.literal(text=unicode(subobj.name))
         else:
             kwargs['reftarget'] = unicode(it.name)
             ref = addnodes.pending_xref('', **kwargs)
             ref += nodes.literal(text=unicode(it.name))
         row += get_entry(ref)
         texts = None
         if subobj is not None and subobj.brief():
             texts = nodes.Text(' '.join(subobj.brief()))
         row += get_entry(texts)
         body += row
     return table
Пример #59
0
def build_table_from_list(table_data, col_widths):
    table = nodes.table()
    tgroup = nodes.tgroup(cols=len(col_widths))
    table += tgroup
    for col_width in col_widths:
        colspec = nodes.colspec(colwidth=col_width)
        tgroup += colspec
    rows = []
    for row in table_data:
        row_node = nodes.row()
        for cell in row:
            entry = nodes.entry()
            entry += cell
            row_node += entry
        rows.append(row_node)
    thead = nodes.thead()
    thead.extend(rows[:1])
    tgroup += thead
    tbody = nodes.tbody()
    tbody.extend(rows[1:])
    tgroup += tbody
    return table