Esempio n. 1
0
    def _generiraj_nalogo_razvrsti_v_preglednico(self, naloga, latex_dokument):

        primeri_naloge = naloga.primeri()

        imena_skupin = primeri_naloge[0]['skupine']
        nastavitve_tabele = ['p{4cm}' for skupina in imena_skupin]

        center = Center()
        with center.create(Tabular('|{}|'.format(
                '|'.join(nastavitve_tabele)))) as tabela:
            tabela.add_hline()
            tabela.add_row(tuple(imena_skupin))
            tabela.add_hline()
            tabela.add_row(
                tuple([Command('vspace', arguments=['4cm'])] *
                      len(imena_skupin)))
            tabela.add_hline()

        primeri = []
        for primer in primeri_naloge:
            primeri.append(Command('podnaloga'))
            primeri.extend([', '.join(primer['besede'])])
            primeri.append(Command('vspace', ['0.5cm']))
            primeri.append(center)
            primeri.append(Command('vspace', ['0.5cm']))

        return primeri
Esempio n. 2
0
    def fromTable(self, s: Table):
        c = Center()
        # c.append(NoEscape(r"\newlength\q"))
        c.append(
            NoEscape(
                rf"\setlength\tablewidth{{\dimexpr (\textwidth -{2*s.col_num}\tabcolsep)}}"
            ))
        c.append(NoEscape(r"\arrayrulecolor{tablelinegray!75}"))
        c.append(NoEscape(r"\rowcolors{2}{tablerowgray}{white}"))

        ratios = s.cacu_col_ratio()
        # format = "|".join([rf"p{{{r}\textwidth}}<{{\centering}}" for r in ratios])
        format = "|".join(
            [rf"p{{{r}\tablewidth}}<{{\centering}}" for r in ratios])
        format = f"|{format}|"

        t = Tabular(format)
        t.add_hline()
        for i, row in enumerate(s.tables):
            if i == 0:
                t.append(NoEscape(r"\rowcolor{tabletopgray}"))

            row = [self.fromTokenLine(c) for c in row]
            if i == 0:
                row = [bold(c) for c in row]

            t.add_row(row)
            t.add_hline()

        c.append(t)
        return c
Esempio n. 3
0
def test_position():

    repr(HorizontalSpace(size='20pt', star=False))

    repr(VerticalSpace(size="20pt", star=True))

    # Test alignment environments
    center = Center()
    center.append("append")
    repr(center)

    right = FlushRight()
    right.append("append")
    repr(right)

    left = FlushLeft()
    left.append("append")
    repr(left)

    minipage = MiniPage(width=r"\textwidth",
                        height="10pt",
                        pos='t',
                        align='r',
                        content_pos='t',
                        fontsize="Large")
    minipage.append("append")
    repr(minipage)

    textblock = TextBlock(width="200",
                          horizontal_pos="200",
                          vertical_pos="200",
                          indent=True)
    textblock.append("append")
    textblock.dumps()
    repr(textblock)
Esempio n. 4
0
def de_image(s: lines.Image):
    img_path = ImageTool.verify(s.link, config.cacheimg_dir)

    if img_path is None:
        c = Center()
        c.append(NoEscape('Link or path not found: {}'.format(s.link)))
        return c

    if config.give_rele_path:
        img_path = os.path.relpath(img_path, config.output_dir)
    img_path = norm_path(img_path)

    c = Center()
    if isinstance(s.parent, env.Quote):
        c.append(
            NoEscape(
                r"\includegraphics[width=0.8\textwidth]{{{img_path}}}".format(
                    img_path=img_path)))
    else:
        fig = Figure(position=config.fig_position)
        fig.add_image(img_path, placement='')
        if len(s.desc.strip()) > 0:
            fig.add_caption(s.desc)
        c.append(fig)
    return c
Esempio n. 5
0
def test_position():

    repr(HorizontalSpace(size='20pt', star=False))

    repr(VerticalSpace(size="20pt", star=True))

    # Test alignment environments
    center = Center()
    center.append("append")
    repr(center)

    right = FlushRight()
    right.append("append")
    repr(right)

    left = FlushLeft()
    left.append("append")
    repr(left)

    minipage = MiniPage(width=r"\textwidth", height="10pt", pos='t',
                        align='r', content_pos='t', fontsize="Large")
    minipage.append("append")
    repr(minipage)

    textblock = TextBlock(width="200", horizontal_pos="200",
                          vertical_pos="200", indent=True)
    textblock.append("append")
    textblock.dumps()
    repr(textblock)
Esempio n. 6
0
def de_table(s: env.Table):
    col, row = s.shape

    c = Center()
    # c.append(NoEscape(r"\newlength\q"))
    c.append(
        NoEscape(
            r"\setlength\tablewidth{{\dimexpr (\textwidth -{}\tabcolsep)}}".
            format(2 * col)))
    c.append(NoEscape(r"\arrayrulecolor{tablelinegray!75}"))
    c.append(NoEscape(r"\rowcolors{2}{tablerowgray}{white}"))

    ratios = s.cacu_col_ratio()
    format = "|".join(
        [r"p{{{r}\tablewidth}}<{{\centering}}".format(r=r) for r in ratios])
    format = "|{format}|".format(format=format)

    t = Tabular(format)
    t.add_hline()
    for i, row in enumerate(s.iter_rows()):
        if i == 0:
            t.append(NoEscape(r"\rowcolor{tabletopgray}"))

        row = [de_line(c) for c in row]
        if i == 0:
            row = [bold(c) for c in row]

        t.add_row(row)
        t.add_hline()

    c.append(t)
    return c
Esempio n. 7
0
    def _generiraj_nalogo_izloci_vsiljivca_glas(self, naloga, latex_dokument):

        center = Center()
        with center.create(Tabular('ccccc')) as tabela:
            for primer in naloga.primeri():
                tabela.add_hline()
                tabela.add_row(primer['glasovi'])
            tabela.add_hline()

        return [center]
Esempio n. 8
0
    def PowerSupply_report(self):
        self.doc.append(NoEscape(r'\clearpage'))
        with self.doc.create(Section('Power Supply')):
            with self.doc.create(Subsection('Description')):
                self.doc.append(
                    'This test asserts the correct assembly of the Voltage regulation circuit.\n'
                )
                self.doc.append(
                    'Both power supply lines (5V and 3.3V) are tested using a simple voltage divider circuit present on the TestBoard. Given that the voltage divider provides a half of the real value to the RFFEuC ADC circuit, the following convertion is applied: \n'
                )
                with self.doc.create(Alignat(numbering=False,
                                             escape=False)) as agn:
                    agn.append(r'V_{PS} = ADC_{read} * 3.3 * 2 \\')

            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(bold('Power Supply'), bold('Measured [V]'),
                                    bold('Result'))
                        tbl.add_hline()
                        for key, val in self.test_results['powerSupply'].items(
                        ):
                            if isinstance(val, dict):
                                tbl.add_row(
                                    bold(key + 'V'),
                                    val['value'],
                                    ('Pass' if val['result'] else 'Fail'),
                                    color=('green'
                                           if val['result'] else 'red'))
                                tbl.add_hline()
Esempio n. 9
0
    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 _add_timing_report(self,
                           doc: Document,
                           title: str = 'Timing Report') -> None:
        """Add timing report sub-section to document.

        :param doc:
        :param title:
        :return:
        """
        with doc.create(Section(title)):
            doc.append(
                'Here is a summary of the execution time of various parts of the algorithm.'
            )
            with doc.create(Center()) as centered:
                with centered.create(Tabu("x[r] x[r] x[r]",
                                          to="4in")) as data_table:
                    header_row = [
                        "Section", "Time Taken (s)", "Time Taken Percentage"
                    ]
                    data_table.add_row(header_row, mapper=[bold])
                    data_table.add_hline()
                    labels, x, x_pct = self.experiment.get_timing_report()
                    # sort by time
                    for label, sec, pct in sorted(zip(labels, x, x_pct),
                                                  key=lambda v: v[1],
                                                  reverse=True):
                        row = ('%s %0.2f %0.2f%%' %
                               (label, sec, pct)).split(' ')
                        data_table.add_row(row)
Esempio n. 11
0
def generate_first_page(schema: PLDSchema, document: Document) -> Document:
    document.append(LargeText(Command("maketitle")))
    document.append(VerticalSpace("4cm"))
    with document.create(Center()) as center:
        center: Center
        center.append(LargeText(bold(schema.subtitle)))
    return document
Esempio n. 12
0
 def create_pdf(self) -> Document:
     questions = functools.reduce(
         lambda a, b: a + b, map(lambda x: x.get_questions(),
                                 self.questions), [])
     doc = Document()
     doc.preamble.append(Package('titling'))
     for i in range(1, self.count + 1):
         random.shuffle(questions)
         with doc.create(Center()):
             doc.append(HugeText(self.header))
         doc.append(bold('Nombre:'))
         doc.append(LineBreak())
         doc.append(bold('ID:'))
         doc.append(LineBreak())
         with doc.create(FlushRight()):
             doc.append(LargeText(f'Examen tipo {i}'))
         enum = Enumerate()
         for question in questions:
             question.append_to_document(doc, enum)
         doc.append(NewPage())
         doc.append('Guía de respuestas')
         doc.append(enum)
         doc.append(NewPage())
         doc.append(Command('setcounter', ['section', '0']))
     return doc
Esempio n. 13
0
    def LED_report(self):
        self.doc.append(NoEscape(r'\clearpage'))
        with self.doc.create(Section('LEDs')):
            with self.doc.create(Subsection('Description')):
                self.doc.append(
                    'This test asserts the correct assembly of the 4 LEDs on RFFEuC\'s edge.\n'
                )
                self.doc.append(
                    'A large LDR (20mm) is positioned in front of all LEDs and is connected to one of the Analogic-to-Digital converter ports - routed through the TestBoard Jn connector.\n'
                )
                self.doc.append(
                    'Each LED is activated separately and the LDR voltage is read and compared to a predefined mask.\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(bold('LED'), bold('LDR read [V]'),
                                    bold('Result'))
                        tbl.add_hline()
                        for key, val in self.test_results['led'].items():
                            if isinstance(val, dict):
                                tbl.add_row(
                                    bold(key), (val['value']),
                                    ('Pass' if val['result'] else 'Fail'),
                                    color=('green'
                                           if val['result'] else 'red'))
                                tbl.add_hline()
Esempio n. 14
0
def genenerate_tabus():
    geometry_options = {
        "landscape": True,
        "margin": "1.5in",
        "headheight": "20pt",
        "headsep": "10pt",
        "includeheadfoot": True
    }
    doc = Document(page_numbers=True, geometry_options=geometry_options)

    # Generate data table with 'tight' columns
    fmt = "X[r] X[r] X[r] X[r] X[r] X[r]"
    with doc.create(LongTabu(fmt, spread="0pt")) as data_table:
        header_row1 = ["Prov", "Num", "CurBal", "IntPay", "Total", "IntR"]
        data_table.add_row(header_row1, mapper=[bold])
        data_table.add_hline()
        data_table.add_empty_row()
        data_table.end_table_header()
        data_table.add_row(
            ["Prov", "Num", "CurBal", "IntPay", "Total", "IntR"])
        row = [
            "aduiashdDASDASDASDSADSAuiasuidhasuidhasi", "9", "$100", "%10",
            "$1000", "Test"
        ]
        for i in range(40):
            data_table.add_row(row)

    with doc.create(Center()) as centered:
        with centered.create(Tabu("X[r] X[r]", spread="1in")) as data_table:
            header_row1 = ["X", "Y"]
            data_table.add_row(header_row1, mapper=[bold])
            data_table.add_hline()
            row = [randint(0, 1000), randint(0, 1000)]
            for i in range(4):
                data_table.add_row(row)

    with doc.create(Center()) as centered:
        with centered.create(Tabu("X[r] X[r]", to="4in")) as data_table:
            header_row1 = ["X", "Y"]
            data_table.add_row(header_row1, mapper=[bold])
            data_table.add_hline()
            row = [randint(0, 1000), randint(0, 1000)]
            for i in range(4):
                data_table.add_row(row)

    doc.generate_pdf("tabus", clean_tex=False)
Esempio n. 15
0
    def Deploy_report(self):
        self.doc.append(NoEscape(r'\clearpage'))
        with self.doc.create(Section('Deploy')):
            with self.doc.create(Subsection('Description')):
                self.doc.append(
                    'Information about the deploy firmware programmed in the board.\n'
                )
                self.doc.append(
                    'If the board passed all the tests, it will be assigned a valid IP in the range 201-213, which corresponds to its slot in the rack.\n'
                )
                self.doc.append(
                    'If the board for some reason failed in any tests, it is treated as a spare part and programmed with a generic IP address (xxx.xxx.xxx.220), which should be ovewritten when replacing an old part.\n'
                )

            with self.doc.create(Subsection('Results')):
                with self.doc.create(Center()) as centered:
                    with centered.create(Tabular('|c|',
                                                 row_height=1.0)) as tbl:
                        tbl.add_hline()
                        tbl.add_row((bold('General Result'), ))
                        tbl.add_hline()
                        tbl.add_row(
                            (('Pass'
                              if self.test_results['result'] else 'Fail'), ),
                            color=('green'
                                   if self.test_results['result'] else 'red'))
                        tbl.add_hline()

                self.doc.append('Deploy firmware information:')
                with self.doc.create(Center()) as centered:
                    with centered.create(Tabular('|c|c|',
                                                 row_height=1.0)) as tbl:
                        tbl.add_hline()
                        tbl.add_row((bold('FW commit'),
                                     self.test_results['deployFWCommit']))
                        tbl.add_hline()
                        tbl.add_row(
                            (bold('IP'), self.test_results['deployIP']))
                        tbl.add_hline()
                        tbl.add_row(
                            (bold('Mask'), self.test_results['deployMask']))
                        tbl.add_hline()
                        tbl.add_row((bold('Gateway'),
                                     self.test_results['deployGateway']))
                        tbl.add_hline()
Esempio n. 16
0
    def fromImage(self, s: Image):
        # cur_dir = os.getcwd() #markdown的相对路径,一定是针对那个markdown的,
        # os.chdir(self.input_dir)
        link = s.link
        link = ImageTool.verify(link, self.image_dir, self.input_dir)
        # os.chdir(cur_dir)

        if config.give_rele_path:
            link = os.path.relpath(link, self.output_dir)

        link = link.replace("\\", "/")

        c = Center()
        c.append(
            NoEscape(rf"\vspace{{\baselineskip}}"
                     rf"\includegraphics[width=0.8\textwidth]{{{link}}}"
                     rf"\vspace{{\baselineskip}}"))
        return c
Esempio n. 17
0
    def FERAM_report(self):
        self.doc.append(NoEscape(r'\clearpage'))
        with self.doc.create(Section('FeRAM')):
            with self.doc.create(Subsection('Description')):
                self.doc.append(
                    'This test asserts the correct assembly of the FeRAM chip (IC1 - FM24CL16B-G) and its communication lines (I2C).\n'
                )
                self.doc.append(
                    'A random pattern, 256 bytes long, is generated by reading the two least significant bits of ADC0 and shifting them left. This pattern is then written in each page of the FeRAM and then read back to be compared with the original data.\n'
                )

            with self.doc.create(Subsection('Results')):
                with self.doc.create(Center()) as centered:
                    with centered.create(Tabular('|c|',
                                                 row_height=0.9)) as tbl:
                        tbl.add_hline()
                        tbl.add_row((bold('Random Pattern'), ))
                        tbl.add_hline()
                        result_str = [
                            ''.join(self.test_results['feram']['pattern'][i:i +
                                                                          16])
                            for i in range(
                                0, len(self.test_results['feram']['pattern']),
                                16)
                        ]
                        for item in result_str:
                            tbl.add_row(((item), ))
                        tbl.add_hline()

                with self.doc.create(Center()) as centered:
                    with centered.create(Tabular('|c|',
                                                 row_height=1.0)) as tbl:
                        tbl.add_hline()
                        tbl.add_row((bold('Result'), ))
                        tbl.add_hline()
                        tbl.add_row(
                            (('Pass' if self.test_results['feram']['result']
                              else 'Fail'), ),
                            color=('green'
                                   if self.test_results['feram']['result'] else
                                   'red'))
                        tbl.add_hline()
Esempio n. 18
0
File: pdfs.py Progetto: yssmcl/fly
def gerar_pdf_parecer(parecer):
    doc = pdfutils.init_document()

    pdfutils.pacotes(doc)

    # Configurações (preâmbulo)
    pdfutils.configuracoes_preambulo(doc)

    pdfutils.cabecalho(doc)

    frase_anexo = 'ANEXO XI DA RESOLUÇÃO Nº 236/2014-CEPE, DE 13 DE NOVEMBRO DE 2014.'
    pdfutils.rodape(doc, NoEscape(r'\texttt{' + frase_anexo + '}%'))
    doc.append(NoEscape(r'{\normalsize\texttt{' + frase_anexo + '}}%'))

    pdfutils.titulo(doc, 'RELATÓRIOS ESPECÍFICOS PARA ATIVIDADES DE EXTENSÃO',
                    'FORMULÁRIO ÚNICO DE PARECER DE ATIVIDADES DE EXTENSÃO')

    # Início do formulário
    with doc.create(Enumerate()) as enum:
        pdfutils.item(doc, enum, 'PARECER CONCLUSIVO DA COMISSÃO DE EXTENSÃO DE CENTRO')

    doc.append(bold('IDENTIFICAÇÃO:'))
    doc.append(NewLine())
    doc.append(NoEscape(r'Coordenador(a): {} \\'.format(escape_latex(parecer.projeto_extensao.coordenador.nome_completo))))
    doc.append(NoEscape(r'Colegiado: {} \\'.format(escape_latex(parecer.projeto_extensao.coordenador.colegiado))))
    doc.append(NoEscape(r'Centro: {} \\'.format(parecer.projeto_extensao.centro.nome)))
    doc.append(NoEscape(r'Campus: {} \\'.format(parecer.projeto_extensao.campus.nome)))
    doc.append(NoEscape(r'Título da atividade: {} \\ \\'.format(escape_latex(parecer.projeto_extensao.titulo))))
    # TODO: referente a portaria?
    # doc.append(NoEscape(r'Parecer referente a: \\ \\'))

    doc.append(bold(NoEscape(r'COMENTÁRIOS: \\')))
    pdfutils.tabela_alternativas(doc, EstadoProjeto, '|c|X|X|c|c|', id=parecer.estado_parecer.id)
    doc.append(NewLine())
    doc.append(NewLine())
    doc.append(NoEscape(r'Ata nº: {} \\'.format(escape_latex(parecer.numero_ata))))
    data = parecer.data.strftime('%d/%m/%Y')
    doc.append(NoEscape(r'Data: {} \\'.format(data)))

    texto = 'Carimbo e Assinatura do Coordenador(a) da Comissão de Extensão ou Representante Legal'
    largura = Command('widthof', texto).dumps()
    pdfutils.assinatura(doc, texto, largura, Center())

    os.system('mkdir -p ' + PDF_DIR)

    filepath = '{}/parecer_{}_projeto_{}'.format(PDF_DIR, str(parecer.id), str(parecer.projeto_extensao.id))
    doc.generate_pdf(filepath, clean_tex=False, compiler=pdfutils.COMPILER, compiler_args=pdfutils.COMPILER_ARGS)

    return filepath
Esempio n. 19
0
def generate_organigram(schema: PLDSchema, locale: LocaleDictionary,
                        document: Document) -> Document:
    document.append(NewPage())
    with document.create(Figure()) as figure:
        figure: Figure
        with figure.create(Section(title=locale.organigram)) as section:
            section: Section
            section.append(Command("centering"))
            with section.create(Center()) as center:
                center: Center
                with center.create(TikZ()) as forest:
                    forest: TikZ

                    node_kwargs = {'align': 'center', 'minimum size': '20pt'}

                    # noinspection PyTypeChecker
                    top_box = TikZNode(text=schema.title,
                                       handle=f"project-box",
                                       options=TikZOptions(
                                           'draw', 'rounded corners',
                                           **node_kwargs))
                    forest.append(top_box)
                    last_box_handle = top_box.handle

                    for n_deliverable, deliverable in enumerate(
                            schema.deliverables, start=1):
                        # noinspection PyTypeChecker
                        box = TikZNode(
                            text=f"{n_deliverable}. {deliverable.name}",
                            handle=f"deliverable-box-{n_deliverable}",
                            options=TikZOptions(
                                'draw', 'rounded corners',
                                f'below = of {last_box_handle}'
                                if top_box.handle == last_box_handle else
                                f'right = of {last_box_handle}',
                                **node_kwargs))

                        last_box_handle = box.handle
                        # noinspection PyTypeChecker
                        path = TikZDraw(
                            TikZPathList(top_box.get_anchor_point("south"),
                                         "--", box.get_anchor_point("north")))
                        forest.append(box)
                        forest.append(path)
    document.append(VerticalSpace("2cm"))
    return document
Esempio n. 20
0
def display(ap, doc):
    properties, effects = analyze(ap)
    with doc.create(Subsection(ap['name'])):
        doc.append('Definition:')
        with doc.create(Itemize(options='noitemsep')) as itemize:
            if 'url' in ap:
                itemize.add_item('url: {}'.format(ap['url']))
            itemize.add_item('floor: {}'.format(ap['floor']))
            itemize.add_item('starting price: {:.2f} Mkr'.format(
                ap['startPrice'] / 1e6))
            if 'booliEstimate' in ap:
                itemize.add_item('Booli estimated price: {:.2f} Mkr'.format(
                    ap['booliEstimate'] / 1e6))
            itemize.add_item('fee: {:.0f} kr/month'.format(ap['fee']))
            ma = Math(inline=True, escape=False)
            ma.append('\\text{{area: }} {:.0f}\\,\\mathrm{{m}}^2'.format(
                ap['area']))
            itemize.add_item(ma)
            itemize.add_item(
                'commute time: {:.0f} min of which {:.0f} min is walking. Frequency every {:.0f} min.'
                .format(ap['commuteTime'], ap['commuteWalkTime'],
                        ap['commutePeriod']))

        doc.append('Results:')
        with doc.create(Itemize(options='noitemsep')) as itemize:
            itemize.add_item('interest: {:.1%}'.format(properties['interest']))
            itemize.add_item('amortization: {:.1%}'.format(
                properties['amortization']))
            itemize.add_item(
                'monthly cost: {a:.0f} kr/month (incl. amortization)'.format(
                    a=properties['monthlyCost']))
        # print('m2 price: {p:.0f}% of local market value'.format(p=100*ap['price']/(ap['area']*m2Price[ap['location']])))
        # print('Effective commute time: ',effectiveCommuteTime,' min')
        # print('Monthly apartment bill:',monthlyPrice)
        doc.append('Value breakdown:\n')
        with doc.create(Center()) as centered:
            with centered.create(Tabular('l|r')) as table:
                tot = 0
                for e in effects:
                    table.add_row((e, '{p}{v:.0f} kr/month'.format(
                        k=e, v=effects[e], p='+' if effects[e] > 0 else '')))
                    tot += effects[e]
                table.add_hline()
                table.add_row(('TOTAL', '{t:.0f} kr/month'.format(t=tot)))
    def _add_comparison(self,
                        doc: Document,
                        title: str = 'Comparison to Other Models') -> None:
        """Add comparison sub-section to document.

        :param doc:
        :param title:
        :return:
        """
        with doc.create(Subsection(title)):
            doc.append(
                'This table contains the RMSE of the best model and others.')
            doc.append("\n")
            doc.append(VerticalSpace("1pt"))
            doc.append(LineBreak())
            with doc.create(Center()) as centered:
                with centered.create(Tabu("|c|c|c|c|c|",
                                          to="4in")) as data_table:
                    header_row = [
                        "Best Model", "Linear Regression",
                        "Support Vector Regression", "GP (RBF kernel)",
                        "k-NN Regression"
                    ]
                    data_table.add_row(header_row, mapper=[bold])
                    data_table.add_hline()

                    rmse_best_model = compute_gpy_model_rmse(
                        self.best_model, self.x_test, self.y_test)
                    rmse_lr = rmse_lin_reg(self.x_train, self.y_train,
                                           self.x_test, self.y_test)
                    rmse_svm = rmse_svr(self.x_train, self.y_train,
                                        self.x_test, self.y_test)
                    se_rmse = rmse_rbf(self.x_train, self.y_train, self.x_test,
                                       self.y_test)
                    knn_rmse = rmse_knn(self.x_train, self.y_train,
                                        self.x_test, self.y_test)

                    row = ('%0.3f %0.3f %0.3f %0.3f %0.3f' %
                           (rmse_best_model, rmse_lr, rmse_svm, se_rmse,
                            knn_rmse)).split(' ')
                    data_table.add_row(row)
    def _add_model_summary(self,
                           doc: Document,
                           title: str = 'Best Model Summary') -> None:
        """Add model summary sub-section to document.

        :param doc:
        :param title:
        :return:
        """
        with doc.create(Subsection(title)):
            doc.append('This table contains various scores of the best model.')
            doc.append("\n")
            doc.append(VerticalSpace("1pt"))
            doc.append(LineBreak())
            with doc.create(Center()) as centered:
                with centered.create(Tabu("|c|c|c|c|c|c|",
                                          to="4in")) as data_table:
                    header_row = [
                        "NLL", "NLL (normalized)", "Mean NLPD", "BIC", "AIC",
                        "PL2"
                    ]
                    data_table.add_row(header_row, mapper=[bold])
                    data_table.add_hline()

                    nll = -self.best_model.log_likelihood()
                    nll_norm = log_likelihood_normalized(self.best_model)
                    mean_nlpd = np.mean(
                        -self.best_model.log_predictive_density(
                            self.x_test, self.y_test))
                    aic = AIC(self.best_model)
                    bic = BIC(self.best_model)
                    pl2_score = pl2(self.best_model)

                    row = ('%0.3f %0.3f %0.3f %0.3f %0.3f %0.3f' %
                           (nll, nll_norm, mean_nlpd, bic, aic,
                            pl2_score)).split(' ')
                    data_table.add_row(row)
Esempio n. 23
0
def create_tables(pwn_data, pdf, start_entry, stop_entry, counter):
    """
	Creates tables for use in the PDF document. It takes the output of the check_pwn
	function as a variable pwn_data. PDF equals the LaTeX document object. The start_entry,
	stop_entry and counter are used to limit the size of the table. Otherwise the result
	will be written to one big table. Which turns out ugly in the document.

	The counter value in particular is being used to loop through the classess of data that
	were leaked in the breach. The looping is done to construct a bullet list of classes that
	were breached.

	This function doesn't return anything. It only alters the state of the PDF document object.
	"""
    with pdf.create(Center()) as centered:
        with centered.create(Table(position='h')):
            with pdf.create(Tabular('|l|c|')) as table:
                table.add_hline()
                for entry in pwn_data[start_entry:stop_entry]:
                    table.add_row(bold("Title"), pwn_data[counter]["Title"])
                    table.add_hline()
                    table.add_row(bold("Domain"), pwn_data[counter]["Domain"])
                    table.add_hline()
                    table.add_row(bold("Date of breach"),
                                  pwn_data[counter]["BreachDate"])
                    table.add_hline()
                    first_class = True
                    for dataclasses in pwn_data[counter]["DataClasses"]:
                        if first_class:
                            table.add_row(bold("Affected classes"),
                                          dataclasses)
                            first_class = False
                        else:
                            table.add_row("", dataclasses)
                    table.add_hline()
                    counter = counter + 1
                    table.add_hline()
Esempio n. 24
0
    def to_tex(self):

        tab = self._create_tabular()
        tab.add_hline()
        for i in range(self.sheet.nrows):
            line = []
            merge_set = set()
            for j in range(self.sheet.ncols):
                res, mindex = self.in_merge_cell(i, j)

                if res == -1:
                    line.append(self.cell(i, j))
                else:
                    merge_set.add(mindex)
                    cres, cnum = self.ismulticol(mindex)
                    rres, rnum = self.ismultirow(mindex)
                    if res == 0:
                        if cres:
                            if rres:
                                line.append(
                                    MultiColumn(
                                        cnum,
                                        align=self._cacu_multicol_align(j),
                                        data=MultiRow(rnum,
                                                      data=self.cell(i, j))))
                            else:
                                line.append(
                                    MultiColumn(
                                        cnum,
                                        align=self._cacu_multicol_align(j),
                                        data=self.cell(i, j)))
                        else:
                            line.append(MultiRow(rnum, data=self.cell(i, j)))
                    elif res == 1:  # 不同行同列
                        if cres and rres:
                            line.append(
                                MultiColumn(cnum,
                                            align=self._cacu_multicol_align(j),
                                            data=""))
                        else:
                            line.append("")
                    elif res == 2:  # 不同列同行
                        pass

            tab.add_row(line)

            all_range = [[0, self.sheet.ncols - 1]]
            for mi in merge_set:
                merge_range = self.merge_col[mi]

                if merge_range[1] - merge_range[0] > 0 and merge_range[
                        1] - i > 0:
                    all_range = self._extract_range(all_range,
                                                    merge_range[2:4])

            if all_range[0][0] == 0 and all_range[0][1] == self.sheet.ncols - 1:
                tab.add_hline()
            else:
                for r in all_range:
                    tab.add_hline(r[0] + 1, r[1] + 1)

        table = TexTable(position=self.params["position"])
        table.append(tab)

        res = table
        if self.params["center"]:
            c = Center()
            c.append(
                NoEscape(
                    r"% \newlength\tablewidth % if haven't define the length 'tablewidth'"
                ))
            c.append(
                NoEscape(
                    rf"\setlength\tablewidth{{\dimexpr (\textwidth -{2*self.sheet.ncols}\tabcolsep)}}"
                ))
            c.append(table)
            res = c

        return self._format_tex(res.dumps())
Esempio n. 25
0
 def add_title(self, title):
     with self.doc.create(Center()):
         self.doc.append(LargeText(bold(title)))
Esempio n. 26
0
def result_to_score(arr,
                    doc,
                    arr_name="",
                    n_class=5,
                    sort="asc",
                    sigma=2.5,
                    iqr_factor=1.5,
                    outliers_method="z-score"):
    '''
	convert continuous value to ranged score 
	:param str arr: input result array
	:param sec: pylatex document object
	:param str arr_name: array name
	:param str n_class: number of score classes
	:param str sort: "asc" or "dsc", order of the class count with ascending or descending order
	:param float sigma: standard deviation of the data in z-score outliers removal
	:param float iqr_factor: factor for iqr outliers removal
	:param str outliers_method: "z-score" or "iqr"
	:type sigma: float
	:return: arr score: array of converted score
	:rtype: None
	'''

    # remove outliners
    if outliers_method == "z-score":
        z = np.abs(stats.zscore(arr))
        arr_filtered = arr[(z < sigma)]
    elif outliers_method == "iqr":
        Q1 = np.quantile(arr, 0.25)
        Q3 = np.quantile(arr, 0.75)
        IQR = Q3 - Q1
        arr_filtered = arr[~((arr < (Q1 - iqr_factor * IQR)) |
                             (arr > (Q3 + iqr_factor * IQR)))]

    plt.clf()
    n, bins, patches = plt.hist(x=arr_filtered,
                                bins=n_class,
                                color='#607c8e',
                                alpha=0.7,
                                rwidth=0.9)
    plt.grid(axis='y', alpha=0.75)
    plt.xlabel('Value')
    plt.ylabel('Frequency')
    # plt.title(arr_name)
    maxfreq = n.max()
    # Set a clean upper y-axis limit.
    plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)

    # print(n, bins, patches)

    # convert result to score
    score = np.zeros_like(arr)
    if sort == "asc":
        for i in range(n_class):
            if i == 0:
                score[arr < bins[1]] = 1
            elif i == n_class - 1:
                score[arr > bins[n_class - 1]] = n_class
            else:
                score[~((arr < bins[i]) | (arr > bins[i + 1]))] = i + 1
    elif sort == "dsc":
        for i in reversed(range(n_class)):
            if i == 0:
                score[arr > bins[n_class - 1]] = 1
            elif i == n_class - 1:
                score[arr < bins[1]] = n_class
            else:
                score[~((arr < bins[::-1][i + 1]) |
                        (arr > bins[::-1][i]))] = i + 1

    with doc.create(Figure(position='htbp')) as plot:
        plot.add_plot(dpi=300)
        plot.add_caption(arr_name)

    with doc.create(Center()) as centered:
        table_format = "c|"
        for i in range(n_class):
            table_format += "c"
        with centered.create(Tabular(table_format)) as table:
            table.add_row(['severity score'] + [i + 1 for i in range(n_class)])
            table.add_hline(1, n_class + 1)
            table.add_row(['range'] + [
                "{:.2f}-{:.2f}".format(bins[i], bins[i + 1])
                for i in reversed(range(n_class))
            ])
            table.add_row(['count'] + [str(int(value)) for value in n])

    doc.append(basic.NewPage())

    return score
Esempio n. 27
0
def append_liquor_list(doc, df, own_page):
    # TODO no interaction with dataframe?
    kinds = df[df.Category.isin(['Spirit', 'Vermouth',
                                 'Liqueur'])][['Kind', 'Type']]
    if own_page:
        print "Appending list as new page"
        doc.append(NewPage())
    listing = SamepageEnvironment()
    block = Center()
    if not own_page:
        block.append(HRuleFill())
        block.append(Command('\\'))
    block.append(VerticalSpace('16pt'))
    block.append(TitleText("Included Ingredients"))
    block.append(Command('\\'))
    listing.append(block)
    listing.append(VerticalSpace('12pt'))

    cols = add_paracols_environment(listing, 2, '8pt', sloppy=False)
    with cols.create(FlushRight()):
        for item in kinds.Kind:
            cols.append(LargeText(item))
            cols.append(Command('\\'))
    cols.append(Command('switchcolumn'))
    with cols.create(FlushLeft()):
        for item in kinds.Type:
            cols.append(LargeText(italic(item)))
            cols.append(Command('\\'))

    doc.append(listing)
Esempio n. 28
0
File: pdfs.py Progetto: yssmcl/fly
def gerar_pdf_certificado(certificado):

    # Configurações da classe
    geometry_options = {'landscape': True,
                        'left': '2cm',
                        'right': '1cm'}
    doc = Document(geometry_options=geometry_options, lmodern=False, document_options=['a4paper', 'brazil'],
                   inputenc=None, fontenc=None, font_size='footnotesize')

    # Pacotes
    doc.packages.add(Package('microtype'))
    doc.packages.add(Package('indentfirst'))
    doc.packages.add(Package('graphicx'))
    doc.packages.add(Package('calc'))
    doc.packages.add(Package('fontspec'))
    options_background = ['scale=1',
                          'opacity=1',
                          'angle=0']
    doc.packages.add(Package('background', options=options_background))
    doc.packages.add(Package('csquotes'))

    # Configurações (preâmbulo)
    doc.preamble.append(Command('MakeOuterQuote', '\"'))  # coverte aspas automaticamente, sem precisar de `` e ''
    doc.preamble.append(Command('renewcommand', arguments=[Command('baselinestretch'), '1.5']))
    doc.preamble.append(Command('setlength', arguments=[Command('parindent'), NoEscape(r'.35\textwidth')]))
    doc.preamble.append(Command('setlength', arguments=[Command('parskip'), '0.2cm']))
    doc.preamble.append(Command('setlength', arguments=[Command('emergencystretch'), '5pt']))

    # Imagem de fundo
    doc.preamble.append(NoEscape(r'\backgroundsetup{ contents=\includegraphics{modelo-certificado-20.pdf} }'))

    # Diretório das imagens
    img_dir = '{}/base/static/img/'.format(BASE_DIR)  # necessário barra no final
    doc.preamble.append(UnsafeCommand('graphicspath', '{{{}}}'.format(img_dir)))

    # Início do documento
    doc.append(UnsafeCommand('setmainfont', 'Latin Modern Sans', ['SizeFeatures={Size=16}', 'Ligatures=TeX']))

    doc.append(Command('pagestyle', 'empty'))
    doc.append(Command('BgThispage'))

    doc.append(VerticalSpace(size='2cm', star=True))

    with doc.create(FlushRight()) as fr:
        fr.append(StandAloneGraphic('titulo-certificado.pdf', 'width=6.5cm'))
        fr.append(LineBreak())

    doc.append(VerticalSpace(size=NoEscape('-1cm'), star=True))
    doc.append(Command('Large'))

    # Usado para o nome dos meses ('%B')
    locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')

    inicio = certificado.relatorio.periodo_inicio.strftime('%d de %B de %Y').lower()
    fim = certificado.relatorio.periodo_inicio.strftime('%d de %B de %Y').lower()
    # TODO: tá faltando coisa
    texto_principal = r'''

    Certificamos que \textbf{{{nome}}} atuou como {funcao}, {sob_coordenacao}no período de {inicio} a {fim}, na cidade de Foz do Iguaçu -- Paraná, com a atividade de extensão: "\textbf{{{titulo}}}", com carga horária de {carga_horaria_total} horas.

    '''

    if certificado.funcao.nome == 'Coordenador(a)':
        sob_coordenacao = ''
    else:
        nome_coordenador = certificado.relatorio.projeto_extensao.coordenador.nome_completo
        sob_coordenacao = r'sob a coordenação de \textbf{{{}}}, '.format(escape_latex(nome_coordenador))

    texto_principal = texto_principal.format(nome=escape_latex(certificado.nome),
                                             funcao=certificado.funcao.nome.lower(),
                                             sob_coordenacao=sob_coordenacao,
                                             inicio=inicio,
                                             fim=fim,
                                             titulo=escape_latex(certificado.relatorio.projeto_extensao.titulo),
                                             carga_horaria_total=str(certificado.carga_horaria_total).split('.')[0])

    # texto_principal = NoEscape(r'''

    # Certificamos que \textbf{Adriana de Oliveira Gomes} participou como bolsista do Programa de Apoio a Inclusão Social em Atividades de Extensão -- Convênio No 750/2014 -- Fundação Araucária, Edital 05/2014-PROEX, sob a orientação do (a) professor (a) \textbf{Fernando Amâncio Aragão}, no período de outubro/2014 a setembro/2015, com a atividade de extensão: \textbf{''Atendimento fisioterapêutico para pacientes com sequelas neurológicas baseada em tarefas funcionais.''}, com carga horária de 960 (novecentas e sessenta) horas.

    # ''')

    doc.append(NoEscape(texto_principal))

    doc.append(VerticalSpace(size='1.5cm', star=True))

    doc.append(HorizontalSpace(size='7cm', star=True))
    dia = timezone.now().strftime('%d')
    mes = timezone.now().strftime('%B')
    ano = timezone.now().strftime('%Y')

    data = NoEscape(r'Foz do Iguaçu, {} de {} de {}'.format(dia, mes, ano))
    largura = Command('widthof', data).dumps()
    with doc.create(MiniPage(width=largura)) as mini:
        with mini.create(Center()) as center:
            center.append(data)
            center.append(NewLine())
            center.append(NewLine())
            center.append(NewLine())
            center.append('Coordenador do Projeto de Extensão')
            center.append(NewLine())
            center.append(NewLine())
            center.append(NewLine())
            center.append('Diretor de Centro')

    os.system('mkdir -p ' + PDF_DIR)

    filepath = '{}/certificado_{}'.format(PDF_DIR, str(certificado.id))
    doc.generate_pdf(filepath, clean_tex=False, compiler=pdfutils.COMPILER, compiler_args=pdfutils.COMPILER_ARGS)

    return filepath
    table.add_row(('','LETES','ARS','At Discount','2 to 12 months','-'))
    table.add_hline(2,6)
    table.add_row(('','LECER','ARS','-','-','-'))
    table.add_hline(2,6)
    table.add_row(('','LELINKS','USD','-','-','-'))
    table.add_hline()
    table.add_row((MultiRow(2,data='Provinces'),'-','ARS','Fixed','16 years','CER*'))
    table.add_hline(2,6)
    table.add_row(('','-','ARS','Variable','16 years','-'))
    table.add_hline()
doc.append(NoEscape(r'}'))
doc.append('\n\nOverview of Debt Securities in Argentina Market\n')
doc.append('*CER: refers to benchmark inflation stabilization coefficient\n**BADLAR: is an average rate regarding the nominal annual interest rate in peso-denominated time deposits of more than 1.0 million ARS from 30 to 35 days\n')

#Future Additions Table
with doc.create(Section('Sections to be Added', numbering=False)):
    with doc.create(Center()) as centered:
        with centered.create(Tabular('c|l',row_height=1.5)) as table:
            table.add_row('-', LargeText(bold('Section Name')))
            table.add_hline()
            table.add_row('1','Internal Debt Held by Local/Residents')
            table.add_row('2','External Currency Central Government Debt: Investors')
            table.add_row('3','Equities')
            table.add_row('4','Deposits and Reserves')


# doc.append(NewPage())
# doc.append(NoEscape(r'\addappheadtotoc'))


doc.generate_pdf('Argentina' ,clean=True)
Esempio n. 30
0
def generate_unique(name, df, version):
    geometry_options = {
        "head": "5pt",
        "margin": "1in",
        "bottom": "1in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)
    # Generating first page style

    doc.preamble.append(Command('title', 'MapeMaker {}'.format(version)))
    doc.preamble.append(
        Command('author', 'Name of the simulator : {}'.format(name)))
    doc.preamble.append(Command('date', NoEscape(r'\today')))
    doc.append(NoEscape(r'\maketitle'))

    summary_text = "Dataset used : {}\n" \
                   "Predicting {} from {}\n" \
                   "Date_Ranges simulated from {} to {}\n" \
                   "With Base Process {}\n" \
                   "Computed {} simulations".format(
                                                      df['parameters']["input_file"],
                                                      df['parameters']["x"],
                                                      df['parameters']["y"],
                                                      df['parameters']["date_range"][0][0].strftime("%Y-%m-%d"),
                                                      df['parameters']["date_range"][0][1].strftime("%Y-%m-%d"),
                                                      df['parameters']["base_process"],
                                                      len(df['mare']["scores_mare"]),
                                                    )

    if df['parameters']['output_file'] is not None:
        summary_text += "\nOutput stored in {}\n".format(
            df['parameters']['output_file'])

    if df["parameters"]["curvature_parameters"] is not None:
        curvature_parameters = df["parameters"]["curvature_parameters"]
        summary_text += "\n\n Smoothness correction  used with parameters :\n" \
                        "    * Solver used : {}\n" \
                        "    * MIP Gap used : {}\n"\
                        "    * TimeLimit used : {}\n".format(
                            curvature_parameters["solver"],
                            curvature_parameters["MIP"],
                            curvature_parameters["time_limit"]
                            )

    with doc.create(Section('Parameters of the simulations')):
        doc.append(MdFramed(arguments=summary_text))

    with doc.create(Section('Raw Results')):
        doc.append(
            'The simulations were computed between {} and {}, for {} samples\n'
            .format(df['parameters']["date_range"][0][0].strftime("%Y-%m-%d"),
                    df['parameters']["date_range"][0][1].strftime("%Y-%m-%d"),
                    df['n']))

        with doc.create(Subsection('Target Mape')):
            mares = df['mare']
            doc.append('The target mape was {}%, the observed mape for '
                       'the range of dates asked for is {}%\n'.format(
                           100 * mares["target_mare"],
                           100 * mares["observed_mare"]))
            with doc.create(Center()) as centered:
                with centered.create(Tabular('|c|c|c|')) as table:
                    table.add_hline()
                    table.add_row(("simulations", "simulated mape", "score"),
                                  mapper=bold,
                                  color="lightgray")
                    table.add_hline()
                    for i in range(len(mares["simulated_mares"])):
                        table.add_row(
                            "simulation n {}".format(i + 1), "{}%".format(
                                round(100 * mares["simulated_mares"][i], 1)),
                            mares["scores_mare"][i])
                    table.add_empty_row()
                    table.add_hline()

        with doc.create(Subsection('Target Smoothness')):
            curvature = df['curvature']
            if curvature["target_second_differences"] is None:
                doc.append("There was no target for curvature")
            else:
                doc.append(
                    'The target second difference was {}, the observed second difference for '
                    'the range of dates asked for is {}\n'.format(
                        round(curvature["target_second_differences"], 1),
                        curvature["observed_second_differences"]))
                with doc.create(Center()) as centered:
                    with centered.create(Tabular('|c|c|c|')) as table:
                        table.add_hline()
                        table.add_row(("simulations",
                                       "simulated second difference", "score"),
                                      mapper=bold,
                                      color="lightgray")
                        table.add_hline()
                        for i in range(
                                len(curvature["simulated_second_differences"])
                        ):
                            table.add_row(
                                "simulation n {}".format(i + 1), "{}".format(
                                    curvature["simulated_second_differences"]
                                    [i]), curvature["scores_curvature"][i])
                        table.add_empty_row()
                        table.add_hline()

        with doc.create(Subsection('Auto Correlation')):
            auto_corr = df['error_auto_correlation']
            doc.append(
                'The target for the autocorrelation of relative errors was {}\n'
                .format(auto_corr["target_auto_correlation"][0]))

            with doc.create(Center()) as centered:
                with centered.create(Tabular('|c|c|c|')) as table:
                    table.add_hline()
                    table.add_row(
                        ("simulations", "simulated auto-correlation", "score"),
                        mapper=bold,
                        color="lightgray")
                    table.add_hline()
                    for i in range(len(auto_corr['scores_auto_correlation'])):
                        table.add_row(
                            "simulation n {}".format(i + 1),
                            auto_corr['simulated_auto_correlation'][i],
                            auto_corr['scores_auto_correlation'][i])
                    table.add_empty_row()
                    table.add_hline()

    # with doc.create(Section('Table')):
    #     with doc.create(Table(position='htbp')) as table:
    #         table.add_caption('Test')
    #         table.append(Command('centering'))
    #         table.append(NoEscape(df.to_latex(escape=False)))

    return doc
Esempio n. 31
0
def seismicity(doc,
               year1,
               month1,
               t,
               lc,
               reg,
               pac,
               car,
               volc,
               imp,
               sub_list=[["1"], ["1"], ["0"], ["0"]]):
    """Add seismicity section to the document.

    :param doc: the document
    :type doc: :class:`pylatex.document.Document` instance
    :param fun_map: name of the functioning map
    :type doc: :string:
    """
    print sub_list
    doc.append(NewPage())
    sec_sismicicdad = open(ruta + "bulletfiles/seccion_sismicidad_mes.txt",
                           "r").read()

    #doc.append(NoEscape(r"\chapterimage{"+ruta+"bulletfiles/sgc_blanco2.jpg}"))
    doc.append(
        NoEscape(r"\chapter{SISMICIDAD \textcolor{sgc2}{DE %s} \\DE %s}" %
                 (month1.upper(), year1)))

    # agregando texto desde archivo
    doc.append(NoEscape(r"\noindent "))
    doc.append(sec_sismicicdad % (month1, t, lc, reg, pac, car, volc, imp))
    with doc.create(Enumerate()) as enum:

        enum.add_item("El sismo tiene una profundidad menor a 120 km y \
	  su magnitud (ML) es mayor o igual a 4.0 en la escala de \
	  Richter o su magnitud de momento (Mw) es mayor o igual 4.0.")

        enum.add_item("El sismo tiene una profundidad mayor o igual \
	  a 120 km y su magnitud (ML) es mayor o igual a 5.0 en la \
	  escala de Richter o su magnitud de momento (Mw) es mayor o igual 5.0.")
        enum.add_item("El sismo es reportado como sentido cerca al epicentro, \
	  sin importar su magnitud o su profundidad.")

    with doc.create(Center()):
        doc.append(NoEscape(r"\sffamily\textcolor{ocre}{Convenciones}"))
    with doc.create(Tabular('ll')) as table:
        table.add_row((bold('FECHA'), "Año Mes Día"))
        table.add_row((bold('H:M:S'),
                       SmallText('Hora:Minuto:Segundo. Hora del \
	  evento en tiempo universal (UT).')))
        table.add_row((
            bold(''),
            SmallText(
                "Para la hora local en el territorio Colombiano se restan 5 horas."
            )))
        table.add_row((bold(''), SmallText("a la hora UT.")))
        table.add_row((bold('LAT'), SmallText("Latitud en grados.")))
        table.add_row((bold('LON'), SmallText("Longitud en grados.")))
        table.add_row((bold('Z'), SmallText("Profundidad en kilometros.")))
        table.add_row((bold('M'), "Magnitud del evento."))
        table.add_row((bold('UBICACION'), SmallText("Epicentro del evento.")))

    # =======================================================================
    #  tabla de sismicidad destacada
    # =======================================================================
    if sub_list[0][0] == "1":
        # tabla con eventos destacados
        doc.append(NoEscape(r"\newpage"))
        doc.append(
            NoEscape(r"\section{Tabla de sismicidad destacada %s de %s}" %
                     (month1, year1)))
        doc.append(NoEscape(r"\vspace{0.8cm}"))

        data_list = sc_table("sc_destacados.out")

        with doc.create(
                LongTabu(
                    "X[1.3,c] X[1.2,c] X[c] X[1.1,c] X[0.4,c] X[0.4,c] X[4,l]",
                    row_height=1)) as data_table:
            data_table.add_row(
                NoEscape(r"\scriptsize\sffamily\bfseries FECHA"),
                NoEscape(r"\scriptsize\sffamily\bfseries H:M:S"),
                NoEscape(r"\scriptsize\sffamily\bfseries LAT"),
                NoEscape(r"\scriptsize\sffamily\bfseries LON"),
                NoEscape(r"\scriptsize\sffamily\bfseries Z"),
                NoEscape(r"\scriptsize\sffamily\bfseries M"),
                NoEscape(r"\scriptsize\sffamily\bfseries UBICACION"),
                color="sgc2")
            #data_table.add_empty_row()
            data_table.end_table_header()

            # para cada elemento en la lista list_to_table (lista con info de destacados)
            for i in range(len(data_list)):
                if (i % 2) == 0:
                    data_table.add_row(Command("tiny", data_list[i][0]),
                                       Command("tiny", data_list[i][1]),
                                       Command("tiny", data_list[i][2]),
                                       Command("tiny", data_list[i][3]),
                                       Command("tiny", data_list[i][4]),
                                       Command("tiny", data_list[i][5]),
                                       Command("tiny", data_list[i][6]),
                                       color="sgc2!20")
                else:
                    data_table.add_row(Command("tiny", data_list[i][0]),
                                       Command("tiny", data_list[i][1]),
                                       Command("tiny", data_list[i][2]),
                                       Command("tiny", data_list[i][3]),
                                       Command("tiny", data_list[i][4]),
                                       Command("tiny", data_list[i][5]),
                                       Command("tiny", data_list[i][6]))
            doc.append(
                NoEscape(r"\caption{Eventos destacados durante %s de %s}" %
                         (month1, year1)))

    # =======================================================================
    #  mapa de sismicidad destacada
    # =======================================================================
    if sub_list[1][0] == "1":
        file_inspector(sub_list[1][1])
        doc.append(NoEscape(r"\begin{figure}"))
        doc.append(NoEscape(r"\begin{minipage}{\textwidth}"))
        doc.append(
            NoEscape(r"\section{Mapa de sismicidad destacada %s de %s}" %
                     (month1, year1)))
        #		doc.append(NoEscape(r"\vspace{-1.5cm}"))
        doc.append(NoEscape(r"\begin{center}"))
        doc.append(
            NoEscape(r"\includegraphics[scale=0.18]{%s}\\" % sub_list[1][1]))
        doc.append(
            NoEscape(r"\caption{\small{Eventos destacados durante %s de %s}}" %
                     (month1, year1)))
        doc.append(NoEscape(r"\end{center}"))
        #		doc.append(NoEscape(r"\vspace{-1.5cm}"))
        add_text(sub_list[1][2], doc)
        doc.append(NoEscape(r"\end{minipage}"))
        doc.append(NoEscape(r"\end{figure}"))

    # =======================================================================
    #  tabla de sismicidad mensual
    # =======================================================================
    if sub_list[2][0] == "1":

        doc.append(NoEscape(r"\newpage"))
        doc.append(
            NoEscape(r"\section{Tabla de sismicidad mensual %s de %s}" %
                     (month1, year1)))
        doc.append(NoEscape(r"\vspace{0.8cm}"))
        data_list = sc_table("sc_mensual.out")
        with doc.create(
                LongTabu(
                    "X[1.3,c] X[1.2,c] X[c] X[1.1,c] X[0.4,c] X[0.4,c] X[4,l]",
                    row_height=1)) as data_table:
            data_table.add_row(
                NoEscape(r"\scriptsize\sffamily\bfseries FECHA"),
                NoEscape(r"\scriptsize\sffamily\bfseries H:M:S"),
                NoEscape(r"\scriptsize\sffamily\bfseries LAT"),
                NoEscape(r"\scriptsize\sffamily\bfseries LON"),
                NoEscape(r"\scriptsize\sffamily\bfseries Z"),
                NoEscape(r"\scriptsize\sffamily\bfseries M"),
                NoEscape(r"\scriptsize\sffamily\bfseries UBICACION"),
                color="sgc2")
            #data_table.add_empty_row()
            data_table.end_table_header()

            # para cada elemento en la lista list_to_table (lista con info de destacados)
            for i in range(len(data_list)):
                if (i % 2) == 0:
                    data_table.add_row(Command("tiny", data_list[i][0]),
                                       Command("tiny", data_list[i][1]),
                                       Command("tiny", data_list[i][2]),
                                       Command("tiny", data_list[i][3]),
                                       Command("tiny", data_list[i][4]),
                                       Command("tiny", data_list[i][5]),
                                       Command("tiny", data_list[i][6]),
                                       color="sgc2!20")
                else:
                    data_table.add_row(Command("tiny", data_list[i][0]),
                                       Command("tiny", data_list[i][1]),
                                       Command("tiny", data_list[i][2]),
                                       Command("tiny", data_list[i][3]),
                                       Command("tiny", data_list[i][4]),
                                       Command("tiny", data_list[i][5]),
                                       Command("tiny", data_list[i][6]),
                                       color="white")
            doc.append(
                NoEscape(r"\caption{Eventos durante %s de %s}" %
                         (month1, year1)))

    # =======================================================================
    #  mapa de sismicidad mensual
    # =======================================================================
    if sub_list[3][0] == "1":
        print sub_list[3][1]
        print sub_list[3][2]
        file_inspector(sub_list[3][1])
        doc.append(NoEscape(r"\begin{figure}"))
        doc.append(NoEscape(r"\begin{minipage}{\textwidth}"))
        doc.append(
            NoEscape(r"\section{Mapa de sismicidad mensual %s de %s}" %
                     (month1, year1)))
        doc.append(NoEscape(r"\begin{center}"))
        #		doc.append(NoEscape(r"\vspace{-1.5cm}"))
        doc.append(
            NoEscape(r"\includegraphics[scale=0.18]{%s}" % sub_list[3][1]))
        doc.append(
            NoEscape(r"\caption{\small{Eventos durante %s de %s}}" %
                     (month1, year1)))
        doc.append(NoEscape(r"\end{center}"))
        #		doc.append(NoEscape(r"\vspace{-1.5cm}"))
        add_text(sub_list[3][2], doc)
        doc.append(NoEscape(r"\end{minipage}"))
        doc.append(NoEscape(r"\end{figure}"))