Esempio n. 1
0
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
Esempio n. 2
0
    def __init__(self):
        super().__init__()

        self.preamble.append(Command('title', 'Awesome Title'))
        self.preamble.append(Command('author', 'Anonymous author'))
        self.preamble.append(Command('date', NoEscape(r'\today')))
        self.append(NoEscape(r'\maketitle'))
Esempio n. 3
0
 def test_lambda_simple(self):
     tables = {}
     ret_ref = Flag()
     epochs = 8
     resp = _parse_lambda_fallback(
         lambda step: cosine_decay(step,
                                   cycle_length=3750,
                                   init_lr=1e-3 + 1
                                   if epochs > 2 else 1e-4), tables,
         ret_ref)
     self.assertIsInstance(
         resp, dict, "_parse_lambda_fallback should return a dictionary")
     self.assertEqual(
         {}, tables,
         "_parse_lambda_fallback should not have generated any tables for this lambda"
     )
     self.assertIn('function', resp,
                   "response should contain a function summary")
     self.assertEqual(
         r"cosine\_decay(step, cycle\_length=3750, init\_lr=1e{-}3 + 1 if epochs > 2 else 1e{-}4)",
         resp['function'])
     self.assertIn('kwargs', resp, "response should contain kwargs")
     self.assertIsInstance(resp['kwargs'], dict,
                           "kwargs should be a dictionary")
     self.assertDictEqual({NoEscape('epochs'): NoEscape(r'\seqsplit{8}')},
                          resp['kwargs'])
Esempio n. 4
0
def generate_table(book):
    '''
    this is used to generate in table style.
    suitable for language learning: e.g. Spanish / English etc
    '''
    print 'generating book: {title}'.format(title=book['title'])
    doc = Document(geometry_options=GEOMETRY_OPTIONS)
    doc = _setup_doc(doc, book)
    # doc.append(NoEscape(r'\maketitle'))

    section_count = 0
    for section in book['sections']:
        with doc.create(Section(section['title'], numbering=False)):
            with doc.create(LongTabu(_TABLE_FORMAT, row_height=1.5)) as table:
                table.end_table_header()
                row_elements = []
                for exercise in section['exercises']:
                    row_elements.append(NoEscape(exercise[0]))
                    row_elements.append(NoEscape(exercise[1]))
                    if len(row_elements) == 6:
                        table.add_row(row_elements)
                        row_elements = []
                    # table.add_hline()
        section_count += 1
        if section_count % 2 == 0:
            doc.append(NewPage())

    book_name = '{target_path}/{user} {title}'.format(target_path=TARGET_PATH,
                                                      user=book['user'],
                                                      title=book['title'])
    doc.generate_pdf(book_name, clean_tex=True, compiler='xelatex')
Esempio n. 5
0
def generate_exam(book):
    '''
    this is used to generate in exam style.
    Suitable for Math
    '''
    print 'generating book: {title}'.format(title=book['title'])
    doc = Document(documentclass='exam')
    doc = _setup_doc(doc, book)

    for section in book['sections']:
        with doc.create(Section(section['title'], numbering=False)):
            with doc.create(Questions()) as questions:
                for exercise in section['exercises']:
                    if isinstance(exercise, basestring):
                        questions.add_question(NoEscape(exercise))
                    else:
                        questions.add_question(
                            NoEscape(exercise['description']))
                        with questions.create(Parts()) as parts:
                            for sub_exercise in exercise['exercises']:
                                parts.add_part(NoEscape(sub_exercise))

    book_name = '{target_path}/{user} {title}'.format(target_path=TARGET_PATH,
                                                      user=book['user'],
                                                      title=book['title'])
    # import pdb; pdb.set_trace()
    doc.generate_pdf(book_name, clean_tex=False, compiler='xelatex')
Esempio n. 6
0
    def __init__(self, fontclass):
        super().__init__()
        self.preamble.append(Command('usepackage', fontclass))
        self.preamble.append(NoEscape(r'\usepackage{float}'))

        # geometry_options = {
        #     "margin": "0.5in",
        #     "bottom": "0.6in",
        # }
        #
        # self.preamble.append(Command('geometry_options', "margin=0.5in"))

        self.preamble.append(
            NoEscape(
                r'\usepackage[margin = 0.5in, head = 1in, bottom = 1in]{geometry}'
            ))
        self.preamble.append(NoEscape(r'\usepackage[export]{adjustbox}'))

        # self.preamble.append(NoEscape(r'\usepackage{geometry}\geometry{a4paper,total={170mm,257mm},left=20mm,top=20mm}'))
        self.preamble.append(
            Command('title',
                    'Multilocus Sequence Typing Report for multiple isolates'))
        # self.preamble.append(Command('author', 'Anonymous author'))
        self.preamble.append(Command('date', NoEscape(r'\today')))
        self.append(NoEscape(r'\maketitle'))
Esempio n. 7
0
    def change_thickness(self, element, thickness):
        r"""Change line thickness.

        Changes the thickness of the line under/over the header/footer
        to the specified thickness.

        Args
        ----
        element: str
            the name of the element to change thickness for: header, footer
        thickness: float
            the thickness to set the line to
        """

        if element == "header":
            self.data.append(
                Command("renewcommand",
                        arguments=[
                            NoEscape(r"\headrulewidth"),
                            str(thickness) + 'pt'
                        ]))
        elif element == "footer":
            self.data.append(
                Command("renewcommand",
                        arguments=[
                            NoEscape(r"\footrulewidth"),
                            str(thickness) + 'pt'
                        ]))
Esempio n. 8
0
 def square_button(self, doc):
     doc.preamble.append(Command(NoEscape(r'newcommand{\square}{')))
     doc.preamble.append(Command(NoEscape(r'begin{tabular}{|c|}')))
     doc.preamble.append(Command(NoEscape(r'hline')))
     doc.preamble.append(Command("\\ "))
     doc.preamble.append(Command(NoEscape(r'hline')))
     doc.preamble.append(Command(NoEscape(r'end{tabular}}')))
Esempio n. 9
0
 def __setup_preamble(self) -> None:
     """
     Setup preamble of the LaTeX document.
     :return: None
     """
     preamble = self.doc.preamble
     issue = self.data[0]
     preamble.append(NoEscape(r"\UseRawInputEncoding"))
     preamble.append(Command("title", issue["issue_key"]))
     author = issue["author"] if issue["author"] else "no author"
     preamble.append(Command("author", author))
     preamble.append(Command("date", issue["created"].split("T")[0]))
     preamble.append(
         Command(
             "lstset",
             NoEscape("tabsize = 4,"
                      r"showstringspaces = false,"
                      r"numbers = left,"
                      r"commentstyle = \color{darkgreen} \ttfamily,"
                      r"keywordstyle = \color{blue} \ttfamily,"
                      r"stringstyle = \color{red} \ttfamily,"
                      r"rulecolor = \color{black} \ttfamily,"
                      r"basicstyle = \footnotesize \ttfamily,"
                      r"frame = single,"
                      r"breaklines = true,"
                      r"numberstyle = \tiny")))
     preamble.append(NoEscape(r"\definecolor{darkgreen}{rgb}{0,0.6,0}"))
Esempio n. 10
0
        def InsDatosEscolares(hasImage):

            with self.doc.create(
                    Tabular(
                        NoEscape("m{0.8in}m{0.6in}m{0.9in}m{1.5in}m{2.3in}"))
            ) as table:
                if hasImage:
                    image = MultiRow(
                        3,
                        data=Command(
                            "includegraphics",
                            NoEscape(self.data["Foto"]
                                     [self.data["Foto"].rfind("/") +
                                      1:][:self.data["Foto"].rfind(".")]),
                            ["width=1.5in", "height=1in"]))
                else:
                    image = ""
                table.add_row(("", "", "", "", ""))
                table.add_row(("", "", "", "", image))
                table.add_row(
                    (bold("Matrícula: "), self.data["Matrícula"],
                     bold("Licenciatura: "), self.data["Licenciatura"], ""))
                table.add_row(
                    (bold("Semestre: "), self.data["Semestre"],
                     bold("Generación: "), self.data["Generación"], ""))
Esempio n. 11
0
 def rep_vm(self, doc, rep):
     doc.append(Command(NoEscape(r'begin{itemize}')))
     for s in rep:
         doc.append(Command(NoEscape(r'item[\square]')))
         doc.append(Command(NoEscape(r'hspace{2mm}')))
         doc.append(s[1])
     doc.append(Command(NoEscape(r'end{itemize}')))
Esempio n. 12
0
        def InsDatosEmergencia():
            with self.doc.create(SectionUnnumbered("En caso de emergencia")):
                Command("vspace", NoEscape("-1ex"))
                self.doc.append(NoEscape(\
                 r"{}{} {}: {} \\{}: {}\\"\
                 .format(bold("¿Padece alguna enfermedad?"), makeUnderline(self.data["¿Enfermedad?"], 0.2),bold("Especifique"), makeUnderline(self.data["Enfermedad"], 3.4), bold("Tipo de Sangre"), makeUnderline(self.data["Tipo de Sangre"], .5))
                 ))

                self.doc.append(NoEscape(\
                 r"{}:\\{}: {} {}: {}\\ "\
                 .format(bold("Contactar a"), bold("Nombre"), makeUnderline(self.data["Nombre Contacto"], 3.52),bold("Parentesco"), makeUnderline(self.data["Parentesco"], 1.5))
                 ))

                with self.doc.create(Tabular(
                        NoEscape("m{2in}m{2in}m{2in}"))) as table:
                    table.add_row((self.data["Teléfono Contacto"],
                                   self.data["Celular Contacto"],
                                   self.data["Correo Contacto"]))
                    table.add_hline()
                    table.add_row(
                        (bold("Teléfono Particular"), bold("Teléfono Celular"),
                         bold("Correo Electrónico")))

                self.doc.append(NoEscape(\
                 r"{}: {} {}: {}\\"\
                 .format(bold("Domicilio"), makeUnderline(self.data["Dirección Contacto"], 3.35),bold("Empresa"), makeUnderline(self.data["Negocio Contacto"], 1.63))
                 ))
Esempio n. 13
0
        def InsDatosDomicilio():
            with self.doc.create(SectionUnnumbered("Domicilio Particular")):
                Command("vspace", NoEscape("-1ex"))
                with self.doc.create(
                        Tabular(NoEscape(
                            "m{1.33in}m{0.6in}m{2in}m{1.9in}"))) as table:
                    table.add_row(
                        (self.data["Calle"], self.data["Número"],
                         self.data["Colonia"], self.data["Población"]))
                    table.add_hline()
                    table.add_row((bold("Calle"), bold("Número"),
                                   bold("Colonia"), bold("Poblacion")))

                with self.doc.create(Tabular(
                        NoEscape("m{2in}m{2in}m{2in}"))) as table:
                    table.add_row((self.data["Municipio"], self.data["Estado"],
                                   self.data["C.P."]))
                    table.add_hline()
                    table.add_row(
                        (bold("Municipio"), bold("Estado"), bold("C.P.")))

                with self.doc.create(Tabular(
                        NoEscape("m{2in}m{2in}m{2in}"))) as table:
                    table.add_row(
                        (self.data["Teléfono Particular"],
                         self.data["Teléfono Celular"], self.data["Correo"]))
                    table.add_hline()
                    table.add_row(
                        (bold("Teléfono Particular"), bold("Teléfono Celular"),
                         bold("Correo Electrónico")))
Esempio n. 14
0
def figure_MO_table(doc,
                    expr_list,
                    allfileslist,
                    tailleMO="8cm",
                    tailleMode="width",
                    caption="Molecular oribitals",
                    pos="p",
                    autosize=True):
    if autosize:
        tailleMO, tailleMode = _figure_MO_autoratio(allfileslist[0])
    doc.append(NoEscape(r'\begin{figure}[%s]' % pos))
    doc.append(NoEscape(r'\begin{minipage}[c][\textheight]{\textwidth}'))
    doc.append(NoEscape(r'\centering'))
    doc.append(NoEscape(r'\begin{tabular}{cc}'))
    for expr in expr_list:
        img = np.sort([i for i in allfileslist if i.find(expr) > 0])
        img_ = "{" + img[0][:-4] + "}.png"
        doc.append(
            NoEscape(r'\includegraphics[' + tailleMode + '=' + tailleMO +
                     ']{' + img_ + '} & '))
        img_ = "{" + img[1][:-4] + "}.png"
        doc.append(
            NoEscape(r'\includegraphics[' + tailleMode + '=' + tailleMO +
                     ']{' + img_ + '} \\\\ '))
    doc.append(NoEscape(r'\end{tabular}'))
    doc.append(NoEscape(r'\caption*{' + caption + '}'))
    doc.append(NoEscape(r'\end{minipage}'))
    doc.append(NoEscape(r'\end{figure}'))
Esempio n. 15
0
        def InsDatosFamiliares():
            with self.doc.create(SectionUnnumbered("Datos Familiares")):
                Command("vspace", NoEscape("-1ex"))
                self.doc.append(NoEscape(\
                 r"{}: {} {}: {}\\{}: {} {}: {}\\"\
                 .format(bold("Nombre del Padre"), makeUnderline(self.data["Nombre del Padre"], 2.75),bold("Teléfono"), makeUnderline(self.data["Teléfono Padre"], 1.65),\
                  bold("Domicilio"), makeUnderline(self.data["Dirección Padre"], 3.35),bold("Empresa"), makeUnderline(self.data["Negocio Padre"], 1.63))
                 ))

                with self.doc.create(Tabular(
                        NoEscape("m{2in}m{2in}m{2in}"))) as table:
                    table.add_row((self.data["Teléfono Padre"],
                                   self.data["Celular Padre"],
                                   self.data["Correo Padre"]))
                    table.add_hline()
                    table.add_row(
                        (bold("Teléfono Particular"), bold("Teléfono Celular"),
                         bold("Correo Electrónico")))

                self.doc.append(NoEscape(\
                 r"{}: {} {}: {}\\{}: {} {}: {}\\"\
                 .format(bold("Nombre de la Madre"), makeUnderline(self.data["Nombre de la Madre"], 2.75),bold("Teléfono"), makeUnderline(self.data["Teléfono Madre"], 1.55),\
                  bold("Domicilio"), makeUnderline(self.data["Dirección Madre"], 3.35),bold("Empresa"), makeUnderline(self.data["Negocio Madre"], 1.63))
                 ))

                with self.doc.create(Tabular(
                        NoEscape("m{2in}m{2in}m{2in}"))) as table:
                    table.add_row((self.data["Teléfono Madre"],
                                   self.data["Celular Madre"],
                                   self.data["Correo Madre"]))
                    table.add_hline()
                    table.add_row(
                        (bold("Teléfono Particular"), bold("Teléfono Celular"),
                         bold("Correo Electrónico")))
Esempio n. 16
0
def generate_cover(doc):
		"""
		Generate a cover for generate_info_report func
		Cover contains name, date and branch info
		:param doc: a Document Class instance
		:return: null
		"""

		## Convert in default command of LaTeX to make title
		## \title{}
		## \author{}
		## \date{}
		doc.preamble.append(Command('title', 'RiMEA-Projekt Analyse'))
		doc.preamble.append(Command('author', get_git_status()[1]))
		doc.preamble.append(Command('date', get_git_status()[2]))

		## Use titling package to add line on title
		doc.packages.append(Package('titling'))

		branch = r"\begin{center}Branch: "+ get_git_status()[0] + "\par"
		doc.preamble.append(Command('predate', NoEscape(branch)))

		commit = r"\par commit: " + get_git_status()[3] + "\par\end{center}"
		doc.preamble.append(Command('postdate', NoEscape(commit)))

		doc.append(NoEscape(r'\maketitle'))
Esempio n. 17
0
    def __init__(self, lista, exercicio):
        super().__init__()
        self.ex = exercicio
        self.titulo = NoEscape('Lista ' + str(lista) + r' - ' + 'Exercício ' + str(exercicio))

        self.packages.append(Package('babel', 'brazilian'))
        self.packages.append(Package('fontenc', 'T1'))
        self.packages.append(Package('geometry', ['a4paper', 'margin=2cm']))
        self.packages.append(Package('amsmath'))
        self.packages.append(Package('amssymb'))

        self.packages.append(Package('inputenc', 'utf8'))
        self.packages.append(Package('textgreek'))
        self.preamble.append(Command('DeclareUnicodeCharacter', ['3BB', Command('textlambda')]))
        self.preamble.append(Command('DeclareUnicodeCharacter', ['2260', Math(inline=True, data=[Command('neq')])]))
        self.preamble.append(Command('DeclareUnicodeCharacter', ['221E', Math(inline=True, data=[Command('infty')])]))

        self.packages.append(Package('titlesec'))
        self.preamble.append(Command('titleformat', [Command('section'), NoEscape(r'\filcenter\Large'), '', '1em', '']))
        self.preamble.append(Command('titleformat', Command('subsection'), 'runin', extra_arguments=[NoEscape(r'\normalfont\large\bfseries'), Command('thesubsection'), '1em', '']))

        self.packages.append(Package('minted', 'cache=false'))
        self.packages.append(Package('xcolor'))
        self.packages.append(DefineColor(['darkergray', 'rgb', '.86,.86,.86']))

        self.preamble.append(Command('title', gera_titulo('Estrutura de Dados - MC202 A', '1º Semestre de 2018')))
        self.preamble.append(Command('author', bold('Tiago de Paula Alves - 187679')))
        self.preamble.append(Command('date', ''))
        self.append(Command('maketitle'))
 def addPic(self):
     """
     This function can randomly insert an image
     with random size
     The image can be either single-row or across two rows
     The caption of an image will be a lorem-ipsum sentence
     """
     mod = random.choice([0, 1])
     scale_width = random.choice([0.5, 0.75, 1])
     scale_height = random.choice([0.5, 0.75, 1, 1.5, 2])
     with open('./lorem-ipsum-caption.txt', 'r', encoding='UTF-8') as f:
         all = f.readlines()
         caption_name = random.choice(all)
     for root, dirnames, filenames in os.walk('./img'):
         img = os.path.join(root + '/', random.choice(filenames))
     if mod == 0:
         with self.doc.create(Figure(position='htbp')) as fig:
             fig.add_image(img,
                           width=NoEscape(r'%f\linewidth' % scale_width))
             fig.add_caption(caption=caption_name)
     else:
         img_name = '{.' + img.split('.')[1] + '}.' + img.split('.')[2]
         with self.doc.create(MyFigure(options='hb')):
             self.doc.append(Command('centering'))
             self.doc.append(
                 Command(
                     'includegraphics',
                     options=Options(
                         NoEscape(
                             r'width=%f\textwidth, height=%f\textwidth' %
                             (scale_width, scale_height * 0.3))),
                     arguments=NoEscape(img_name)))
             self.doc.append(Command('caption', caption_name))
Esempio n. 19
0
def geometrische_angaben_pultdach(self, doc, arg_latex):
    hoehe = self.pultdach.hoehe
    dachneigung = self.pultdach.dachneigung
    breite_x = self.pultdach.breite_x
    breite_y = self.pultdach.breite_y
    vereinfachtes_verfahren = self.pultdach.verfahren_wahl

    doc.append(NoEscape(r'\subsubsection*{Geometrische Angaben}'))
    doc.append(NoEscape(r'\begin{table}[h]'))
    doc.append(NoEscape(r'\centering'))
    doc.append(
        NoEscape(
            r'\begin{tabular}{R{1.5cm}  @{ }L{2.0cm} @{ \dots} L{3.14cm}  R{1.5cm}  @{ }L{2.0cm} @{ \dots} L{5.25cm}}'
        ))
    doc.append(NoEscape(r'$h =$&\SI{' + str(hoehe) + r'}{\meter}  &  Höhe &'))
    doc.append(
        NoEscape(r'$b_x =$&$\SI{' + str(breite_x) +
                 r'}{\meter}$  &	 Breite in +X \\'))
    doc.append(
        NoEscape(r'$\alpha=$&$\ang{' + str(dachneigung) +
                 r'}$  & Dachneigung &'))
    doc.append(
        NoEscape(r'$b_y =$&$\SI{' + str(breite_y) +
                 r'}{\meter}$ & Breite in +Y '))
    doc.append(NoEscape(r'\end{tabular}'))
    doc.append(NoEscape(r'\end{table}'))
Esempio n. 20
0
    def create_document(self):
        geometry = {
            "head": "40pt",
            "margin": "1in",
            "bottom": "1in",
        }

        doc = Document(geometry_options=geometry)
        page = PageStyle("pagestyle")
        with page.create(Head("L")) as header_left:
            with header_left.create(
                    MiniPage(width=NoEscape(r"0.5\textwidth"),
                             pos="c")) as logo_wrapper:
                logo_file = os.path.join(get_current_directory(),
                                         "assets/" + LOGO).replace("\\", "/")
                logo_wrapper.append(
                    StandAloneGraphic(image_options="width=120px",
                                      filename=logo_file))

        with page.create(Head("R")) as right_header:
            with right_header.create(
                    MiniPage(width=NoEscape(r"0.5\textwidth"),
                             pos="c",
                             align="r")) as title_wrapper:
                title_wrapper.append(LargeText(bold("Vindskjerming")))

        doc.preamble.append(page)
        doc.change_document_style("pagestyle")
        return doc
def add_sub_figure(doc, graphics_dir, image_names=[], captioning="Metrics"):
    """
    Helper function to create multiple sub figures
    Arguments:
        doc: document to add figure
        graphics_dir: directory containing .png image
        image_names: the list of image names without extension
        captioning: global captioning for the figure
    """
    num_figures = len(image_names)
    scale = 1.0 / num_figures
    sub_width = str(scale) + r"\linewidth"

    with doc.create(Figure(position="h!")) as fig:
        for image in image_names:
            image_filename = os.path.join(os.path.dirname(__file__),
                                          graphics_dir, image + ".png")

            with doc.create(SubFigure(position="b",
                                      width=NoEscape(sub_width))) as sub_fig:

                sub_fig.add_image(image_filename,
                                  width=NoEscape(r"\linewidth"))
                sub_fig.add_caption(image)

        fig.add_caption(captioning)
Esempio n. 22
0
    def __init__(
        self,
        df,
        filepath,
        table_string=None,
        booktabs=True,
        logging=True,
        options_packages=[
            ("locale=DE", "siunitx"),
            ("", "booktabs"),
            ("ngerman", "babel"),
        ],
    ):
        r"""Fill TexTable with DataFrame.

        Parameters
        ----------
        df : pandas.DataFrame
            Data.
        filepath : str
            Complete filepath without extensions to name PDF and TEX files.
        table_string: str, None
            String in \tabular{table_string}.
            If None, default to 'S' for number of fields.
        booktabs : bool, True
            Using booktabs style horizontal lines.
        logging : bool, True
            Log if compilation occurs.
        options_packages : list[tuple]
            Additional packages with options to include in header of TEX file.
        """
        self.df = df
        self.filepath = filepath
        self.logging = logging

        if table_string is None:
            table_string = "S " * df.shape[1]

        self.table = Tabular(table_string,
                             booktabs=booktabs,
                             width=df.shape[1])
        self.table.escape = False

        self.document = Document(self.filepath,
                                 documentclass="standalone",
                                 document_options="preview")
        for opt_pack in options_packages:
            self.document.packages.append(
                NoEscape(r"\usepackage[{}]".format(opt_pack[0]) + r"{" +
                         str(opt_pack[1]) + r"}"))

        self.table.add_row(self.df.columns)

        self.table.add_hline()  # \midrule

        for i in range(self.df.shape[0]):
            self.table.add_row(self.df.loc[i].values)

        self.document.append(NoEscape(self.table.dumps()))
Esempio n. 23
0
def graphs(fname, width, *args, **kwargs):
     with doc.create(Section(fname)):
        with doc.create(Figure(position='h')) as plot1:
            plot1.add_plot(width=NoEscape(width), *args, **kwargs)
            line_graph(single_data, ylabel="Single Effective Marginal Tax Rate")
        with doc.create(Figure(position='h')) as plot2:
            plot2.add_plot(width=NoEscape(width), *args, **kwargs)
            line_graph(joint_data, ylabel="Joint Effective Marginal Tax Rate")
Esempio n. 24
0
    def __init__(self, basename):
        super().__init__()

        self.preamble.append(
            Command('title', 'QC Report of {}'.format(basename)))
        # self.preamble.append(Command('author', 'Anonymous author'))
        self.preamble.append(Command('date', NoEscape(r'\today')))
        self.append(NoEscape(r'\maketitle'))
Esempio n. 25
0
 def rep_vu(self, doc, rep):
     doc.append(Command(NoEscape(r'begin{itemize}')))
     for a in rep:
         doc.append(Command(NoEscape(r'item[')))
         doc.append(Command(NoEscape(r'radiobutton]')))
         doc.append(Command(NoEscape(r'hspace{2mm}')))
         doc.append(a[1])
     doc.append(Command(NoEscape(r'end{itemize}')))
Esempio n. 26
0
def createTex(docFile, resultOCR):
    docFile.preamble.append(Command('title', 'OCR Result'))
    docFile.preamble.append(Command('author', getpass.getuser()))
    docFile.preamble.append(Command('date', NoEscape(r'\today')))
    docFile.append(NoEscape(r'\maketitle'))

    with docFile.create(Section('Result')):
        docFile.append(resultOCR)
Esempio n. 27
0
 def add_solution(self, ah):
     #  use database approach here.
     with self. doc.create(Section('Lösungen', numbering = False, label = False)):
         with self.doc.create(Enumerate()) as enum:
             for a in ah.assignments:
                 enum.add_item(NoEscape('$'+a.latex_solution + '$'))
                 #self.doc.append(NoEscape(r'\newline'))      
                 #self.draw_grid(10,4)
         self.doc.append(NoEscape(r'\newpage'))
Esempio n. 28
0
 def __init__(self):
     super().__init__(documentclass='book',
                      document_options=['12pt', 'b5paper', 'twoside'],
                      indent=True)
     self.preamble.append(Command('title', 'Blogs of Paul Graham'))
     self.preamble.append(Command('author', 'scrapy by gk'))
     self.preamble.append(Command('date', NoEscape(r'\today')))
     self.append(NoEscape(r'\maketitle'))
     self.append(NoEscape(r'\tableofcontents'))
 def _escape_latex_symbols(self, data):
     reconData = []
     for s in data:
         if s == ' ':
             reconData.append(NoEscape(r'\space '))
         elif s == '*':
             reconData.append(NoEscape(r'\ctmstar '))
         else:
             reconData.append(s)
     return reconData
Esempio n. 30
0
def _append2latexdoc(doc, content):
    if isinstance(content, list):
        for item in content:
            if item.get('title'):
                doc.append(_get_section(**item))
                _append2latexdoc(doc, item['content'])
            else:
                _append2latexdoc(doc, item)
    else:
        section = _get_last_section(doc)
        if content.get('text'):
            if isinstance(content['text'], dict):
                section.append(open(content['text']['filename']).read())
            else:
                temp = ''
                if isinstance(content['text'],list):
                    for subtext in content['text']:
                        temp += subtext
                elif isinstance(content['text'],str):
                    temp = content['text']
                else:
                    raise Exception(f'Did not understand format of text string: \n {content["text"]}')
                section.append(temp)
        if content.get('latex_code'):
            if isinstance(content['latex_code'], dict):
                section.append(NoEscape(open(content['latex_code']['filename']).read()))
            else:
                section.append(NoEscape(content['latex_code']))
        if content.get('table'):
            for table in content['table']:
                section.append(NoEscape('\\begin{table}[H]'))  # note require float latex package for H command
                if table.get('filename'):
                    df = pd.read_excel(table['filename'], **table['kwargs'])
                elif isinstance(table.get('dataframe'),pd.DataFrame):
                    df = table.get('dataframe')
                section.append(NoEscape(df.to_latex(longtable=True,multicolumn_format='c')))
                section.append(NoEscape('\\end{table}'))
        if content.get('image'):
            for image in content.get('image'):
                section.append(NoEscape('\\begin{figure}[H]'))  # note require float latex package for H command
                Figure.add_image(section, image['filename'])
                section.append(NoEscape('\\end{figure}'))
        if content.get('subimage'):
            figure = Figure(position='H')
            for i, subimage in enumerate(content['subimage']):
                subfigure = SubFigure(width=NoEscape(
                    r'{}\linewidth'.format(np.round(1. / subimage.get('nr_horizontal_subimages', 2), 2) - 0.01)))
                subfigure.add_image(subimage['filename'])
                if subimage.get('caption', False):
                    subfigure.add_caption(subimage['caption'])
                if subimage.get('figure_caption', False) and i == 0:
                    figure.add_caption(subimage['figure_caption'])
                figure.append(subfigure)
                if (i + 1) % subimage.get('nr_horizontal_subimages', 2) == 0 and i != 0 or subimage.get(
                        'nr_horizontal_subimages', 2) == 1:
                    section.append(figure)
                    figure = Figure(arguments=NoEscape('\ContinuedFloat'), position='H')
            section.append(figure)
        if content.get('packages'):
            [doc.packages.append(Package(package)) for package in content['packages']]