def quadro_planejamento(self, planejamento_acoes): with self.create( LongTabu("|X[1,l]|X[3,l]|X[6,l]|")) as tabela_planejamento: tabela_planejamento.add_hline() tabela_planejamento.add_row( (MultiColumn(3, align='|c|', data=bold('Cronograma de Ações')), )) tabela_planejamento.add_hline() tabela_planejamento.add_row( (bold('Prazo'), bold('Ação'), bold('Prioridade'))) tabela_planejamento.add_hline() tabela_planejamento.end_table_header() tabela_planejamento.add_hline() tabela_planejamento.add_row( (MultiColumn(3, align='|r|', data='Continua na próxima página'), )) tabela_planejamento.add_hline() tabela_planejamento.end_table_footer() tabela_planejamento.end_table_last_footer() for acao in planejamento_acoes: metas = acao['metas'] if not len(metas): continue col_meta = MultiRow(len(metas), data=acao['prazo'].capitalize()) row = [col_meta, acao['acao'], '1. ' + metas[0]] tabela_planejamento.add_row(row) for meta in metas[1:]: tabela_planejamento.add_row( ('', '', (str(metas.index(meta) + 1) + '. ' + meta))) tabela_planejamento.add_hline()
def quadro_epis(self, fichas_exposicao): with self.create(LongTabu("|X[l]|X[l]|")) as tabela_epi: tabela_epi.add_hline() tabela_epi.add_row( (MultiColumn(2, align='|c|', data=bold('Quadro Demonstrativo de EPIs')), )) tabela_epi.add_hline() tabela_epi.add_row((bold('Função'), bold('EPIs Indicados'))) tabela_epi.add_hline() tabela_epi.end_table_header() tabela_epi.add_row( (MultiColumn(2, align='|c|', data='Continua na próxima página'), )) tabela_epi.add_hline() tabela_epi.end_table_footer() tabela_epi.end_table_last_footer() for ficha in fichas_exposicao: epis = ficha['epis'] if not len(epis): continue col_cargo = MultiRow(len(epis), data=ficha['cargo']) row = [col_cargo, epis[0]] tabela_epi.add_row(row) for epi in epis[1:]: tabela_epi.add_row(('', epi)) tabela_epi.add_hline()
def genenerate_longtabu(): geometry_options = { "margin": "2.54cm", "includeheadfoot": True } doc = Document(page_numbers=True, geometry_options=geometry_options) # Generate data table with doc.create(LongTable("l l l")) as data_table: data_table.add_hline() data_table.add_row(["header 1", "header 2", "header 3"]) data_table.add_hline() data_table.end_table_header() data_table.add_hline() data_table.add_row((MultiColumn(3, align='r', data='Containued on Next Page'),)) data_table.add_hline() data_table.end_table_footer() data_table.add_hline() data_table.add_row((MultiColumn(3, align='r', data='Not Containued on Next Page'),)) data_table.add_hline() data_table.end_table_last_footer() row = ["Content1", "9", "Longer String"] for i in range(150): data_table.add_row(row) doc.generate_pdf("longtable", clean_tex=False)
def generate_user_story(user_story: UserStory, locale: LocaleDictionary, paragraph: Paragraph) -> Paragraph: with paragraph.create(Tabularx(table_spec="|X|X|", row_height="1.4")) as tabularx: tabularx: Tabularx definitions_of_done = Itemize() for definition_of_done in user_story.definitions_of_done: definitions_of_done.add_item(definition_of_done) comments = Itemize() for comment in user_story.comments: comments.add_item(comment) tabularx.add_row( [MultiColumn(2, data=bold(user_story.name), color="gray")]) tabularx.add_row([f"{locale.as_user}: ", f"{locale.user_want}: "]) tabularx.add_row([user_story.user, user_story.action]) if user_story.description is not None: tabularx.add_row([ MultiColumn( 2, align=NoEscape("|p{\\rowWidth}|"), data=[f"{locale.description}: ", user_story.description], color="gray") ]) if len(user_story.definitions_of_done) > 0: tabularx.add_row([ MultiColumn(2, align=NoEscape("|p{\\rowWidth}|"), data=[ f"{locale.definition_of_done}: ", definitions_of_done ]) ]) if len(user_story.assignments) > 0: tabularx.add_row([ MultiColumn(2, align=NoEscape("|p{\\rowWidth}|"), data=[ f"{locale.assignation}: ", ", ".join(user_story.assignments) ], color="gray") ]) tabularx.add_row([ f"{locale.estimated_duration}: ", f"{user_story.estimated_duration:g} {locale.man_days} ({int(user_story.estimated_duration * 8)}" f" {locale.hours})" ]) tabularx.add_row( [f"{locale.status}: ", user_story.status.translate(locale)]) if len(user_story.comments) > 0: tabularx.add_row([ MultiColumn(2, align=NoEscape("|p{\\rowWidth}|"), data=[f"{locale.comments}: ", comments], color="gray") ]) return paragraph
def create_long_table( doc, parameters, skip_parameters=[], table_specs=r"|p{0.45\linewidth}|p{0.45\linewidth}|", header=[bold("Parameter"), bold("Value")], ): """ Helper function to create long table for parameters Arguments: doc: document to add table parameters: parameters dict skip_parameters: list of parameters to skip table_specs: latex specific table settings header: list with column names """ columns = len(header) with doc.create(LongTable(table_spec=table_specs)) as data_table: # Table header data_table.add_hline() data_table.add_row(header) data_table.add_hline() data_table.end_table_header() data_table.add_row((MultiColumn(columns, align="r", data="Continued on Next Page"), )) data_table.end_table_footer() data_table.add_row((MultiColumn(columns, align="r", data="End of Table"), )) data_table.end_table_last_footer() for item in parameters: if item not in skip_parameters: data_table.add_row([item, str(parameters[item])]) data_table.add_hline()
def addAppendix(self, apdx): """Adds mapping tables as an appendix to the report. For the specified (apdx) csv file in the appendix folder, it will create a table with either 2/3-columns specifying the mapping values. Note that this might not work well with extremely long mapping tables. """ mappingTable = pd.read_csv(apdx, header=None) colNum = len(mappingTable.columns) apdx_name = os.path.basename(apdx) # for printing if colNum == 2: hdr_format = 'l X[l]' col_names = ['Original', 'Category'] mappingTable.columns = col_names mappingTable = mappingTable.groupby('Category')['Original'].apply( list).reset_index() tbl_type = LongTabularx(hdr_format, width_argument=NoEscape(r'0.9\textwidth')) elif colNum == 3: hdr_format = 'l l l' col_names = ['Lower', 'Upper', 'Category'] tbl_type = Tabular(hdr_format) self.doc.append(Subsection('{}'.format(apdx_name.replace('_', ' ')))) with self.doc.create(tbl_type) as appendix: appendix.add_hline() appendix.add_row(col_names) appendix.add_hline() if colNum == 2: appendix.end_table_header() appendix.add_hline() appendix.add_row( (MultiColumn(colNum, align='r', data='Continued on Next Page'), )) appendix.end_table_footer() appendix.add_hline() appendix.add_row( (MultiColumn(colNum, align='r', data='Not Continued on Next Page'), )) appendix.end_table_last_footer() # Iterate through each row in the csv. for i, rw in mappingTable.iterrows(): row = [rw[j] for j in range(colNum)] appendix.add_row(row) appendix.add_hline() self.doc.append(LineBreak()) return
def _document_aggregate_table(self, tests: List[Dict[str, Any]]) -> None: """Document a result table of aggregate tests. Args: tests: List of corresponding test dictionary to make a table. """ with self.doc.create(LongTable('|c|p{8cm}|p{7.3cm}|', booktabs=True)) as tabular: package = Package('seqsplit') if package not in tabular.packages: tabular.packages.append(package) # add table heading tabular.add_row((MultiColumn(size=1, align='|c|', data="Test ID"), MultiColumn(size=1, align='c|', data="Test Description"), MultiColumn(size=1, align='c|', data="Input Value"))) # add table header and footer tabular.add_hline() tabular.end_table_header() tabular.add_hline() tabular.add_row((MultiColumn(3, align='r', data='Continued on Next Page'), )) tabular.add_hline() tabular.end_table_footer() tabular.end_table_last_footer() for idx, test in enumerate(tests): if idx > 0: tabular.add_hline() inp_data = [ f"{arg}={self.sanitize_value(value)}" for arg, value in test["inputs"].items() ] inp_data = [WrapText(data=x, threshold=27) for x in inp_data] des_data = [ WrapText(data=x, threshold=27) for x in test["description"].split(" ") ] row_cells = [ self.test_id, IterJoin(data=des_data, token=" "), IterJoin(data=inp_data, token=escape_latex(", \n")), ] tabular.add_row(row_cells) self.test_id += 1
def create_comp_table(self): self.append(LineBreak()) self.append(Command("scriptsize")) total_concp = 0 with self.create( Tabu(r"|X[2]|X[c]|X[c]|X[c]|X[c]|X[c]|X[c]|X[c]|", to=r"\textwidth", width=8)) as data_table: data_table.add_hline() data_table.add_row( [ "Компонент", "Сод., \%", "$C_i$", "$X_i$", "$Z_i$", "$\lg W_i$", "$W_i$", "$K_i$" ], #mapper=bold, color="gray", escape=False) data_table.add_hline() for key, val in self.components.items(): data_table.add_row([ key, val['concp'], val['concr'], val['xi'], val['zi'], val['lgw'], val['w'], val['k'] ]) total_concp += float(val['concp']) data_table.add_hline() data_table.add_row(("Компонентов учтено", str(total_concp) + " %", MultiColumn(6, align='r|', data=''))) data_table.add_hline() data_table.add_row([ MultiColumn(7, align='|r|', data='Показатель К степени опасности отхода:'), self.k ]) data_table.add_hline() data_table.add_row((MultiColumn(7, align='|r|', data='Класс опасности отхода:'), self.safety_class)) data_table.add_hline() self.append(Command("normalsize")) self.append(Command("bigskip")) self.append(LineBreak())
def cria_segunda_secao(self): redacoes_notas = { '1ª Redação': [], '2ª Redação': [], '3ª Redação': [], '4ª Redação': [], 'Médias': True } path_graf_gerais = [] graficos_gerais = [] table_sup = Tabular('c c') table_inf = Tabular('c c') table_sup.add_row([MultiColumn(2, align='c')]) table_inf.add_row([MultiColumn(2, align='c')]) for i in range(3): # print(self.notas) marcadores = list(self.notas[i][1:5]) if marcadores[i] < 0: marcadores[i] = 0 print(marcadores) for aluno in self.alunos_ids: notas = busca_notas(aluno[0], str(i + 1), self.banco)[0][1:5] redacoes_notas['1ª Redação'].append(notas[0]) redacoes_notas['2ª Redação'].append(notas[1]) redacoes_notas['3ª Redação'].append(notas[2]) redacoes_notas['4ª Redação'].append(notas[3]) for red in redacoes_notas: redacoes_notas[red] = [mean(redacoes_notas[red]).round(2)] if redacoes_notas[red][0] < 0: redacoes_notas[red][0] = 0 path_graf_gerais.append( self.cria_grafico_com_marcadores(dados=redacoes_notas, marcadores=marcadores)) for g in path_graf_gerais: graficos_gerais.append( StandAloneGraphic(filename=g, image_options='width = 190 px')) table_sup.add_row([graficos_gerais[0], graficos_gerais[1]]) table_inf.add_row([graficos_gerais[2], graficos_gerais[2]]) # graf_comparacao_1 = StandAloneGraphic(filename = path_graf_gerais[0], image_options = 'width = 190 px') return [table_sup, table_inf]
def create_latex_file(pokemon, list_of_normal_ivs, list_of_boosted_ivs): geometry_options = { "landscape": True, "margin": "0.5in", "headheight": "20pt", "headsep": "10pt", "includeheadfoot": True } doc = Document(page_numbers=True, geometry_options=geometry_options) doc.add_color('color100', 'rgb', rgb_to_dumb_string(0, 207, 194)) doc.add_color('color98', 'rgb', rgb_to_dumb_string(60, 141, 1)) doc.add_color('color96', 'rgb', rgb_to_dumb_string(72, 165, 6)) doc.add_color('color93', 'rgb', rgb_to_dumb_string(242, 183, 8)) doc.add_color('color91', 'rgb', rgb_to_dumb_string(246, 96, 0)) section = Section(f'{pokemon.name} IV Chart') table = Tabular('|c|c|c|c|c|c|', row_height=1.5) table.add_hline() table.add_row((MultiColumn( 6, align='|c|', data=TextColor('white', pokemon.name), color='black'), ), ) table.add_row( (MultiColumn(1, align='|c', data='Lv20'), MultiColumn(1, align='c|', data='Lv25'), MultiColumn(3, align='c|', data='IV'), MultiColumn(1, align='|c|', data='%'))) for index in range(len(list_of_normal_ivs)): n_iv = list_of_normal_ivs[index] b_iv = list_of_boosted_ivs[index] row_data = (f'{n_iv.cp}', f'{b_iv.cp}', f'{n_iv.attack}', f'{n_iv.defense}', f'{n_iv.stamina}', f'{n_iv.perfection_percent_rounded}') table.add_hline() table.add_row(row_data, color=color_by_iv(n_iv.perfection_percent_rounded)) section.append(table) doc.append(section) doc.generate_tex(f'latex/{pokemon.name}') doc.generate_pdf(f'pdf/{pokemon.name}')
def GPIOLoopback_report(self): self.doc.append(NoEscape(r'\clearpage')) with self.doc.create(Section('GPIO Loopback')): with self.doc.create(Subsection('Description')): self.doc.append( 'This test asserts the correct assembly of the GPIO pins on both RFFEuC\'s headers.' ) self.doc.append( 'In the TestBoard all GPIO pins are connected in pairs via a 1K1 resistor, so they\'re logically binded.\n' ) self.doc.append( 'Each pin in the loopback pair is tested as an Input and Output, changing the logic level of its pair to assert the electrical connection.\n' ) with self.doc.create(Subsection('Results')): with self.doc.create(Center()) as centered: with centered.create(Tabular('|c|c|c|', row_height=1.2)) as tbl: tbl.add_hline() tbl.add_row((MultiColumn(2, align='|c|', data=bold('Loopback Pair')), bold('Result'))) tbl.add_hline() for key, val in self.test_results['gpio'].items(): if isinstance(val, dict): tbl.add_row( val['pin1'], val['pin2'], ('Pass' if val['result'] else 'Fail'), color=('green' if val['result'] else 'red')) tbl.add_hline()
def produce_table(): # create document structure doc = Document("testtable") section = Section('Produce accessories table') test1 = Subsection('Test accessories table production') # test input code bench = [('Incline BP (4 x 12)'), ('Pull up (4 x Max)')] # test code accesory = bench table = Tabular('|c|c|c|c|c|c|c|c|c|') table.add_hline() table.add_row((MultiColumn(9, align='|c|', data='Accessories'), )) table.add_hline() table.add_row(('Exercise', 'Weight', 'Reps', 'Weight', 'Reps', 'Weight', 'Reps', 'Weight', 'Reps')) table.add_hline() for i in range(len(accesory)): table.add_row((str(accesory[i]), '', '', '', '', '', '', '', '')) table.add_hline() # append table to document test1.append(table) section.append(test1) doc.append(section) doc.generate_pdf(clean_tex=True)
def test_table(): # Tabular t = Tabular(table_spec='|c|c|', data=None, pos=None) t.add_hline(start=None, end=None) t.add_row(cells=(1, 2), escape=False) t.add_multicolumn(size=2, align='|c|', content='Multicol', cells=None, escape=False) t.add_multirow(size=3, align='*', content='Multirow', hlines=True, cells=None, escape=False) # MultiColumn/MultiRow. t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'), )) t.add_row((MultiRow(size=2, width='*', data='MultiRow'), ))
def add_static_cols(row, line, config): """ A function used to add the 14 first static columns. Those columns don't depend on the config.bench file. """ f = clean_formula(line[0]) # TODO: define math operators for formula m = line[1] f_type = line[2] c = line[9] if all_aut_are_det(line, config): c_str = line[9] else: c_str = SetColor(arguments=ColorArgument('Red', line[9])) dtgba_st = line[3] dtgba_tr = line[5] dtgba_acc = line[6] dtgba_time = '%.2f' % round(float(line[10]), 2) dba_st = line[13] dba_tr = line[15] dba_time = line[20] row.append(f) # formula row.append(m) row.append(get_type(f_type)) # trad -> T, TCONG -> P, DRA -> R, WDBA -> W row.append(c_str) # is complete or not row.append(get_dra_st(line, c)) row.append(dtgba_st) row.append(dtgba_tr) row.append(dtgba_acc) row.append(dtgba_time) row.append(dba_st) row.append(dba_tr) if '-' in dba_time or '!' in dba_time: row.append(dba_time) else: row.append('%.2f' % round(float(dba_time), 2)) # DBAminimizer length = len(line) for i in range(0, length): if 'dbaminimizer' in line[i]: if '-' in line[i + 1]: row.append(MultiColumn(2, align='|c', data='(killed)')) elif 'n/a' in line[i + 1]: row.append('') row.append('') else: minimizer_st = int(line[i + 1]) - 1 + int(c) if minimizer_st < int(dba_st): row.append( SetColor(arguments=ColorArgument( 'Gray', str(minimizer_st)))) elif minimizer_st > int(dba_st): row.append( SetColor( arguments=ColorArgument('Red', str(minimizer_st)))) else: row.append(minimizer_st) row.append('%.2f' % round(float(line[i + 2]), 2))
def _subtable(self, idx, subK, octets): """ Generates latex code for a ccsds keys table Args: * idx (int): the index of the current sub-table in case the trousseau needs to be split into several tables * subK (list of keys): the list of keys to generate table on * octets (bool): corresponding to trousseau.octets """ titles = ('Name', 'Start', 'Len', 'Value') table = Tabular('|'.join(['l'] + ['c'] * (len(titles) - 1))) if idx > 0: table.add_row((MultiColumn(len(titles), align='c', data=italic("Continued")), )) table.add_row(titles) unit = "octets" if octets else "bits" table.add_hline() table.add_hline() start_bit = 0 for cle in subK: if not cle.relative_only: start_bit = cle.start # if no padding, allows flexible len of the ccsdskey the_len = cle.len if cle.pad else "[0..{:d}]".format(cle.len) if cle.isdic: if cle.dic_force is not None: the_type = repr(cle.dic[cle.dic_force]) else: the_type = repr(cle.dic.values()) else: the_type = re.search(r'type *= *([\S ]+)', getattr(cle._fctunpack, 'func_doc', '')) if the_type is None: the_type = '-' else: the_type = the_type.group(1) table.add_row((cle.name, start_bit, the_len, the_type)) start_bit += cle.len table.add_row((MultiColumn(len(titles), align='c', data='"Start" and "Len" are given in {}'\ .format(unit)),)) return table
def latex(self): from pylatex import Document, Section, Subsection, Tabular, MultiColumn,\ MultiRow width = '|' for i in range(0, self.__maxColumns()): width += 'c|' t = Tabular(width) colsWidth = [] for c in self.children[0].children: colsWidth.append(c.width) for r in self.children: if r.hasHline: if r.isFullWidthHline(): t.add_hline() else: start = 1 cellsCount = 0 end = 0 hline = False lastCell = None for i, c in enumerate(r.children): if c.isHline: if start == 1: start = r.children.index(c) + 1 cellsCount += c.colspan if i == len(r.children) - 1: end = start + cellsCount - 1 t.add_hline(start=start, end=end) else: end = start + cellsCount - 1 if (start > 0 and end >= start): t.add_hline(start=start, end=end) start = end + 1 else: start = start + c.colspan cellsCount = 0 end = 0 else: cellsObjects = r.children cells = [] i = 0 for c in cellsObjects: if c.colspan == 1: cells.append(str(c.content)) else: cells.append( MultiColumn(c.colspan, align='|c|', data=str(c.content))) t.add_row(cells) return t
def write_header(table, config): """ Function that write the first lines of the document. """ # Static datas data_row1 = ne('Column ') + bold('type') + \ ne(' shows how the initial det. aut. was obtained: T = translation' ' produces DTGBA; W = WDBA minimization works; P = powerset ' 'construction transforms TBA to DTBA; R = DRA to DBA.') data_row2 = ne('Column ') + bold('C.') + \ ne(' tells whether the output automaton is complete: rejecting ' 'sink states are always omitted (add 1 state when C=0 if you ' 'want the size of the complete automaton).') row3 = [MultiColumn(14)] row4 = [ '', '', '', '', 'DRA', MultiColumn(4, align='|c', data='DTGBA'), MultiColumn(3, align='|c', data='DBA'), MultiColumn(2, align='|c', data=ne('DBA\\footnotesize minimizer')) ] row5 = [ 'formula', 'm', 'type', 'C.', 'st.', 'st.', 'tr.', 'acc.', 'time', 'st.', 'tr.', 'time', 'st.', 'time' ] # Datas that depends on the configuration file len_l = len(config.l) for i in range(0, len_l): row3.append(MultiColumn(7, align='|c', data=config.l[i].name)) row4.append(MultiColumn(3, align='|c', data='minDBA')) row4.append(MultiColumn(4, align='|c', data='minDTGBA')) row5.extend(['st.', 'tr.', 'time', 'st.', 'tr.', 'acc.', 'time']) # Add the first 5 lines of the document. n = 14 + len_l * 7 table.add_row((MultiColumn(n, align='c', data=data_row1), )) table.add_row((MultiColumn(n, align='c', data=data_row2), )) table.add_row((MultiColumn(n, align='l', data=''), )) # add empty line table.add_row(tuple(row3)) table.add_row(tuple(row4)) table.add_row(tuple(row5)) table.add_hline()
def POP_generator(df): data_used = df.values.tolist() for i in range(0, len(data_used)): data_used[i][1] = str(("%.2f" % data_used[i][1])).replace(".", ",") data_used[i][2] = str(("%.2f" % data_used[i][2])).replace(".", ",") data_used[i][3] = str(("%.2f" % data_used[i][3])).replace(".", ",") with doc.create(Section('Vymezení požárně nebezpečného prostoru')): with doc.create(Subsection('Procenta požárně otevřených ploch')): doc.append(NoEscape(r'Dále je určeno, zda je možné jednotlivé otvory ve fasádě posuzovat samostatně, a to výpočtem procenta požárně otevřených ploch z celkové plochy každé fasády. Způsob odečtení plochy fasády a plochy otevřených ploch je patrný z obrázku \ref{SchemaPOP}.')) with doc.create(Figure(position='htb!')) as POP: POP.add_image('images/POP.jpg', width='200px') POP.add_caption('Odečtení požárně otevřených ploch') POP.append(Command('label', 'SchemaPOP')) doc.append(NoEscape(r'Procentuální výsledky jednotlivých fasád s požárně otevřenými plochami jsou patrné z tabulky \ref{POP}.')) with doc.create(LongTable("lcccc", pos=['htb'])) as data_table: doc.append(Command('caption', 'Odstupové vzdálenosti od objektu')) doc.append(Command('label', 'POP')) doc.append(Command('\ ')) data_table.append data_table.add_hline() data_table.add_row(["Popis", "Celková plocha", "Plocha POP", "Procento POP", "POP jednotlivě"]) data_table.add_row([" ", NoEscape('[m$^2$]'), NoEscape('[m$^2$]'), NoEscape('[\%]'), NoEscape(r'\textless 40 \%')]) data_table.add_hline() data_table.end_table_header() for i in range(0, len(data_used)): if i == 0: # \multicolumn{9}{l}{\textbf{1. nadzemní podlaží - POP společné}}\\ data_table.add_row((MultiColumn(5, align='l', data=utils.bold(df_popis_POP[i])),)) if i > 0 and df_popis_POP[i] != df_popis_POP[i-1]: data_table.add_hline() data_table.add_row((MultiColumn(5, align='l', data=utils.bold(df_popis_POP[i])),)) if (i) % 2 == 0: data_table.add_row(data_used[i], color="Hex") elif (i) % 2 != 0: data_table.add_row(data_used[i]) data_table.add_hline() doc.append(NoEscape(r'Ostatní v tabulce výše nezmíněné otvory na fasádách objektu jsou spočteny jako samostatné 100 \% otevřené požární plochy.'))
def write_summary(table2, config): """ Function that writes all the bench's summary. """ dba_summary = get_summary(config, 'DBA') dtgba_summary = get_summary(config, 'DTGBA') len_l = len(config.l) table2.add_hline() table2.add_row((MultiColumn(len_l + 2, align='|c|', data='DBA'), )) table2.add_hline() for i in range(0, len(dba_summary)): table2.add_row(tuple(dba_summary[i])) table2.add_hline() table2.add_row((MultiColumn(len_l + 2), )) table2.add_hline() table2.add_row((MultiColumn(len_l + 2, align='|c|', data='DTGBA'), )) table2.add_hline() for line in dtgba_summary: table2.add_row(tuple(line)) table2.add_hline()
def render_table(self, doc: Document, name_override: Optional[LatexObject] = None, toc_ref: Optional[str] = None, extra_rows: Optional[List[Tuple[str, Any]]] = None) -> None: """Write this table into a LaTeX document. Args: doc: The LaTeX document to be appended to. name_override: An optional replacement for this table's name field. toc_ref: A reference to be added to the table of contents. extra_rows: Any extra rows to be added to the table before the kwargs. """ with doc.create(Table(position='htp!')) as table: table.append(NoEscape(r'\refstepcounter{table}')) table.append(Label(Marker(name=str(self.fe_id), prefix="tbl"))) if toc_ref: table.append(NoEscape(r'\addcontentsline{toc}{subsection}{' + escape_latex(toc_ref) + '}')) with doc.create(Tabularx('|lX|', booktabs=True)) as tabular: package = Package('xcolor', options='table') if package not in tabular.packages: # Need to invoke a table color before invoking TextColor (bug?) tabular.packages.append(package) package = Package('seqsplit') if package not in tabular.packages: tabular.packages.append(package) tabular.add_row((name_override if name_override else bold(self.name), MultiColumn(size=1, align='r|', data=TextColor('blue', self.fe_id)))) tabular.add_hline() type_str = f"{self.type}" match = re.fullmatch(r'^<.* \'(?P<typ>.*)\'>$', type_str) type_str = match.group("typ") if match else type_str tabular.add_row(("Type: ", escape_latex(type_str))) if self.path: if isinstance(self.path, LatexObject): tabular.add_row(("", self.path)) else: tabular.add_row(("", escape_latex(self.path))) for k, v in self.fields.items(): tabular.add_hline() tabular.add_row((f"{k.capitalize()}: ", v)) if self.args: tabular.add_hline() tabular.add_row(("Args: ", self.args)) if extra_rows: for (key, val) in extra_rows: tabular.add_hline() tabular.add_row(key, val) if self.kwargs: tabular.add_hline() for idx, (kwarg, val) in enumerate(self.kwargs.items()): tabular.add_row((italic(kwarg), val), color='white' if idx % 2 else 'black!5')
def make_table_of_symbols(symbols: List[str], units: List[str], descriptions: List[str]): table_symbols_content = LongTable("l l l") table_symbols_content.add_hline() table_symbols_content.add_row(["Symbol", "Unit", "Description"]) table_symbols_content.add_hline() table_symbols_content.end_table_header() table_symbols_content.add_hline() table_symbols_content.add_row( (MultiColumn(3, align='r', data='Continued on Next Page'), )) table_symbols_content.add_hline() table_symbols_content.end_table_footer() table_symbols_content.add_hline() table_symbols_content.add_row((MultiColumn(3, align='r', data='***End'), )) table_symbols_content.add_hline() table_symbols_content.end_table_last_footer() for i in range(len(symbols)): try: symbol = py2tex(symbols[i], print_latex=False, print_formula=False).replace('$', '') except: symbol = symbols[i] try: unit = py2tex(units[i], print_latex=False, print_formula=False, simplify_fractions=True).replace('$', '') except: unit = units[i] table_symbols_content.add_row([ NoEscape(f'${symbol}$'), NoEscape(f'${unit}$'), NoEscape(descriptions[i]) ]) table_symbols_content.add_hline() return table_symbols_content
def build_statistics_table(self): if not self.statistics: return self.doc.append(Command('centering')) with self.doc.create(Section('DP Statistics')): table1 = Tabular('|c|c|') table1.add_hline() table1.add_row((MultiColumn(2, align='|c|', data='Summary'), )) table1.add_hline() for stat in self.statistics: table1.add_row((stat['statistic'], stat['result']['value'])) table1.add_hline() self.doc.append(table1)
def generate_document_description(schema: PLDSchema, locale: LocaleDictionary, document: Document) -> Document: document.append(NewPage()) total_man_days, man_days_distribution = generate_stats(schema) with document.create(MiniPage()) as minipage: minipage: MiniPage with minipage.create( Section(title=locale.document_description)) as section: section: Section with section.create(Tabularx(table_spec="|l|X|", row_height=1.4)) as tabularx: tabularx: Tabularx tabularx.add_row([ MultiColumn(1, data=locale.title, color="gray"), schema.title ]) tabularx.add_row([ MultiColumn(1, data=locale.description, color="gray"), schema.description ]) tabularx.add_row([ MultiColumn(1, data=locale.authors, color="gray"), ", ".join(schema.authors) ]) tabularx.add_row([ MultiColumn(1, data=locale.updated_date, color="gray"), schema.versions[-1].date ]) tabularx.add_row([ MultiColumn(1, data=locale.model_version, color="gray"), schema.versions[-1].version ]) tabularx.add_row( [MultiColumn(2, color="gray", data=bold(locale.stats))]) tabularx.add_row([ MultiColumn(1, data=locale.man_days_distribution, color="gray"), NoEscape(f"{NewLine().dumps()} ".join([ f"{author}: {score:g}" for author, score in man_days_distribution.items() ])) ]) tabularx.add_row([ MultiColumn(1, data=locale.total_man_days, color="gray"), f"{total_man_days:g}" ]) return document
def quadro_empresa(self, ppra): with self.create(Tabu("|X[4,l]|X[6,l]|")) as tabela_empresa: tabela_empresa.add_hline() tabela_empresa.add_row((MultiColumn( 2, align='|c|', data=bold('COMPROVANTE DE INSCRIÇÃO E SITUAÇÃO CADASTRAL')), )) tabela_empresa.add_hline() tabela_empresa.add_row((bold('CNPJ'), ppra['CNPJFilial'])) tabela_empresa.add_hline() tabela_empresa.add_row((bold('Data de abertura'), ppra['data'])) tabela_empresa.add_hline() tabela_empresa.add_row( (bold('Nome empresarial'), ppra['nomeEmpresa'].capitalize())) tabela_empresa.add_hline() tabela_empresa.add_row( (bold('Título do estabelecimento (Nome Fantasia)'), ppra['nomeFilial'])) tabela_empresa.add_hline() tabela_empresa.add_row((bold( 'Código e descrição da atividade econômica principal CNAE'), ppra['CNAE'])) tabela_empresa.add_hline() tabela_empresa.add_row( (bold('Grau de risco pela NR'), ppra['grauRisco'])) tabela_empresa.add_hline() tabela_empresa.add_row( (bold('Número de funcionários:'), ppra['numFunc'])) tabela_empresa.add_hline() tabela_empresa.add_row( (bold('Horário de Trabalho'), ppra['horaTrabalho'])) tabela_empresa.add_hline() tabela_empresa.add_row((bold('Atividade'), ppra['atividade'])) tabela_empresa.add_hline() tabela_empresa.add_row((bold('Logradouro'), ppra['logradouro'])) tabela_empresa.add_hline() tabela_empresa.add_row((bold('Número'), ppra['numero'])) tabela_empresa.add_hline() tabela_empresa.add_row((bold('Complemento'), ppra['complemento'])) tabela_empresa.add_hline() tabela_empresa.add_row((bold('Bairro'), ppra['bairro'])) tabela_empresa.add_hline() tabela_empresa.add_row((bold('CEP'), ppra['cep'])) tabela_empresa.add_hline() tabela_empresa.add_row((bold('Município'), ppra['cidade'])) tabela_empresa.add_hline() tabela_empresa.add_row((bold('UF'), ppra['uf'])) tabela_empresa.add_hline() tabela_empresa.add_row((bold('Telefone'), ppra['telefone'])) tabela_empresa.add_hline()
def cria_primeira_secao(self, cabecalho): colunas_section_1 = Tabularx('c c c') colunas_section_1.add_row([MultiColumn(3, align='c')]) info_aluno = MiniPage(width=NoEscape(r'0.25\textwidth'), pos='b', align='l') graf_media = StandAloneGraphic(filename=self.path_graf_medias, image_options='width = 180 px') box_medias_aluno = MiniPage(width=NoEscape(r'0.23\textwidth'), pos='b', align='l') info_aluno.append(f'Nome: {self.resumo[1]} {self.resumo[2]}') info_aluno.append(NewLine()) info_aluno.append(f'Número: {self.resumo[5]}') info_aluno.append(NewLine()) info_aluno.append(f'Série: {self.resumo[4]}º ano') info_aluno.append(NewLine()) info_aluno.append(f'Turma: {self.resumo[3]}') info_aluno.append(NewLine()) info_aluno.append(NewLine()) if self.resumo[9] >= 45: info_aluno.append(LargeText(f'Aprovado')) else: info_aluno.append(LargeText(f'Reprovado')) for i in range(3): info_aluno.append(NewLine()) media_final = LargeText(f'Média final: {self.resumo[9]}') info_aluno_medias = Tabular('c | c | c', pos='b') info_aluno_medias.add_row(cabecalho, mapper=[bold]) info_aluno_medias.add_hline() info_aluno_medias.add_empty_row() info_aluno_medias.add_row( [self.resumo[6], self.resumo[7], self.resumo[8]]) box_medias_aluno.append(media_final) for i in range(3): box_medias_aluno.append(NewLine()) box_medias_aluno.append(info_aluno_medias) for i in range(3): box_medias_aluno.append(NewLine()) colunas_section_1.add_row([info_aluno, graf_media, box_medias_aluno]) return colunas_section_1
def quadro_funcionarios(self, quadro_funcionarios, total_masc, total_fem, total_fun): with self.create( LongTabu("|X[3,c]|X[c]|X[c]|")) as tabela_funcionarios: tabela_funcionarios.add_hline() tabela_funcionarios.add_row( (MultiRow(2, data=bold('Função')), MultiColumn(2, align='c|', data=bold('Número de Funcionários')))) tabela_funcionarios.add_hline(2, 3) tabela_funcionarios.add_row( ('', bold('Masculino'), bold('Feminino'))) tabela_funcionarios.end_table_header() tabela_funcionarios.add_row( (MultiColumn(3, align='|r|', data='Continua na próxima página'), )) tabela_funcionarios.add_hline() tabela_funcionarios.end_table_footer() tabela_funcionarios.add_hline() tabela_funcionarios.add_row( (MultiRow(2, data=bold('Total Funcionários')), bold(total_masc), bold(total_fem))) tabela_funcionarios.add_hline(2, 3) tabela_funcionarios.add_row( ('', MultiColumn(2, align='c|', data=bold(total_fun)))) tabela_funcionarios.add_hline() tabela_funcionarios.end_table_last_footer() for funcao in quadro_funcionarios: row = [ funcao['funcao'], funcao['qtdMasculino'], funcao['qtdFeminino'] ] tabela_funcionarios.add_hline() tabela_funcionarios.add_row(row)
def _document_sys_config(self) -> None: """Add a system config summary to the traceability document. """ with self.doc.create(Section("System Config")): with self.doc.create(Itemize()) as itemize: itemize.add_item( escape_latex(f"FastEstimator {fe.__version__}")) itemize.add_item( escape_latex(f"Python {platform.python_version()}")) itemize.add_item(escape_latex(f"OS: {sys.platform}")) itemize.add_item( f"Number of GPUs: {torch.cuda.device_count()}") if fe.fe_deterministic_seed is not None: itemize.add_item( escape_latex( f"Deterministic Seed: {fe.fe_deterministic_seed}")) with self.doc.create(LongTable('|lr|', pos=['h!'], booktabs=True)) as tabular: tabular.add_row((bold("Module"), bold("Version"))) tabular.add_hline() tabular.end_table_header() tabular.add_hline() tabular.add_row((MultiColumn(2, align='r', data='Continued on Next Page'), )) tabular.add_hline() tabular.end_table_footer() tabular.end_table_last_footer() color = True for name, module in humansorted(sys.modules.items(), key=lambda x: x[0]): if "." in name: continue # Skip sub-packages if name.startswith("_"): continue # Skip private packages if isinstance(module, Base): continue # Skip fake packages we mocked if hasattr(module, '__version__'): tabular.add_row( (escape_latex(name), escape_latex(str(module.__version__))), color='black!5' if color else 'white') color = not color elif hasattr(module, 'VERSION'): tabular.add_row((escape_latex(name), escape_latex(str(module.VERSION))), color='black!5' if color else 'white') color = not color
def test_table(): # Tabular t = Tabular(table_spec='|c|c|', data=None, pos=None, width=2) t.add_hline(start=None, end=None) t.add_row((1, 2), escape=False, strict=True, mapper=[bold]) t.add_row(1, 2, escape=False, strict=True, mapper=[bold]) # MultiColumn/MultiRow. t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'), ), strict=True) # One multiRow-cell in that table would not be proper LaTeX, # so strict is set to False t.add_row((MultiRow(size=2, width='*', data='MultiRow'), ), strict=False) repr(t) # TabularX tabularx = Tabularx(table_spec='X X X', width_argument=NoEscape(r"\textwidth")) tabularx.add_row(["test1", "test2", "test3"]) # Long Table longtable = LongTable(table_spec='c c c') longtable.add_row(["test", "test2", "test3"]) longtable.end_table_header() # Colored Tabu coloredtable = Tabu(table_spec='X[c] X[c]') coloredtable.add_row(["test", "test2"], color="gray", mapper=bold) # Colored Tabu with 'spread' coloredtable = Tabu(table_spec='X[c] X[c]', spread="1in") coloredtable.add_row(["test", "test2"], color="gray", mapper=bold) # Colored Tabu with 'to' coloredtable = Tabu(table_spec='X[c] X[c]', to="5in") coloredtable.add_row(["test", "test2"], color="gray", mapper=bold) # Colored Tabularx coloredtable = Tabularx(table_spec='X[c] X[c]') coloredtable.add_row(["test", "test2"], color="gray", mapper=bold) # Column column = ColumnType("R", "X", r"\raggedleft", parameters=2) repr(column)
def quadro_responsavel(self, profissionais, data_emissao): with self.create(LongTabu("|X[l]|X[l]|")) as tabela_resp: tabela_resp.add_hline() tabela_resp.add_row( (MultiColumn(2, align='|c|', data=bold('Responsável pela elaboração')), )) tabela_resp.add_hline() tabela_resp.add_row((bold('Nome'), profissionais[0]['nome'])) tabela_resp.add_hline() tabela_resp.add_row((bold('Função'), profissionais[0]['titulo'])) tabela_resp.add_hline() tabela_resp.add_row((bold('Data da elaboração'), data_emissao)) tabela_resp.add_hline() tabela_resp.add_row((bold('Revisão Programada'), data_emissao)) tabela_resp.add_hline()
def test_table(): # Tabular t = Tabular(table_spec='|c|c|', data=None, pos=None) t.add_hline(start=None, end=None) t.add_row(cells=(1, 2), escape=False, strict=True) # MultiColumn/MultiRow. t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'), ), strict=True) # One multiRow-cell in that table would not be proper LaTeX, # so strict is set to False t.add_row((MultiRow(size=2, width='*', data='MultiRow'), ), strict=False) repr(t)