<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gabi Cavalcante on Medium]]></title>
        <description><![CDATA[Stories by Gabi Cavalcante on Medium]]></description>
        <link>https://medium.com/@_gabiCavalcante?source=rss-60e12fcdb956------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*TDSztjvkzNYDFc9-nn00tA.jpeg</url>
            <title>Stories by Gabi Cavalcante on Medium</title>
            <link>https://medium.com/@_gabiCavalcante?source=rss-60e12fcdb956------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:30:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@_gabiCavalcante/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[…]]></title>
            <link>https://medium.com/@_gabiCavalcante/-76e26065139e?source=rss-60e12fcdb956------2</link>
            <guid isPermaLink="false">https://medium.com/p/76e26065139e</guid>
            <category><![CDATA[palestra]]></category>
            <category><![CDATA[comunicação]]></category>
            <category><![CDATA[comunidade]]></category>
            <dc:creator><![CDATA[Gabi Cavalcante]]></dc:creator>
            <pubDate>Sat, 23 Nov 2019 00:43:53 GMT</pubDate>
            <atom:updated>2019-11-23T02:47:52.967Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vamos trocar umas ideias sobre comunicação</h3><p>A ideia aqui é juntar sugestões que podem te ajudar caso você queira/vá dar um curso/aula/palestra e esteja preocupada em como fazer isso. Juntei algumas coisas que observei ao longo desses anos trabalhando no <a href="http://brasil.pyladies.com/about/"><strong>PyLadies Brasil</strong></a>, e talvez você possa aproveitar um pouco disso :) A ideia do post surgiu de uma conversar no grupo do <a href="https://www.instagram.com/pyladiesnatal/?hl=pt-br">PyLadies Natal</a>, então a própria construção dessas sugestões foi algo coletivo.</p><p>Uma das coisas que sempre faço logo no começo das atividades <strong>é perguntar a experiência que o pessoal tem naquilo que estou falando sobre. </strong>As vezes a gente supõe um nível, e a galera tem outro, e rola um grande desencontro de informação. Algumas vezes eu ainda chego a preparar materiais alternativos (ou diferentes exercícios), que eu possa usar dependendo da experiência das pessoas com quem estou falando (ex: se são iniciantes, se já tem conhecimento mas não experiência prática, etc).</p><p>Algo que também é interessante é <strong>sempre que usar uma expressão em inglês, também usar a equivalente em português</strong>. A gente está em um área carregada de expressões técnicas em inglês, é até bom o pessoal saber por exemplo o que é “<a href="https://pt.wikipedia.org/wiki/Depura%C3%A7%C3%A3o"><em>debug</em></a>” ou “<a href="https://pt.wikipedia.org/wiki/Raspagem_de_dados"><em>webscraping</em></a>”, mas soltar a expressões sem dar uma tradução pode dificultar o entendimento de algumas pessoas. Então quando for falar a expressão em <strong>inglês</strong>, também fale em <strong>português</strong> junto.</p><p>As vezes partimos do ponto que a turma pra quem estamos falando já entende um certo conceito, mas vamos lembrar que isso pode ser algo que a nossa experiência nos ensinou, e nem todo mundo trilhou o mesmo caminho que a gente. Por isso, sempre tento <strong>explicar os conceitos que eu cito, e ai eu peço pra galera me avisar caso ela já saiba</strong> (e não o contrario, que é falar coisas e pedir para que eles avisem quando não entenderem… dependendo, eles podem nunca fazer que não estão entendendo).</p><p>As vezes também temos uma certa mania de reproduzir expressões que no fim, só dão aquela atrapalhada. Algo que eu fazia muito, e notei que <strong>não é nada bom</strong>, é falar que as coisas são fáceis, tipo “<em>pessoal, vamos fazer isso aqui, é bem simples</em>”, “<em>é bem fácil</em>”, “<em>vocês fazem rápido</em>”… Essas eram frases que eu passei muito tempo falando por força do habito, até notar que tem gente que fica ansiosa com o medo de não entender o que era pra ser “fácil” e trava na tarefa (eu mesma no caso). Além disso, você só acha aquele assunto fácil por já ter estudado, trabalhado, e exercitado aquilo (né?). Aproveita o embalo e já tenta evitar falar “<em>os atrasados estão em que parte?</em>”, “<em>tem alguém atrasado?</em>”, “<em>quem diria</em>”, “<em>até que enfim” </em>e por ai vai.</p><p>Uma outra mania que sugiro que a gente dê aquela repensada é a de perguntar “<em>vocês entenderam?”</em>. Hoje em dia eu tento sempre lembrar de perguntar “<em>eu to explicando direito?</em>”. Mudar a forma com que as perguntas são feitas causa um impacto grande. Nessa caso, reformular a pergunta <strong>faz a gente lembrar que a responsabilidade de transmitir aquele conhecimento é nossa</strong>.</p><p>Algo que as vezes faço também é <strong>dividir um problema em pequenos pedaços. </strong>Quando vou dar introdução a python com <em>webscraping </em>(raspagem de dados ;) eu divido o problema em partezinhas. Por exemplo, “<em>recuperamos o texto da página, mas queremos só uma parte do conteúdo, e agora?</em>” Dai eu explico como fatiar textos em python, e peço pra eles me falarem como seria a solução. No passo seguinte, vamos achar outro problema, conversar sobre algum outro recurso do python, e discutir possíveis soluções.</p><p>Mas isso é uma opção, <strong>dividir o problema e fazer junto com a turma</strong>, de forma coletiva. As vezes eu vou chamando pessoas para irem na frente escrever a solução e as vezes reservo o fim do curso pra dar o problema todo e vou acompanhando (notei que essa última opção é um pouco mais complicada quando estou sozinha ou com poucas pessoas no apoio, nesse caso prefiro a abordagem de fazer junto com todo mundo).</p><p>Você pode ir sentindo qual abordagem usar dependendo da turma. <strong>Massss</strong>, se você não “sentir” isso, tudo bem, a gente vai tendo essa ideia do que fazer em cada situação com o tempo e experiência, e pegando turmas diferentes.</p><p>A gente fala muito de <strong>sentir</strong> a coisa, mas também não se cobre isso, na real, <strong>esteja atenta</strong>, e ai com a atenção a gente nota coisas. Na minha primeira palestra eu tava tão preocupada em provar que eu sabia dos assuntos, que eu falei um tanto de conteúdo que ninguém entendeu (o público era de iniciantes, e eu não me atentei a isso). Fiquei tão traumatizada, que depois disso mantive em mente o quanto eu queria ser plural e democrática na minha fala.</p><p>A verdade é que pra qualquer relação dar certo, <strong>a gente precisa estar atenta a outra parte da relação</strong> né? A mesma coisa se aplica na relação professor-aluno. Você pode até não saber o que fazer naquela hora, ou como agir naquela situação, mas você vai notar e vai se importar em fazer melhor na próxima vez.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76e26065139e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Pdf with Latex and Django]]></title>
            <link>https://medium.com/@_gabiCavalcante/create-pdf-with-latex-and-django-c892f4805aaf?source=rss-60e12fcdb956------2</link>
            <guid isPermaLink="false">https://medium.com/p/c892f4805aaf</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[latex]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Gabi Cavalcante]]></dc:creator>
            <pubDate>Tue, 01 Oct 2019 11:03:01 GMT</pubDate>
            <atom:updated>2019-10-01T11:03:01.563Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started in my new jog, the fist task was: <strong>reports</strong>. It was great because I didn’t know the software, but when I open the file that created PDFs, I found something really messed up. I needed define each position of every thing (columns, rows, title…) in my document, and define that in centimetres. So, a task that should take some time, would take much more.</p><p>But I reminded that Latex can easily created PDF, could I use it with Django? So I found <a href="https://github.com/weinbusch/django-tex"><strong>django-tex</strong></a>, a simple Django app to render LaTeX templates and compile them into PDF files. You just need a local Latex installations and jinja2 templating engine for templates rendering. In my case, I <a href="https://github.com/gabicavalcante/django-tex">fork</a> the project and include some escape character and filter for templates.</p><h3>Use</h3><ol><li>Add <strong>django_tex</strong>to your INSTALLED_APPS setting:</li></ol><pre>INSTALLED_APPS = [<br>    ...<br>    &#39;django_tex&#39;,<br>]</pre><p>2. Configure thesettings.py and make Latex file as your template:</p><pre>TEMPLATES = [<br>    {<br>        &#39;NAME&#39;: &#39;tex&#39;,<br>        &#39;BACKEND&#39;: &#39;django_tex.engine.TeXEngine&#39;, <br>        &#39;APP_DIRS&#39;: True,<br>        &#39;DIRS&#39;: [<br>            &#39;%s/templates&#39; % ROOT_PATH        <br>        ],    <br>    },<br>]</pre><p>3. Create a LaTeX template test.tex in your template directory:</p><pre>\documentclass{article}</pre><pre>\begin{document}</pre><pre>\section{ {{- title -}} }</pre><pre>\end{document}</pre><ol><li>Use compile_template_to_pdf in your code to get the PDF file as a bytes object</li></ol><pre>from django_tex.core import compile_template_to_pdf</pre><pre>template_name = &#39;teste.tex&#39;<br>context = {&#39;title&#39;: &#39;Arquivo PDF Teste&#39;}<br>PDF = compile_template_to_pdf(template_name, context)</pre><p>Or use render_to_pdf to get aHTTPResponse containing the PDF file.</p><pre>from django_tex.shortcuts import render_to_pdfdef view(request):<br>    <br>template_name = &#39;teste.tex&#39;<br>context = {&#39;title&#39;: &#39;Arquivo PDF Teste&#39;}<br>return render_to_pdf(request, template_name, context,<br>               filename=&#39;teste.pdf&#39;)</pre><p>The default LaTeX interpreter is set to lualatexThis but you can change by the setting LATEX_INTERPRETER, for instance: LATEX_INTERPRETER = &#39;pdflatex&#39;. To work properly, the interpreter needs to be installed on your system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c892f4805aaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python, Django and GitHub CI/CD]]></title>
            <link>https://medium.com/@_gabiCavalcante/python-django-and-github-ci-cd-65f9eae7e6fa?source=rss-60e12fcdb956------2</link>
            <guid isPermaLink="false">https://medium.com/p/65f9eae7e6fa</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Gabi Cavalcante]]></dc:creator>
            <pubDate>Mon, 30 Sep 2019 19:06:45 GMT</pubDate>
            <atom:updated>2019-10-04T03:42:29.074Z</atom:updated>
            <content:encoded><![CDATA[<h4>A demo CI/CD pipeline using Python Django and Pytest</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KszKm-8110p3v-LRzZCTZg.png" /></figure><p>GitHub Actions was introduced last year, and it’s an API for cause and effect on GitHub. You can orchestrate any workflow, based on any event, you can have your workflow run on push events to master and release branches, or only run on pull_request events that target the master branch, or run every day of the week at Friday 02:00. The workflows are code in a repository, as you will see in this project, so you can create, share, reuse, and fork.</p><p>I’m working in a Django project and when I started I found a problem: there was not CI/CD working or integration/unit test. In the past I used the GitLab CI/CD, but now the code was hosted on GitHub. So, my challenge was create tests to my Django project (it was implemented before I got the job) and create CI/CD pipeline for integrating it with GitHub CI/CD. For this tutorial, the application that I’m gonna show you, demonstrates CRUD operations using class based views in Django (you can find <a href="https://github.com/gabicavalcante/django-test-ci">here</a>). It also includes UI for all CRUD views and it’s based on the <a href="https://semaphoreci.com/blog/python-continuous-integration-continuous-delivery">semaphoreci.com</a> tutorial.</p><h3>Local project setup</h3><ol><li>You can use virtualenv for setting up this project.</li></ol><pre>$ virtualenv -p python3 env</pre><p>2. Download the project</p><pre>$ git clone <a href="https://github.com/gabicavalcante/django-test-ci.git">https://github.com/gabicavalcante/django-test-ci.git</a></pre><p>3. Install pip requirements</p><pre>$ pip install -r requirements.txt</pre><ol><li>Create a new psql database</li></ol><pre>postgres=# create database pydjango;</pre><p>3. Setup your database credentials and SITE_URL in settings.py file available inside core folder.</p><p>4. Once you have setup your database, open command prompt and run the migrate command to create the application default database and the superuser.</p><pre>(env) $ python manage.py migrate</pre><pre>(env) $ python manage.py createsuperuser</pre><p>5. Once all of the above command run successfully, let’s run:</p><pre>(env) $ python manage.py runserver</pre><p>6. And visit the web browser with <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a></p><h3>Environment variables</h3><p>The following environment variables can be set to override defaults:</p><ul><li>SECRET_KEY: Django <a href="https://docs.djangoproject.com/en/2.2/ref/settings/#secret-key">secret key</a>.</li><li>DB_ENGINE: Django database <a href="https://docs.djangoproject.com/en/2.2/ref/databases/">backend</a>.</li><li>DB_NAME: database name.</li><li>DB_HOST: database hostname.</li><li>DB_PORT: database port.</li><li>DB_USER: database user.</li><li>DB_PASSWORD: database password.</li></ul><h3>Test with PyTest</h3><p>To tell <strong>pytest</strong> witch Django settings that should be used for tests runs, we need to setup a <strong>pytest</strong> configuration file, called pytest.ini in our project root directory. The file contains:</p><pre>[pytest]<br>DJANGO_SETTINGS_MODULE=core.test_settings<br>addopts = --nomigrations --cov=. --cov-report=html</pre><p>To run the tests, we can invoke directly pytest command instead of manage.py test. The <strong>pytest-django</strong> is designed to run with the pytest command, but in case of you want to use manage.py test with pytest-django, you can create <a href="https://pytest-django.readthedocs.io/en/latest/faq.html#how-can-i-use-manage-py-test-with-pytest-django">a simple test runner</a>.</p><h3>CI/CD GIthub</h3><p>The example pipeline contains 3 blocks:</p><h4>Install Dependencies</h4><p>Installs pip requirements</p><h4>Run Code Analysis</h4><p>Run code analysis / code linting with Pylint</p><h4>Run Unit Tests</h4><p>Runs Unit Tests with pytest module for views and models file</p><h3>Control when your workflows are triggered</h3><p>Some time we don’t want workflows run on every push to every branch in the repo. So, we can have our workflow run on push events to master and release branches:</p><pre>on:<br>  push:<br>    branches:<br>      - master<br>      - release/*</pre><p>or only run on pull_request events that target the master branch:</p><pre>on:<br>  pull_request:<br>    branches:<br>      - master</pre><p>or, run every Friday at 02:00:</p><pre>on:<br>  schedule:<br>    - cron: 0 2 * * 5</pre><p>For more information see <a href="https://help.github.com/articles/events-that-trigger-workflows">Events that trigger workflows</a> and <a href="https://help.github.com/articles/workflow-syntax-for-github-actions#on">Workflow syntax for GitHub Actions</a>.</p><h4>Run your jobs on different operating systems</h4><p>GitHub actions provides hosted runners for Linux, Windows and macOS. To change the operating system for you job simply specify a different virtual machine:</p><pre>runs-on: ubuntu-latest</pre><p>For more information see <a href="https://help.github.com/articles/virtual-environments-for-github-actions">Virtual environments for GitHub Actions</a>.</p><h4>Conditionally run steps or jobs</h4><p>GitHub Actions supports conditions on steps and jobs based data present in your workflow context. To run a step only as part of a push and not in a pull_request you simply specify a condition in the if: property based on the event name:</p><pre>steps:<br>- run: npm publish ..<br>  if: github.event == &#39;push&#39;</pre><p>For more information on the expression language see <a href="https://help.github.com/articles/workflow-syntax-for-github-actions#jobsjob_idstepsif">Workflow syntax for GitHub Actions</a>.</p><h4>Use an action</h4><p>Actions are reusable units of work that can be built and distributed by anyone on GitHub. You can find a wide varity of actions in the <a href="https://github.com/marketplace?type=actions">GitHub marketplace</a>. Actions are referenced by specifying the repo that contains the action and the ref that you want to use.</p><pre>- name: &lt; display name for action &gt;<br>  uses: {owner}/{repo}@ref<br>  with:<br>      &lt;map of inputs&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65f9eae7e6fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebScraping, Python e Ordem da Câmara dos Deputados]]></title>
            <link>https://medium.com/@_gabiCavalcante/webscraping-python-e-ordem-da-c%C3%A2mara-dos-deputados-f6b46a088228?source=rss-60e12fcdb956------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6b46a088228</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Gabi Cavalcante]]></dc:creator>
            <pubDate>Mon, 30 Sep 2019 02:20:24 GMT</pubDate>
            <atom:updated>2019-11-13T18:36:20.984Z</atom:updated>
            <content:encoded><![CDATA[<h3>WebScraping, Python e Ordem da Câmara dos Vereadores</h3><h4><em>Usando tecnologia pra entender política</em></h4><p>Eu não sei se isso aconteceu com você, mas nas minhas rodas de conversa o tema <em>política</em> vem sendo uma pauta cada vez mais constante. No fim, a gente sempre fica com aquela pulga atrás da orelha sem saber o que exatamente está sendo feito com nosso dinheiro, o que tanto vem sendo discutido pelos políticos, quanto tempo vem sendo gasto nessas discussões… enfim.</p><p>Foi pensando nisso que começamos uma analise do conteúdo das <strong>Ordens do Dia da Câmara dos Vereadores </strong>como resultado de um projeto de disciplina de Ciência de Dados (UFRN). A ideia inicial seria ter uma noção de quantas pautas das reuniões eram requerimentos para entrega de Título de Cidadão Natalense. Mas o que seriam essas Ordens do Dia?</p><p>A câmara dos vereadores realiza alguns tipos de sessões, como as <strong>deliberativas</strong> e <strong>não</strong> <strong>deliberativas</strong>. As deliberativas são quando acontecem discussões e votações de proposições, e nesse caso, podemos ter as <strong>ordinárias</strong> e as <strong>extraordinárias</strong>. Já as não deliberativas são divididas em sessões de debate e solenes (homenagens e comemorações).</p><p><strong>Vamos focar nas sessões deliberativas</strong>, mas especificadamente na <strong>Ordem do Dia</strong>. A Ordem do Dia é um período em que há deliberação, discussão e votação de proposição. Essa sessão produz como resultado um PDF que fica disponível no <a href="https://www.cmnat.rn.gov.br/ordens">site da câmara municipal </a>(de Natal, no caso do nosso projeto).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9EK5Rug4OPjJmjacFYbXg.png" /></figure><p>Infelizmente os dados dessas sessões podem estar em formatos extremamente variados. Você pode ter a mesma informações sendo dada usando diferentes formatações, símbolos, espaçamentos, quantidade de quebras de linha… perceber isso foi o primeiro passo para visualizarmos o tamanho do nosso desafio.</p><p>O nosso objetivo aqui é raspar os documentos que foram disponibilizadas no primeiro semestre do ano de 2019, recuperar e organizar os dados que estão nesses documentos, e fazer algumas análises curiosas. Ao longo dessas analises, vamos dividir em diferentes posts tudo que o descobrimos e as descrição das ferramentas que usamos, já que passamos desde WebScraping, a NLP, dados Geolocalizados, e por ai vai.</p><h3>Raspando os dados</h3><p>O primeiro passo da análise foi pegar os documentos do site da Câmara Municipal. E para isso precisávamos entender como funcionava a pesquisa para encontra-los. Quando você entra no site, você pesquisa pelo ano e pelo mês através de um formulário. Como resultado o site te mostra um conjunto de links para os PDFs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lfqo05L9rtNUSve4s9c8w.png" /><figcaption>Resultado da pesquisa por documentos do mês 03 de 2019.</figcaption></figure><p>Usando o <strong>BeautifulSoup </strong>o trabalho ficou bem simples.</p><pre><em>from</em> bs4 <em>import</em> BeautifulSoup</pre><pre>months = {<br>    &#39;01&#39;: &#39;Janeiro&#39;,<br>    &#39;02&#39;: &#39;Fevereiro&#39;,<br>    &#39;03&#39;: &#39;Marco&#39;,<br>    &#39;04&#39;: &#39;Abril&#39;,<br>    &#39;05&#39;: &#39;Maio&#39;,<br>    &#39;06&#39;: &#39;Junho&#39;,<br>    &#39;07&#39;: &#39;Julho&#39;,<br>    &#39;08&#39;: &#39;Agosto&#39;,<br>    &#39;09&#39;: &#39;Setembro&#39;<br>}</pre><pre><em>for</em> month, label in months.items(): <br>    parameters = {&#39;ano_id&#39;: &#39;8&#39;, &#39;mes_id&#39;: month<br>    url = &quot;https://www.cmnat.rn.gov.br/ordens/send&quot;<br>    response = requests.post(url, data=parameters)</pre><p>Nesse trecho do código, criamos um dicionário com o código dos meses que gostaríamos de pesquisar por documentos . Em seguida, vamos caminhar por cada mês, fazendo uma requisição ao site da câmara municipal, passando como parâmetro o <strong>id</strong> do ano (vimos no site que o código para o ano de 2019 seria 8), e o id do mês.</p><p>Como resposta vamos receber uma página com o conjunto de links para os documentos, como vimos na imagem anterior. Para extrair esses links e baixar os documentos, bastou capturar o conteúdo de dentro das <em>tags </em>&lt;a&gt; caso ela esteja dentro da tag &lt;p&gt; e por sua vez, esta esteja dentro da tag &lt;li&gt;.</p><pre>doc = BeautifulSoup(response.text, &#39;html.parser&#39;)<br><em><br></em>content = doc.select(&quot;.listagem-noticias li p a&quot;)<br><em>if</em> not content:<br>    <em>continue</em></pre><pre>#<em> pegar o conteúdo da tag &lt;a&gt;<br></em>documents = [c.get_text() <em>for</em> c in content]</pre><pre>#<em> pegar o link dos documentos<br></em>urls = [c[&#39;href&#39;] <em>for</em> c in content]</pre><pre>#<em> criar o caminho para os documentos, caso não exista<br></em>path = &#39;../documents/{}/&#39;.format(label)<br><em>if</em> not os.path.exists(path):<br>    os.makedirs(path)</pre><pre><em>for</em> doc, url in zip(documents, urls):<br>    pdf = requests.get(url)<br>    file_name = &#39;{}&#39;.format(doc<br>        .lstrip()  #<em> remove initial space<br>        </em>.lower()  #<em> convert to lowcase<br>        </em>.replace(&#39; &#39;, &#39;_&#39;)<br>        .replace(&#39;/&#39;, &#39;_&#39;)<br>        .replace(&#39;-&#39;, &#39;_&#39;))<br>            open(&#39;../documents/{}/{}.pdf&#39;.format(label,<br>                  file_name), &#39;wb&#39;).write(pdf.content)</pre><p>Nesse ponto já temos todos os documentos de interesse salvos em diretórios divididos por mês. Veja o script completo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b78730f4d3cbdd369a0ec2e30737b9b4/href">https://medium.com/media/b78730f4d3cbdd369a0ec2e30737b9b4/href</a></iframe><p>O proximo passo é extrair informações.</p><h3>Organizando os dados</h3><p>Agora que temos os arquivos que queremos analisar, vamos extrair informação. As Ordens da Câmara tem uma estrutura padrão que se repente entre os documentos (não é muito bem formatada, mas segue um certo padrão).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Pif9dwgJ3mb5xAkwc3i_A.png" /></figure><p>Temos o cabeçalho do documento com informações sobre a Câmara, depois temos a data da Ordem, campos de assinatura para o Presidente, o 1° secretário e o 2° secretário, lista de oradores daquela seção e em seguida a lista de Pautas. As pautas podem ser um<strong> projeto de lei</strong>, <strong>projeto de emenda</strong>, <strong>moção</strong>, ou <strong>requerimento</strong>, elas vão possuir um <strong>número identificador</strong>, <strong>responsáveis</strong> e um <strong>assunto</strong>. No nosso caso, vamos focar em extrair a lista de oradores e as pautas do documento.</p><h4>Extraindo texto com PyPDF2</h4><p>Para ler as informações do arquivo PDF utilizamos o <a href="https://pythonhosted.org/PyPDF2/"><strong>PyPDF2</strong></a>, que vai extrair o conteúdo das páginas e armazena na variável pdf_text. Nessa etapa já existem alguns caracteres indesejados que podemos remover, como[&#39;\n&#39;, &#39;\\&#39;, &#39;-&#39;]. Conforme fomos analisando os documentos, novos caracteres indesejados foram identificados, e adicionados na lista de scape.</p><pre><em>import</em> PyPDF2</pre><pre>def <em>read_content</em>(file_path):<br>    pdfFileObj = open(file_path, &#39;rb&#39;)<br>    pdfReader = PyPDF2.PdfFileReader(pdfFileObj, strict=False)<br>    pdf_text = &#39;&#39;</pre><pre><em>    for</em> page in range(pdfReader.numPages)<br>        page_text = pdfReader.getPage(page).extractText()<br>        page_text = replace_all(scape, page_text)<br>        pdf_text += page_text</pre><h4>Expressões Regulares para ajudar nas incertezas</h4><p>O nosso maior desafio na etapa de pre-processamento foi lidar com a falta de padrão dos arquivos. Mesmo que a estrutura seja bem semelhante, pequenos detalhes que estávamos usando para saber onde um certo conteúdo começava e terminava, podiam ser distintos de documento para documento. Também acontecia de querermos achar informações que não tinham bem um delimitador de inicio e fim, mas tinham um padrão especifico quando apareciam, por exemplo, cada pauta tem um número de identificação:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htgyrKqcyl4Ei5UYs2ncNQ.png" /></figure><p>Nesse caso, precisávamos de um mecanismo flexível para encontrar uma cadeira de caracter formada por 1 ou mais dígitos antes do ‘<strong>/</strong>’ e 4 dígitos após, sabendo que esses 4 dígitos identificam o ano, e no caso, todos seriam depois de 2000. Para encontrar essa informação, utilizamos expressões regulares.</p><pre><em>import</em> re</pre><pre>re.search(r&#39;\d/20\d\d&#39;, keyword)</pre><p>Outro caso em que usamos isso foi para remover abreviações de <em>Vereador</em>, que podem vir como <strong>Ver.</strong> ou ‘<strong>Ver.ª</strong>. O problema foi que no caso da abreviação de <em>Vereadora</em>, tivemos <strong>Ver.ª</strong>, <strong>Verª. </strong>e<strong> Ver.a</strong>, e para não criar diversos casos e condicionais, usamos também expressões regulares.</p><pre>re.sub(r&#39;VER[.a]*[.ª]*[ .]* &#39;, &#39;&#39;)</pre><h4>Quebrando a cabeça com Linguagem Natural</h4><p>Então até agora conseguimos raspar os documentos do site da câmara, e achamos uma maneira prática para encontrar informações com um certo padrão no texto usando expressões regulares. Mas o que fazer com isso? Agora que temos uma massa de dados, temos textos descrevendo o que os vereadores falaram, como vamos fazer para entender o que vem sendo dito?</p><p>É agora que entra o <strong>processamento de linguagem natural</strong> (ou pelo menos, o pouco do que entendi sobre), e ferramentas como NLTK (Natural language toolkit), que nos ajudam a processar textos e extrair informações deles. O NLTK vai nos dar um conjunto de recursos para classificação, criação de tokens, tagging, stemming e lematização (e mais uma série de recursos que não cheguei a mexer ainda). Além de ser um projeto open source e muito bem documentado.</p><p>No pré-processamento dos dados, uma necessidade que tivemos foi de dividir nosso texto em pequenos pedaços, para poder encontrar expressões ou padrões no que estava sendo dito. O NLTK tem alguns recursos que nos permite dar um texto, e ele nos retorna pequenos blocos (sintáticos e semânticos) do conteúdo, que podem ser parágrafos, sentenças, frases e palavras.</p><p>No nosso caso, queremos transformar cada palavra em tokens. Para isso usamos uma função do <strong>nltk</strong> chamada word_tokenize. No nosso caso ela parece mais interessante do que usar um split(), que não encontraria tokens no sentindo linguistico.</p><pre>&gt;&gt;&gt; texto = &quot;Vamos tentar encontrar sentido nesses documentos, me desejem sorte.&quot;<br>&gt;&gt;&gt; texto.split()<br>[&#39;Vamos&#39;, &#39;tentar&#39;, &#39;encontrar&#39;, &#39;sentido&#39;, &#39;nesses&#39;, &#39;documentos,&#39;, &#39;me&#39;, &#39;desejem&#39;, &#39;sorte.&#39;]<br>&gt;&gt;&gt; from nltk import word_tokenize<br>&gt;&gt;&gt; word_tokenize(sent)<br>[&#39;Vamos&#39;, &#39;tentar&#39;, &#39;encontrar&#39;, &#39;sentido&#39;, &#39;nesses&#39;, &#39;documentos&#39;, &#39;,&#39;, &#39;me&#39;, &#39;desejem&#39;, &#39;sorte&#39;, &#39;.&#39;] </pre><h4>No fim, o que conseguimos?</h4><p>Com tudo isso em mãos, conseguimos pegar os documentos do site, extrair o texto, quebrar o texto em pequenos pedaços… e por fim, organizar o conteúdo.</p><p>O resultado final do processo foi um dicionário representando cada documento, contendo as informações dos oradores, e o conteúdos das pautas discutidas (assunto, movimento, número e responsável).</p><pre>{<br>    &quot;oradores&quot;: [<br>        &quot;AROLDO ALVES&quot;,<br>        &quot;ARY GOMES&quot;,<br>        &quot;BISPO FRANCISCO DE ASSIS&quot;,<br>        &quot;CARLA DICKSON&quot;,<br>        &quot;CHAGAS CATARINO&quot;,<br>        &quot;CÍCERO MARTINS&quot;<br>    ],<br>    &quot;pautas&quot;: [<br>        {<br>            &quot;assunto&quot;: &quot;Autoriza a compensação de dívidas de qualquer natureza perante o município de Natal com créditos líquidos certos vencidos ou vincendos ainda de que natureza tributária de titularidade de servidores públicos municipais e dá outras providências &quot;,<br>            &quot;movimento&quot;: &quot;EM SEGUNDA DISCUSSÃO COM EMENDA ENCARTADA&quot;,<br>            &quot;n&quot;: &quot;136/2014&quot;,<br>            &quot;responsavel&quot;: &quot;AROLDO ALVES PSDB SUBSCRITO PELO PRETO AQUINO PATRIOTA&quot;,<br>            &quot;tipo&quot;: &quot;PROJETO DE LEI&quot;<br>        },<br>        ...<br>    ]<br>}</pre><p>Esse dicionário é guardado em um banco de dados não relacional, <strong>o Mongo</strong>, para em seguida ser usado nas análises. Agora que os dados foram extraídos e organizados, vamos fazer algumas descobertas?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6b46a088228" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brincando com Kernel, docker e busy box]]></title>
            <link>https://medium.com/@_gabiCavalcante/brincando-com-kernel-docker-e-busy-box-27e2982dfc68?source=rss-60e12fcdb956------2</link>
            <guid isPermaLink="false">https://medium.com/p/27e2982dfc68</guid>
            <category><![CDATA[qemu]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <dc:creator><![CDATA[Gabi Cavalcante]]></dc:creator>
            <pubDate>Mon, 30 Sep 2019 01:25:58 GMT</pubDate>
            <atom:updated>2019-09-30T01:25:58.987Z</atom:updated>
            <content:encoded><![CDATA[<p>Algumas semanas atrás tive que testar compilar o kernel linux e testar ele juntamente com o busy box. Acabei brincando um pouco com o <strong>docker</strong>, <strong>qemu</strong>, e algumas outras coisas que achei importante registrar.</p><pre>➜  redes docker search ubuntu<br>NAME                                                      DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED<br>ubuntu                                                    Ubuntu is a Debian-based Linux operating sys…   9808                [OK]<br>dorowu/ubuntu-desktop-lxde-vnc                            Docker image to provide HTML5 VNC interface …   331                                     [OK]<br>rastasheep/ubuntu-sshd                                    Dockerized SSH service, built on top of offi…   226                                     [OK]<br>consol/ubuntu-xfce-vnc                                    Ubuntu container with &quot;headless&quot; VNC session…   186                                     [OK]<br>ubuntu-upstart                                            Upstart is an event-based replacement for th…   99                  [OK]<br>ansible/ubuntu14.04-ansible                               Ubuntu 14.04 LTS with ansible                   97                                      [OK]<br>1and1internet/ubuntu-16-nginx-php-phpmyadmin-mysql-5      ubuntu-16-nginx-php-phpmyadmin-mysql-5          50                                      [OK]<br>ubuntu-debootstrap                                        debootstrap --variant=minbase --components=m…   40                  [OK]<br>i386/ubuntu                                               Ubuntu is a Debian-based Linux operating sys…   18<br>1and1internet/ubuntu-16-apache-php-5.6                    ubuntu-16-apache-php-5.6                        14                                      [OK]<br>ppc64le/ubuntu                                            Ubuntu is a Debian-based Linux operating sys…   13<br>1and1internet/ubuntu-16-apache-php-7.0                    ubuntu-16-apache-php-7.0                        13                                      [OK]<br>1and1internet/ubuntu-16-nginx-php-phpmyadmin-mariadb-10   ubuntu-16-nginx-php-phpmyadmin-mariadb-10       11                                      [OK]<br>eclipse/ubuntu_jdk8                                       Ubuntu, JDK8, Maven 3, git, curl, nmap, mc, …   11                                      [OK]<br>1and1internet/ubuntu-16-nginx-php-5.6                     ubuntu-16-nginx-php-5.6                         8                                       [OK]<br>1and1internet/ubuntu-16-nginx-php-5.6-wordpress-4         ubuntu-16-nginx-php-5.6-wordpress-4             7                                       [OK]<br>1and1internet/ubuntu-16-apache-php-7.1                    ubuntu-16-apache-php-7.1                        6                                       [OK]<br>darksheer/ubuntu                                          Base Ubuntu Image -- Updated hourly             5                                       [OK]<br>1and1internet/ubuntu-16-nginx-php-7.0                     ubuntu-16-nginx-php-7.0                         4                                       [OK]<br>pivotaldata/ubuntu                                        A quick freshening-up of the base Ubuntu doc…   2<br>1and1internet/ubuntu-16-apache-php-5.6-zend-2             ubuntu-16-apache-php-5.6-zend-2                 2                                       [OK]<br>1and1internet/ubuntu-16-sshd                              ubuntu-16-sshd                                  1                                       [OK]<br>1and1internet/ubuntu-16-php-7.1                           ubuntu-16-php-7.1                               1                                       [OK]<br>smartentry/ubuntu                                         ubuntu with smartentry                          1                                       [OK]<br>pivotaldata/ubuntu-gpdb-dev                               Ubuntu images for GPDB development              0<br>➜  redes docker search ubuntu | heade -5<br>zsh: command not found: heade<br>➜  redes docker search ubuntu | head -5<br>NAME                                                      DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED<br>ubuntu                                                    Ubuntu is a Debian-based Linux operating sys…   9808                [OK]<br>dorowu/ubuntu-desktop-lxde-vnc                            Docker image to provide HTML5 VNC interface …   331                                     [OK]<br>rastasheep/ubuntu-sshd                                    Dockerized SSH service, built on top of offi…   226                                     [OK]<br>consol/ubuntu-xfce-vnc                                    Ubuntu container with &quot;headless&quot; VNC session…   186                                     [OK]<br>➜  redes docker pull ubuntu<br>Using default tag: latest<br>latest: Pulling from library/ubuntu<br>7413c47ba209: Pull complete<br>0fe7e7cbb2e8: Pull complete<br>1d425c982345: Pull complete<br>344da5c95cec: Pull complete<br>Digest: sha256:c303f19cfe9ee92badbbbd7567bc1ca47789f79303ddcef56f77687d4744cd7a<br>Status: Downloaded newer image for ubuntu:latest<br>docker.io/library/ubuntu:latest<br>➜  redes docker image ls<br>REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE<br>ubuntu              latest              3556258649b2        2 weeks ago         64.2MB<br>➜  redes docker run -ti ubuntu /bin/bash<br>root@b9efbbde665f:/# l<br>bin/  boot/  dev/  etc/  home/  lib/  lib64/  media/  mnt/  opt/  proc/  root/  run/  sbin/  srv/  sys/  tmp/  usr/  var/<br>root@b9efbbde665f:/#</pre><h3>fora do container</h3><pre>➜  ~ docker container exec b2bda67db7db df -h<br>➜  ~ docker container ls<br>CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES<br>b9efbbde665f        ubuntu              &quot;/bin/bash&quot;         13 minutes ago      Up 13 minutes                           stoic_lichterman<br>➜  ~ docker container exec b9efbbde665f df -h<br>Filesystem      Size  Used Avail Use% Mounted on<br>overlay          59G  1.3G   55G   3% /<br>tmpfs            64M     0   64M   0% /dev<br>tmpfs          1000M     0 1000M   0% /sys/fs/cgroup<br>shm              64M     0   64M   0% /dev/shm<br>/dev/sda1        59G  1.3G   55G   3% /etc/hosts<br>tmpfs          1000M     0 1000M   0% /proc/acpi<br>tmpfs          1000M     0 1000M   0% /sys/firmware</pre><p>instalar wget</p><pre>root@b9efbbde665f:~# wget https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.2.6.tar.gz<br>bash: wget: command not found<br>root@b9efbbde665f:~# sudo apt-get install wget<br>bash: sudo: command not found<br>root@b9efbbde665f:~# apt-get install wget<br>Reading package lists... Done<br>Building dependency tree<br>Reading state information... Done<br>E: Unable to locate package wget</pre><p>It is because there is no package cache in the image, you need to run:</p><pre>apt-get update<br>before installing packages, and if your command is in a Dockerfile, you&#39;ll then need:<br><br>apt-get -y install curl<br><br>root@b9efbbde665f:~# wget https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.2.6.tar.gz<br>--2019-08-09 13:05:26--  https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.2.6.tar.gz<br>Resolving cdn.kernel.org (cdn.kernel.org)... 151.101.93.176, 2a04:4e42:16::432<br>Connecting to cdn.kernel.org (cdn.kernel.org)|151.101.93.176|:443... connected.<br>HTTP request sent, awaiting response... 200 OK<br>Length: 164478004 (157M) [application/x-gzip]<br>Saving to: &#39;linux-5.2.6.tar.gz&#39;<br><br>linux-5.2.6.tar.gz                                     100%[=========================================================================================================================&gt;] 156.86M  3.66MB/s    in 4m 1s<br><br>2019-08-09 13:09:29 (668 KB/s) - &#39;linux-5.2.6.tar.gz&#39; saved [164478004/164478004]                                                                                                        ]   2.05M  62.6KB/s    eta 52m 54s                                                                                      ]  28.25M  4.66MB/s    eta 20s</pre><p>depois</p><pre>2019-08-09 12:51:50 (1023 KB/s) - &#39;linux-5.2.6.tar.xz&#39; saved [107056496/107056496]<br><br>root@b9efbbde665f:~# ls<br>linux-5.2.6.tar.gz<br>root@b9efbbde665f:~# ps -ef<br>UID        PID  PPID  C STIME TTY          TIME CMD<br>root         1     0  0 12:43 pts/0    00:00:00 /bin/bash<br>root      2562     1  0 12:55 pts/0    00:00:00 ps -ef<br>root@b9efbbde665f:~# tar xvfz linux-5.2.6.tar.gz<br>....<br>root@b9efbbde665f:~# rm linux-5.2.6.tar.gz<br>root@b9efbbde665f:~/linux-5.2.6# make x86_64_defconfig<br>bash: make: command not found<br>root@b9efbbde665f:~/linux-5.2.6# apt-get install make<br>root@b9efbbde665f:~/linux-5.2.6# apt install gcc<br>root@b9efbbde665f:~/linux-5.2.6# apt-get install flex<br>root@b9efbbde665f:~/linux-5.2.6# apt-get install bison<br>root@b9efbbde665f:~/linux-5.2.6#  make x86_64_defconfig<br>root@b9efbbde665f:~/linux-5.2.6# make menuconfig<br>*<br>* Unable to find the ncurses package.<br>* Install ncurses (ncurses-devel or libncurses-dev<br>* depending on your distribution).<br>*<br>scripts/kconfig/Makefile:206: recipe for target &#39;scripts/kconfig/mconf-cfg&#39; failed<br>make[1]: *** [scripts/kconfig/mconf-cfg] Error 1<br>Makefile:558: recipe for target &#39;menuconfig&#39; failed<br>make: *** [menuconfig] Error 2<br>root@b9efbbde665f:~/linux-5.2.6# apt-get install libncurses5-dev libncursesw5-dev<br>root@b9efbbde665f:~/linux-5.2.6# make menuconfig</pre><p>Crie uma pasta para armazenar o arquivo do kernel a ser gerado e os filesystems.</p><pre>mkdir ~/aux<br>DIR_AUX=~/aux</pre><p>Compilar o kernel e instalá-lo em uma pasta para usar em uma máquina virtual (com qemu, por exemplo). Ao executar o comando “make menuconfig” a seguir, desative algumas opções do kernel, como o suporte ao IPV6, por exemplo.</p><p>Pasta onde será criado o filesystem com o novo kernel (DIR_FS1)</p><pre>mkdir ~/fs1<br>DIR_FS1=~/fs1</pre><pre>root@b9efbbde665f:~/linux-5.2.6# ls<br>COPYING  Documentation  Kconfig   MAINTAINERS  README  block  crypto   fs       init  kernel  mm   samples  security  tools  virt<br>CREDITS  Kbuild         LICENSES  Makefile     arch    certs  drivers  include  ipc   lib     net  scripts  sound     usr<br>root@b9efbbde665f:~/linux-5.2.6# make -j 4 bzImage<br>  SYSTBL  arch/x86/include/generated/asm/syscalls_32.h<br>  SYSHDR  arch/x86/include/generated/asm/unistd_32_ia32.h<br>  SYSHDR  arch/x86/include/generated/asm/unistd_64_x32.h<br>  SYSTBL  arch/x86/include/generated/asm/syscalls_64.h<br>  UPD     include/config/kernel.release<br>  SYSHDR  arch/x86/include/generated/uapi/asm/unistd_32.h<br>  SYSHDR  arch/x86/include/generated/uapi/asm/unistd_64.h<br>  SYSHDR  arch/x86/include/generated/uapi/asm/unistd_x32.h<br>  WRAP    arch/x86/include/generated/uapi/asm/bpf_perf_event.h<br>  WRAP    arch/x86/include/generated/uapi/asm/poll.h<br>  WRAP    arch/x86/include/generated/uapi/asm/sockios.h<br>  WRAP    arch/x86/include/generated/uapi/asm/socket.h<br>  UPD     include/generated/uapi/linux/version.h<br>  UPD     include/generated/utsrelease.h<br>  HOSTCC  arch/x86/tools/relocs_32.o<br>  WRAP    arch/x86/include/generated/asm/dma-contiguous.h<br>  WRAP    arch/x86/include/generated/asm/early_ioremap.h<br>  WRAP    arch/x86/include/generated/asm/export.h<br>  WRAP    arch/x86/include/generated/asm/mcs_spinlock.h<br>  WRAP    arch/x86/include/generated/asm/mm-arch-hooks.h<br>  WRAP    arch/x86/include/generated/asm/mmiowb.h<br>  HOSTCC  scripts/selinux/genheaders/genheaders<br>  HOSTCC  scripts/selinux/mdp/mdp<br>  HOSTCC  arch/x86/tools/relocs_64.o<br>  HOSTCC  scripts/kallsyms<br>  HOSTCC  arch/x86/tools/relocs_common.o<br>  HOSTLD  arch/x86/tools/relocs<br>error: Cannot generate ORC metadata for CONFIG_UNWINDER_ORC=y, please install libelf-dev, libelf-devel or elfutils-libelf-devel<br>Makefile:1139: recipe for target &#39;prepare-objtool&#39; failed<br>make: *** [prepare-objtool] Error 1<br>make: *** Waiting for unfinished jobs....<br>  HOSTCC  scripts/pnmtologo<br>  HOSTCC  scripts/conmakehash<br>  HOSTCC  scripts/sortextable<br>  HOSTCC  scripts/asn1_compiler<br>  HOSTCC  scripts/extract-cert<br>scripts/extract-cert.c:21:10: fatal error: openssl/bio.h: No such file or directory<br> #include &lt;openssl/bio.h&gt;<br>          ^~~~~~~~~~~~~~~<br>compilation terminated.<br>scripts/Makefile.host:90: recipe for target &#39;scripts/extract-cert&#39; failed<br>make[1]: *** [scripts/extract-cert] Error 1<br>make[1]: *** Waiting for unfinished jobs....<br>Makefile:1086: recipe for target &#39;scripts&#39; failed<br>make: *** [scripts] Error 2</pre><p>para o make rodar sem erros, precisaremos instalar algumas libs</p><pre>root@b9efbbde665f:~/linux-5.2.6# apt-get install libelf-dev<br>root@b9efbbde665f:~/linux-5.2.6# apt-get install -y libsdl1.2-dev libssl-dev bc<br>root@b9efbbde665f:~/linux-5.2.6# make -j 4 bzImage<br>...<br>CC      arch/x86/boot/cpu.o<br>  GZIP    arch/x86/boot/compressed/vmlinux.bin.gz<br>  MKPIGGY arch/x86/boot/compressed/piggy.S<br>  AS      arch/x86/boot/compressed/piggy.o<br>  LD      arch/x86/boot/compressed/vmlinux<br>  ZOFFSET arch/x86/boot/zoffset.h<br>  OBJCOPY arch/x86/boot/vmlinux.bin<br>  AS      arch/x86/boot/header.o<br>  LD      arch/x86/boot/setup.elf<br>  OBJCOPY arch/x86/boot/setup.bin<br>  BUILD   arch/x86/boot/bzImage<br>Setup is 16060 bytes (padded to 16384 bytes).<br>System is 8529 kB<br>CRC c5d5c9b5<br>Kernel: arch/x86/boot/bzImage is ready  (#1)<br>root@b9efbbde665f:~/linux-5.2.6# make -j 4 modules<br>  DESCEND  objtool<br>  CALL    scripts/atomic/check-atomics.sh<br>  CALL    scripts/checksyscalls.sh<br>  CC [M]  fs/efivarfs/inode.o<br>  CC [M]  fs/efivarfs/file.o<br>  CC [M]  fs/efivarfs/super.o<br>  LD [M]  fs/efivarfs/efivarfs.o<br>  CC [M]  net/ipv4/netfilter/nf_log_arp.o<br>  CC [M]  net/ipv4/netfilter/nf_log_ipv4.o<br>  CC [M]  net/ipv6/netfilter/nf_log_ipv6.o<br>  CC [M]  net/ipv4/netfilter/iptable_nat.o<br>  CC [M]  drivers/thermal/intel/x86_pkg_temp_thermal.o<br>  CC [M]  net/netfilter/nf_log_common.o<br>  CC [M]  net/netfilter/xt_mark.o<br>  CC [M]  net/netfilter/xt_nat.o<br>  CC [M]  net/netfilter/xt_LOG.o<br>  CC [M]  net/netfilter/xt_MASQUERADE.o<br>  CC [M]  net/netfilter/xt_addrtype.o<br>  Building modules, stage 2.<br>  MODPOST 12 modules<br>  CC      drivers/thermal/intel/x86_pkg_temp_thermal.mod.o<br>  CC      net/ipv4/netfilter/nf_log_arp.mod.o<br>  CC      net/ipv4/netfilter/iptable_nat.mod.o<br>  CC      fs/efivarfs/efivarfs.mod.o<br>  CC      net/ipv4/netfilter/nf_log_ipv4.mod.o<br>  CC      net/ipv6/netfilter/nf_log_ipv6.mod.o<br>  CC      net/netfilter/nf_log_common.mod.o<br>  CC      net/netfilter/xt_LOG.mod.o<br>  CC      net/netfilter/xt_MASQUERADE.mod.o<br>  CC      net/netfilter/xt_addrtype.mod.o<br>  CC      net/netfilter/xt_mark.mod.o<br>  CC      net/netfilter/xt_nat.mod.o<br>  LD [M]  drivers/thermal/intel/x86_pkg_temp_thermal.ko<br>  LD [M]  fs/efivarfs/efivarfs.ko<br>  LD [M]  net/ipv4/netfilter/iptable_nat.ko<br>  LD [M]  net/ipv4/netfilter/nf_log_arp.ko<br>  LD [M]  net/ipv4/netfilter/nf_log_ipv4.ko<br>  LD [M]  net/ipv6/netfilter/nf_log_ipv6.ko<br>  LD [M]  net/netfilter/nf_log_common.ko<br>  LD [M]  net/netfilter/xt_LOG.ko<br>  LD [M]  net/netfilter/xt_MASQUERADE.ko<br>  LD [M]  net/netfilter/xt_addrtype.ko<br>  LD [M]  net/netfilter/xt_mark.ko<br>  LD [M]  net/netfilter/xt_nat.ko<br> root@b9efbbde665f:~/linux-5.2.6# make INSTALL_MOD_PATH=$DIR_FS1 modules_install<br>  INSTALL drivers/thermal/intel/x86_pkg_temp_thermal.ko<br>  INSTALL fs/efivarfs/efivarfs.ko<br>  INSTALL net/ipv4/netfilter/iptable_nat.ko<br>  INSTALL net/ipv4/netfilter/nf_log_arp.ko<br>  INSTALL net/ipv4/netfilter/nf_log_ipv4.ko<br>  INSTALL net/ipv6/netfilter/nf_log_ipv6.ko<br>  INSTALL net/netfilter/nf_log_common.ko<br>  INSTALL net/netfilter/xt_LOG.ko<br>  INSTALL net/netfilter/xt_MASQUERADE.ko<br>  INSTALL net/netfilter/xt_addrtype.ko<br>  INSTALL net/netfilter/xt_mark.ko<br>  INSTALL net/netfilter/xt_nat.ko<br>  DEPMOD  5.2.6<br>Warning: &#39;make modules_install&#39; requires /sbin/depmod. Please install it.<br>This is probably in the kmod package.<br>root@b9efbbde665f:~/linux-5.2.6# apt-get install kmod<br>Reading package lists... Done<br>Building dependency tree<br>Reading state information... Done<br>The following additional packages will be installed:<br>  libkmod2<br>The following NEW packages will be installed:<br>  kmod libkmod2<br>0 upgraded, 2 newly installed, 0 to remove and 3 not upgraded.<br>Need to get 129 kB of archives.<br>After this operation, 360 kB of additional disk space will be used.<br>Do you want to continue? [Y/n] Y<br>Get:1 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libkmod2 amd64 24-1ubuntu3.2 [40.0 kB]<br>Get:2 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 kmod amd64 24-1ubuntu3.2 [88.8 kB]<br>Fetched 129 kB in 2s (80.6 kB/s)<br>debconf: delaying package configuration, since apt-utils is not installed<br>Selecting previously unselected package libkmod2:amd64.<br>(Reading database ... 20374 files and directories currently installed.)<br>Preparing to unpack .../libkmod2_24-1ubuntu3.2_amd64.deb ...<br>Unpacking libkmod2:amd64 (24-1ubuntu3.2) ...<br>Selecting previously unselected package kmod.<br>Preparing to unpack .../kmod_24-1ubuntu3.2_amd64.deb ...<br>Unpacking kmod (24-1ubuntu3.2) ...<br>Setting up libkmod2:amd64 (24-1ubuntu3.2) ...<br>Processing triggers for libc-bin (2.27-3ubuntu1) ...<br>Setting up kmod (24-1ubuntu3.2) ...<br>root@b9efbbde665f:~/linux-5.2.6# make INSTALL_MOD_PATH=$DIR_FS1 modules_install<br>  INSTALL drivers/thermal/intel/x86_pkg_temp_thermal.ko<br>  INSTALL fs/efivarfs/efivarfs.ko<br>  INSTALL net/ipv4/netfilter/iptable_nat.ko<br>  INSTALL net/ipv4/netfilter/nf_log_arp.ko<br>  INSTALL net/ipv4/netfilter/nf_log_ipv4.ko<br>  INSTALL net/ipv6/netfilter/nf_log_ipv6.ko<br>  INSTALL net/netfilter/nf_log_common.ko<br>  INSTALL net/netfilter/xt_LOG.ko<br>  INSTALL net/netfilter/xt_MASQUERADE.ko<br>  INSTALL net/netfilter/xt_addrtype.ko<br>  INSTALL net/netfilter/xt_mark.ko<br>  INSTALL net/netfilter/xt_nat.ko<br>  DEPMOD  5.2.6<br>root@b9efbbde665f:~/linux-5.2.6# ls $DIR_FS1/<br>lib<br>root@b9efbbde665f:~/linux-5.2.6# cp System.map $DIR_AUX<br>root@b9efbbde665f:~/linux-5.2.6# ls $DIR_AUX<br>System.map</pre><p>Obs: O arquivo do kernel é gerado na pasta arch/x86_64/boot</p><pre>root@b9efbbde665f:~/linux-5.2.6# ls arch/x86_64/boot/<br>bzImage<br>root@b9efbbde665f:~/linux-5.2.6# cp arch/x86_64/boot/bzImage $DIR_AUX</pre><p>Obs: Analise a estrutura de pastas geradas dentro de $DIR_FS1</p><h3>qemu</h3><pre>root@b9efbbde665f:~# apt-get install qemu -y</pre><p>#Testando o kernel (1)</p><p>Do jeito que está se fecharmos o terminal ou apertarmos “CTRL + C” ou “CTRL + D” por exemplo o nosso container morre, para prosseguirmos vamos sair do container porém mantendo-o em execução, com a seguinte instrução:</p><p>Pressione: CTRL + p + q</p><h4>docker --priviledged</h4><pre>➜ docker exec -ti --privileged b9efbbde665f /bin/bash<br>root@92a1732c0ac8:/# apt install qemu qemu-kvm  virt-manager<br><br><br>root@b9efbbde665f:~/fs2# qemu-system-x86_64 -kernel $DIR_AUX/bzImage -m 256m -append &#39;root=/dev/vda console=ttyS0&#39;  -nographic...<br>....<br>[    8.963417] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0)<br>[    8.976363] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 5.2.6 #1<br>[    8.982909] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014<br>[    8.991685] Call Trace:<br>[    8.995851]  dump_stack+0x46/0x5b<br>[    8.998668]  panic+0xf3/0x2b8<br>[    9.003950]  mount_block_root+0x184/0x248<br>[    9.018247]  ? set_debug_rodata+0xc/0xc<br>[    9.021430]  mount_root+0x121/0x13f<br>[    9.024162]  prepare_namespace+0x130/0x166<br>[    9.025518]  kernel_init_freeable+0x1ed/0x1fa<br>[    9.027940]  ? rest_init+0xb0/0xb0<br>[    9.029944]  kernel_init+0x5/0x100<br>[    9.033349]  ret_from_fork+0x35/0x40<br>[    9.046244] Kernel Offset: 0x21800000 from 0xffffffff81000000 (relocation range: 0xffffffff80000000-0xffffffffbfffffff)<br>[    9.055677] ---[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0) ]---</pre><p><strong>ctr + a</strong> depois <strong>x </strong>para sair</p><p>Deu certo? Se não, por que?</p><h3>Testando o kernel (2)</h3><p>vamos criar o sistema de arquivos</p><pre>root@b9efbbde665f:~/fs2# mkdir ~/fs2<br>root@b9efbbde665f:~/fs2# DIR_FS2=~/fs2<br>root@b9efbbde665f:~/fs2# cp $DIR_AUX/System.map ~/fs2</pre><p>Crie o arquivo init.c em $DIR_AUX com o conteúdo a seguir:</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br><br>void main(void){<br>	char cmd[200];<br> 	while(1){<br>		printf(&quot;root# &quot;);<br>		gets(cmd);<br>	}<br>}<br><br># Compile o programa com o comando: <br>root@b9efbbde665f:~/fs2# cd $DIR_AUX<br>root@b9efbbde665f:~/aux# $ gcc -o init init.c<br>root@b9efbbde665f:~/aux# ls<br>System.map  bzImage  init  init.c  ramfs1.gz</pre><p>Copie o executável para DIR_FS2</p><pre>$ cp ~/init $DIR_FS2</pre><p>Gere o <strong>ramfs</strong></p><pre>cd $DIR_FS2<br>find . | cpio -o -H newc | gzip &gt; $DIR_AUX/ramfs1.gz</pre><pre>root@b9efbbde665f:~/aux# qemu-system-x86_64 -kernel $DIR_AUX/bzImage -m 256m -append &#39;root=/dev/vda console=ttyS0&#39;  -nographic  -initrd $DIR_AUX/ramfs1.gz<br>[   10.841209] platform regulatory.0: Direct firmware load for regulatory.db failed with error -2<br>[   10.844213] ALSA device list:<br>[   10.845365]   No soundcards found.<br>[   10.849082] cfg80211: failed to load regulatory.db<br>[   10.958594] Freeing unused kernel image memory: 1312K<br>[   10.971184] Write protecting the kernel read-only data: 20480k<br>[   11.003807] Freeing unused kernel image memory: 2008K<br>[   11.054375] Freeing unused kernel image memory: 1024K<br>[   11.113212] Run /init as init process<br>[   11.223908] Failed to execute /init (error -2)<br>[   11.259439] Run /sbin/init as init process<br>[   11.294942] Run /etc/init as init process<br>[   11.392107] Run /bin/init as init process<br>[   11.423360] Run /bin/sh as init process<br>[   11.449082] Kernel panic - not syncing: No working init found.  Try passing init= option to kernel. See Linux Documentation/admin-guide/init.rst for guidance.<br>[   11.468945] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 5.2.6 #1<br>[   11.476599] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014<br>[   11.482582] Call Trace:<br>[   11.492254]  dump_stack+0x46/0x5b<br>[   11.514472]  ? csum_partial_copy_generic+0x3090/0x30a0<br>[   11.525650]  panic+0xf3/0x2b8<br>[   11.529767]  ? __do_execve_file.isra.44+0x9a/0x8b0<br>[   11.547421]  ? __do_execve_file.isra.44+0x9a/0x8b0<br>[   11.552762]  ? rest_init+0xb0/0xb0<br>[   11.555638]  kernel_init+0xe6/0x100<br>[   11.560657]  ret_from_fork+0x35/0x40<br>[   11.568041] Kernel Offset: 0x16a00000 from 0xffffffff81000000 (relocation range: 0xffffffff80000000-0xffffffffbfffffff)<br>[   11.606749] ---[ end Kernel panic - not syncing: No working init found.  Try passing init= option to kernel. See Linux Documentation/admin-guide/init.rst for guidance. ]---</pre><p>Deu certo? Se não, por que?</p><p>Testando o kernel (2)</p><p>Compile novamente o programa com o comando para que o executável não possua ligação com bibliotecas dinâmicas:</p><pre>$ cd $DIR_AUX<br>$ gcc -o init init.c --static<br>Copie o executável para $DIR_FS2 <br>$ cp init $DIR_FS2<br>Gere o ramfs <br>cd $DIR_FS2<br>find . | cpio -o -H newc | gzip &gt; $DIR_AUX/ramfs2.gz<br><br>root@b9efbbde665f:~/fs2# qemu-system-x86_64 -kernel $DIR_AUX/bzImage -m 256m -append &#39;root=/dev/vda console=ttyS0&#39;  -nographic  -initrd $DIR_AUX/ramfs2.gz<br>...<br>[   11.360473] e1000e: Intel(R) PRO/1000 Network Driver - 3.2.6-k<br>[   11.388745] e1000e: Copyright(c) 1999 - 2015 Intel Corporation.<br>[   11.431163] sky2: driver version 1.30<br>[   11.467064] ehci_hcd: USB 2.0 &#39;Enhanced&#39; Host Controller (EHCI) Driver<br>[   11.480564] ehci-pci: EHCI PCI platform driver<br>[   11.525735] ohci_hcd: USB 1.1 &#39;Open&#39; Host Controller (OHCI) Driver<br>[   11.585770] ohci-pci: OHCI PCI platform driver<br>[   11.628669] uhci_hcd: USB Universal Host Controller Interface driver<br>[   11.677254] usbcore: registered new interface driver usblp<br>[   11.710945] usbcore: registered new interface driver usb-storage<br>[   11.744283] i8042: PNP: PS/2 Controller [PNP0303:KBD,PNP0f13:MOU] at 0x60,0x64 irq 1,12<br>[   11.773629] serio: i8042 KBD port at 0x60,0x64 irq 1<br>[   11.822874] serio: i8042 AUX port at 0x60,0x64 irq 12<br>[   11.884913] rtc_cmos 00:00: RTC can wake from S4<br>[   11.905764] input: AT Translated Set 2 keyboard as /devices/platform/i8042/serio0/input/input1<br>[   11.942800] rtc_cmos 00:00: registered as rtc0<br>[   11.978055] rtc_cmos 00:00: alarms up to one day, y3k, 114 bytes nvram, hpet irqs<br>[   12.038450] device-mapper: ioctl: 4.40.0-ioctl (2019-01-18) initialised: dm-devel@redhat.com<br>[   12.077327] hidraw: raw HID events driver (C) Jiri Kosina<br>[   12.100025] usbcore: registered new interface driver usbhid<br>[   12.123317] usbhid: USB HID core driver<br>[   12.173927] Initializing XFRM netlink socket<br>[   12.196602] NET: Registered protocol family 10<br>[   12.260030] Segment Routing with IPv6<br>[   12.311247] sit: IPv6, IPv4 and MPLS over IPv4 tunneling driver<br>[   12.371189] NET: Registered protocol family 17<br>[   12.400406] Key type dns_resolver registered<br>[   12.429124] mce: Using 10 MCE banks<br>[   12.450145] sched_clock: Marking stable (12427333324, 22227655)-&gt;(16745051824, -4295490845)<br>[   12.493213] registered taskstats version 1<br>[   12.507846] Loading compiled-in X.509 certificates<br>[   12.539756] PM:   Magic number: 15:790:82<br>[   12.562430] printk: console [netcon0] enabled<br>[   12.584362] netconsole: network logging started<br>[   12.618125] cfg80211: Loading compiled-in X.509 certificates for regulatory database<br>[   12.665620] input: ImExPS/2 Generic Explorer Mouse as /devices/platform/i8042/serio1/input/input3<br>[   12.737722] cfg80211: Loaded X.509 cert &#39;sforshee: 00b28ddf47aef9cea7&#39;<br>[   12.772653] platform regulatory.0: Direct firmware load for regulatory.db failed with error -2<br>[   12.817059] ALSA device list:<br>[   12.847152]   No soundcards found.<br>[   12.880669] cfg80211: failed to load regulatory.db<br>[   13.023022] Freeing unused kernel image memory: 1312K<br>[   13.055775] Write protecting the kernel read-only data: 20480k<br>[   13.104955] Freeing unused kernel image memory: 2008K<br>[   13.153901] Freeing unused kernel image memory: 1024K<br>[   13.208347] Run /init as init process<br>root#</pre><h3>busy box</h3><pre>root@b9efbbde665f:~# wget https://busybox.net/downloads/busybox-1.31.0.tar.bz2<br>--2019-08-09 15:10:23--  https://busybox.net/downloads/busybox-1.31.0.tar.bz2<br>Resolving busybox.net (busybox.net)... 140.211.167.122<br>Connecting to busybox.net (busybox.net)|140.211.167.122|:443... connected.<br>HTTP request sent, awaiting response... 200 OK<br>Length: 2427873 (2.3M) [application/x-bzip2]<br>Saving to: &#39;busybox-1.31.0.tar.bz2&#39;<br><br>busybox-1.31.0.tar.bz2                                      100%[=========================================================================================================================================&gt;]   2.31M   484KB/s    in 5.1s<br><br>2019-08-09 15:10:29 (466 KB/s) - &#39;busybox-1.31.0.tar.bz2&#39; saved [2427873/2427873]<br><br>root@b9efbbde665f:~# tar xvfj busybox-1.31.0.tar.bz2<br>root@b9efbbde665f:~# rm busybox-1.31.0.tar.bz2<br>root@b9efbbde665f:~# ls<br>aux  busybox-1.31.0  fs1  fs2  linux-5.2.6</pre><p>Crie uma pasta para instalar o sistema de arquivo que será gerado pelo Busybox:</p><pre>$ mkdir ~/fs3<br>DIR_FS3=~/fs3<br>root@b9efbbde665f:~# cp $DIR_AUX/System.map $DIR_FS3</pre><p>Entre na pasta busybox-1.31.0 (onde descompactou o busybox) e digite os comandos a seguir. Na tela de configuração que aparece após o comando “make menuconfig” entre no menu &quot;Settings&quot; e selecione/ative a opção &quot;Build static binary (no shared libs).</p><pre>$ cd busybox-1.31.0<br>$ make menuconfig<br>$ make CONFIG_PREFIX=$DIR_FS3<br>$ make CONFIG_PREFIX=$DIR_FS3 install<br>...<br>  /root/root/fs3//usr/sbin/readprofile -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/remove-shell -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/rtcwake -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/sendmail -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/setfont -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/setlogcons -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/svlogd -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/telnetd -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/tftpd -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/ubiattach -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/ubidetach -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/ubimkvol -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/ubirename -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/ubirmvol -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/ubirsvol -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/ubiupdatevol -&gt; ../../bin/busybox<br>  /root/root/fs3//usr/sbin/udhcpd -&gt; ../../bin/busybox<br><br><br>--------------------------------------------------<br>You will probably need to make your busybox binary<br>setuid root to ensure all configured applets will<br>work properly.<br>--------------------------------------------------<br><br>root@b9efbbde665f:~/fs3# cd $DIR_FS3<br>root@b9efbbde665f:~/fs3# l<br>System.map  bin/  linuxrc@  sbin/  usr/<br>root@b9efbbde665f:~/fs3# cd bin/<br>root@b9efbbde665f:~/fs3/bin# l<br>arch@     chattr@  cp@        df@             ed@       fgrep@   gzip@      ipcalc@    linux64@  lzop@      more@        mv@       ping@           pwd@        rmdir@         setarch@    stat@  touch@   vi@<br>ash@      chgrp@   cpio@      dmesg@          egrep@    fsync@   hostname@  kbd_mode@  ln@       makemime@  mount@       netstat@  ping6@          reformime@  rpm@           setpriv@    stty@  true@    watch@<br>base64@   chmod@   cttyhack@  dnsdomainname@  false@    getopt@  hush@      kill@      login@    mkdir@     mountpoint@  nice@     pipe_progress@  resume@     run-parts@     setserial@  su@    umount@  zcat@<br>busybox*  chown@   date@      dumpkmap@       fatattr@  grep@    ionice@    link@      ls@       mknod@     mpstat@      nuke@     printenv@       rev@        scriptreplay@  sh@         sync@  uname@<br>cat@      conspy@  dd@        echo@           fdflush@  gunzip@  iostat@    linux32@   lsattr@   mktemp@    mt@          pidof@    ps@             rm@         sed@           sleep@      tar@   usleep@<br>root@b9efbbde665f:~/fs3/bin# cd ..<br>root@b9efbbde665f:~/fs3# ls<br>System.map  bin  linuxrc  sbin  usr<br>root@b9efbbde665f:~/fs3# chmod u+s bin/busybox<br>root@b9efbbde665f:~/fs3# ln -s bin/busybox init<br>root@b9efbbde665f:~/fs3# ls<br>System.map  bin  init  linuxrc  sbin  usr <br>root@b9efbbde665f:~/fs3# chown -R root:root $DIR_FS3/*</pre><p>Será necessário criar alguns arquivos no novo filesystem, como arquivos de dispositivo e um script de inicialização que é chamado pelo processo init. Para isso, digite os comandos a seguir.</p><pre>root@b9efbbde665f:~/busybox-1.31.0# cd $DIR_FS3<br>root@b9efbbde665f:~/fs3# ls<br>System.map<br>root@b9efbbde665f:~/fs3# mkdir dev etc lib proc root sys tmp var boot<br>root@b9efbbde665f:~/fs3# cd etc/<br>root@b9efbbde665f:~/fs3/etc# ls<br>root@b9efbbde665f:~/fs3/etc# mkdir init.d<br>root@b9efbbde665f:~/fs3/etc# echo &quot;root::0:0:root:/root:/bin/sh&quot; &gt; passwd<br>root@b9efbbde665f:~/fs3/etc# echo &quot;root:x:0:&quot; &gt; group<br>root@b9efbbde665f:~/fs3/etc# cd init.d/<br>root@b9efbbde665f:~/fs3/etc/init.d# nano rcS<br>root@b9efbbde665f:~/fs3/etc/init.d# cat rcS<br>mount -t proc proc /proc<br>mount -t sysfs sys /sys<br>export PS1=&#39;\u@\h:\w# &#39;<br>root@b9efbbde665f:~/fs3/etc/init.d# chmod 755 rcS<br>root@b9efbbde665f:~/fs3/etc/init.d# cd ../../dev/<br>root@b9efbbde665f:~/fs3/dev#  mknod console c 5 1<br>root@b9efbbde665f:~/fs3/dev# mknod null c 3 1<br>root@b9efbbde665f:~/fs3/dev# mknod tty0 c 4 0<br>root@b9efbbde665f:~/fs3/dev# mknod tty1 c 4 1<br>root@b9efbbde665f:~/fs3/dev# mknod tty2 c 4 2<br>root@b9efbbde665f:~/fs3/dev# mknod tty3 c 4 3<br>root@b9efbbde665f:~/fs3/dev#  mknod tty4 c 4 4<br>root@b9efbbde665f:~/fs3/dev# cd $DIR_FS3<br>root@b9efbbde665f:~/fs3# cd $DIR_FS3<br>root@b9efbbde665f:~/fs3# ls<br>System.map  boot  dev  etc  lib  proc  root  sys  tmp  var<br>root@b9efbbde665f:~/fs3# find . | cpio -o -H newc | gzip &gt; $DIR_AUX/ramfs3.gz<br>8014 blocks<br>root@b9efbbde665f:~/fs3# ls<br>System.map  boot  dev  etc  lib  proc  root  sys  tmp  var<br>root@b9efbbde665f:~/fs3# cd ..<br>root@b9efbbde665f:~# ls<br>aux  busybox-1.31.0  fs1  fs2  fs3  linux-5.2.6  root<br>root@b9efbbde665f:~# qemu-system-x86_64 -kernel $DIR_AUX/bzImage -m 256m -append &#39;root=/dev/vda console=ttyS0&#39;  -nographic  -initrd $DIR_AUX/ramfs3.gz<br>...<br><br><br><br>root@b9efbbde665f:~/fs3# tree<br>.<br>|-- System.map<br>|-- boot<br>|-- dev<br>|   |-- console<br>|   |-- null<br>|   |-- tty0<br>|   |-- tty1<br>|   |-- tty2<br>|   |-- tty3<br>|   `-- tty4<br>|-- etc<br>|   |-- group<br>|   |-- init.d<br>|   |   `-- rcS<br>|   `-- passwd<br>|-- lib<br>|-- proc<br>|-- root<br>|-- sys<br>|-- tmp<br>`-- var</pre><ul><li><a href="https://github.com/surajx/qemu-arm-linux/wiki/Compile-Linux,-BusyBox-for-ARM-and-load-it-using-QEMU">surajx/qemu-arm-linux</a></li><li><a href="https://churrops.io/2017/04/21/docker-p02-brincando-com-imagem-centos-e-subindo-um-container-nginx/">[Docker] P02 - Brincando com imagem centos e subindo um container NGINX</a></li><li><a href="https://www.itzgeek.com/how-tos/linux/centos-how-tos/install-kvm-qemu-on-centos-7-rhel-7.html">Install KVM (QEMU) on CentOS 7 / RHEL 7 - ITzGeek</a></li><li><a href="https://www.qemu.org/download/">Download QEMU</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27e2982dfc68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gerando relatórios com Latex + Django]]></title>
            <link>https://medium.com/@_gabiCavalcante/gerando-relat%C3%B3rios-com-latex-django-70581af6cb20?source=rss-60e12fcdb956------2</link>
            <guid isPermaLink="false">https://medium.com/p/70581af6cb20</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[latex]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Gabi Cavalcante]]></dc:creator>
            <pubDate>Mon, 30 Sep 2019 01:18:05 GMT</pubDate>
            <atom:updated>2019-09-30T01:18:05.458Z</atom:updated>
            <content:encoded><![CDATA[<p>Quando comecei no meu novo emprego a primeira tarefa que me deixaram responsável foi: <strong>relatórios</strong>. Eu não conhecia o sistema, e a principio achei ótimo começar por ai, já que para mexer nos relatórios eu precisaria fuçar o sistema muito bem.</p><p>Mas quando abri os arquivos que geravam os documentos, me deparei com algo não muito agradável. No arquivo python eles descreviam as exatas posições de cada item do PDF (em centímetros). Eles precisavam descrever quando cm ficaria uma coluna, e depois de quantos cm ficaria a próxima coluna… e quantos cm abaixo ficaria a linha seguinte. E assim uma tarefa que já seria demorada por que eu não tinha conhecimento do sistema, demorava muito mais por que eu tinha que ficar testando se acertei a distância de cada coisa.</p><p>Foi ai que veio a ideia de usar Latex para gerar os PDFs. Eu já havia trabalhado com ele para produção de artigos e trabalhos acadêmicos, me parecia perfeito para a situação.</p><p>Usei o <a href="https://github.com/weinbusch/django-tex"><strong>django-tex</strong></a>, que é um simples app Django para renderizar templates LaTex e compilar eles para PDF. O <strong>django-tex </strong>requer apenas a instalação local do LaTex e o uso de <strong>jinja2</strong> para fazer os templates.</p><p>No nosso caso, fizemos um <a href="https://github.com/gabicavalcante/django-tex">fork</a> do projeto com algumas melhorias, como caracteres para serem “escapados” e alguns filtros para os templates.</p><h3>Como usar</h3><ol><li>Adicionar <strong>django_tex</strong> to your INSTALLED_APPS setting:</li></ol><pre>INSTALLED_APPS = [<br>    ...<br>    &#39;django_tex&#39;,<br>]</pre><p>2. Configure o settings.py:</p><pre>TEMPLATES = [<br>    {<br>        &#39;NAME&#39;: &#39;tex&#39;,<br>        &#39;BACKEND&#39;: &#39;django_tex.engine.TeXEngine&#39;, <br>        &#39;APP_DIRS&#39;: True,<br>        &#39;DIRS&#39;: [<br>            &#39;%s/templates&#39; % ROOT_PATH        <br>        ],    <br>    },<br>]</pre><p>3. Crie um template teste.tex LaTeX no seu diretório de templates:</p><pre>\documentclass{article}</pre><pre>\begin{document}</pre><pre>\section{ {{- title -}} }</pre><pre>\end{document}</pre><ol><li>Use compile_template_to_pdf no seu código para gerar um objeto binário com o arquivo PDF.</li></ol><pre>from django_tex.core import compile_template_to_pdf</pre><pre>template_name = &#39;teste.tex&#39;<br>context = {&#39;title&#39;: &#39;Arquivo PDF Teste&#39;}<br>PDF = compile_template_to_pdf(template_name, context)</pre><p>Ou use render_to_pdf para gerar umHTTPResponse contendo o PDF</p><pre>from django_tex.shortcuts import render_to_pdf</pre><pre>def view(request):<br>    template_name = &#39;teste.tex&#39;<br>    context = {&#39;title&#39;: &#39;Arquivo PDF Teste&#39;}<br>    return render_to_pdf(request, template_name, context, filename=&#39;teste.pdf&#39;)</pre><p>O interpreter default do LaTeX no projeto é o lualatex, mas você pode mudar isso no settings.py do projeto colocando o LATEX_INTERPRETER, por exemplo: LATEX_INTERPRETER = &#39;pdflatex&#39;. Para funcionar corretamente o interpretador precisa estar instalado na máquina.</p><h3>é isso pessoal</h3><p>Com isso conseguimos gerar relatórios de forma mais simples, mais fácil de manter, com uma curva de aprendizagem menor caso outro desenvolvedor precise assumir o projeto, e o tempo consumido parar gerar os arquivos também diminuiu!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70581af6cb20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SimpleSamlPHP como IdP]]></title>
            <link>https://medium.com/@_gabiCavalcante/simplesamlphp-como-idp-ae19a38a2d81?source=rss-60e12fcdb956------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae19a38a2d81</guid>
            <category><![CDATA[federação]]></category>
            <category><![CDATA[dev]]></category>
            <category><![CDATA[simplesamlphp]]></category>
            <dc:creator><![CDATA[Gabi Cavalcante]]></dc:creator>
            <pubDate>Tue, 25 Apr 2017 02:06:37 GMT</pubDate>
            <atom:updated>2017-04-25T17:26:25.027Z</atom:updated>
            <content:encoded><![CDATA[<p>Durante um estudo sobre Autenticaçao Federada, fiquei responsável por realizar alguns testes usando o <a href="https://simplesamlphp.org/"><strong>SimpleSamlPHP</strong></a> como um <strong>IdP</strong>. O objetivo seria testar o Keystone com Federação, usamos o IdP SimpleSamlPHP (uma ferramenta escrita em PHP que lida com questões relacionadas a autenticação).</p><h3>Instalação e configuração</h3><p><strong>OBS</strong>: O SO do ambiente que fiz os testes é o <em>Ubuntu 16</em>.</p><p>Antes de começar com a instalação, tenha certeza que tudo esta atualizado.</p><pre>$ sudo apt-get update <br><br>$ sudo apt-get upgrade</pre><p>Se você estiver usando o Ubuntu 16.04, vai notar que a versao padrao do php sera a 7.</p><pre>$ sudo apt-get install php7.0</pre><p>Precisei instalar alguns pacotes especificos para que a instalaçao e configuração ocorrecem normalmente:</p><pre>$ sudo apt-get install apache2<br>$ sudo apt-get install php-xml<br>$ sudo apt-get install php5-sqlite<br>$ sudo apt-get install php5-curl<br>$ sudo apt install zip unzip php7.0-zip<br>$ sudo apt-get install libapache2-mod-php</pre><p>Baixe o repositorio do simplesamlphp (o diretório do simplesamlphp nos meus testes foi /var):</p><pre># cd /var/<br># git clone <a href="https://github.com/simplesamlphp/simplesamlphp.git">https://github.com/simplesamlphp/simplesamlphp.git</a> simplesamlphp</pre><p>Copie os templetes de configuração e matadata:</p><pre># cd simplesamlphp</pre><pre># cp -r config-templates/*.php config/</pre><pre># cp -r metadata-templates/*.php metadata/</pre><p>Para ajudar na instalação de algumas dependências necessarias, o simplesamlphp vai ter um arquivo composer. O Composer é um gerenciador de dependências PHP, para fazer o download e instalar <a href="https://getcomposer.org/download/">acesse</a>. Por fim execute:</p><pre>php composer.phar install</pre><p>Ou execute o comando:</p><pre>$ sudo apt-get install composer</pre><p>E dentro do diretório do simplesamlphp:</p><pre>$ composer install</pre><p><strong>OBS</strong>: caso seja negado o acesso a pasta /var/simplesamlphp/, o que é muito provável, execute<strong> sudo chmod -R 777 /var/simplesamlphp/</strong>.</p><p>Adicione um link do diretorio do simplesamlphp para o diretório /var/www/html/(para saber mais sobre o comando ln, use o comando man ls no terminal):</p><pre>$ cd /var/www/html/</pre><pre>$ ln -s /var/simplesamlphp/www simplesaml</pre><p>O diretorio que precisa ser acessivel é o simplesamlphp/www. Você pode expôr esse diretório de varias formas, uma das maneiras é a que vamos usar nesse tutorial (criando um link entre o diretório do simplesamlphp e o diretorio /var/www/html), mas você também pode editar o arquivo de configuraçao do Apache e adicionar uma virtual host, como na documentaçao do <a href="https://simplesamlphp.org/docs/stable/simplesamlphp-install#section_6">simplesamlphp</a>.</p><p>Vamos passar agora para a configuração de algumas informações no arquivo config/config.php, como a senha do usuário admin:</p><pre>&#39;auth.adminpassword&#39;        =&gt; &#39;setnewpasswordhere&#39;,</pre><p>Mude também o valor de SecretSalt (uma string aleatória usada em algumas partes do SimpleSamlPhp para gerar hash seguras). Caso você nao mude o valor default, o SimpleSaml dará um erro. Talvez ajude usar o comando a seguir para gerar a string:</p><pre>$ tr -c -d ‘0123456789abcdefghijklmnopqrstuvwxyz’ &lt;/dev/urandom | dd bs=32 count=1 2&gt;/dev/null;echo</pre><p>Restart o apache:</p><pre>$ sudo service apache2 restart</pre><p>Você deve conseguir acessar o simplesamlphp acessando uma url como: <a href="http://10.7.49.61/simplesaml">http://10.7.49.61/simplesaml</a>.</p><h3>Criando IdP</h3><ul><li><em>Libera a funcionalidade IdP</em></li></ul><p>O primeiro passo é liberar a funcionalidade IdP, editando o arquivo config/config.php. As opções enable.saml20-idp e enable.shib13-idp, controlam tanto o SAML 2.0 quanto o Shibboleth 1.3. No nosso exemplo, basta liberar a opção enable.saml20-idp.</p><p><strong>‘enable.saml20-idp’ =&gt; true</strong></p><ul><li><em>Configure o modo de autenticaçao</em></li></ul><p>O proximo passo é configurar a forma como o usuário se autentica no IdP. Existem varios módulos no diretorio modules/, o que escolhemos foi o <strong>exampleauth:UserPass</strong> (autenticar o usuário usando uma lista de <em>usernames</em> e <em>passwords</em>).</p><pre>$ touch modules/exampleauth/enable</pre><p>Agora devemos criar uma fonte de autenticaçao — <em>authentication source</em> -, um modulo de autenticaçao com um conjunto de configuraçoes. Cada fonte de autenticaçao tem um nome, que é usado para referenciar uma configuração especifica no IdP. Essa configuraçao para a fonte de autenticação pode ser encontrada no arquivo config/authsources.php.</p><p>No nosso exemplo, o conteudo desse arquivo sera:</p><pre>&lt;?php<br>$config = array(<br>    // This is a authentication source which handles admin authentication.<br>    &#39;admin&#39; =&gt; array(<br>        // The default is to use core:AdminPassword, but it can be replaced with<br>        // any authentication source.</pre><pre>        &#39;core:AdminPassword&#39;,<br>    ),</pre><pre>    &#39;example-userpass&#39; =&gt; array(<br>        &#39;exampleauth:UserPass&#39;,<br>        &#39;admin:adminpass&#39; =&gt; array(<br>            &#39;uid&#39; =&gt; array(&#39;admin&#39;),<br>            &#39;mail&#39; =&gt; &#39;admin@email.com&#39;,<br>            &#39;first_name&#39; =&gt; &#39;User&#39;,<br>            &#39;last_name&#39; =&gt; &#39;Admin&#39;<br>        ),<br>        &#39;developer:developerpass&#39; =&gt; array(<br>            &#39;uid&#39; =&gt; array(&#39;developer&#39;),<br>            &#39;mail&#39; =&gt; &#39;developer@email.com&#39;,<br>            &#39;first_name&#39; =&gt; &#39;User&#39;,<br>            &#39;last_name&#39; =&gt; &#39;Developer&#39;<br>        ),<br>    ),<br>);</pre><p>Essa configuraçao cria dois usuarios: <em>admin</em> e <em>developer</em>, com passwords <em>adminpass</em> e <em>developerpass</em>. Os atributos para cada usuário é configurado no array referenciado por index. Por exemplo, os atributos do usuário admin:</p><pre>array(<br>    &#39;exampleauth:UserPass&#39;,<br>    &#39;admin:adminpass&#39; =&gt; array(<br>        &#39;uid&#39; =&gt; array(&#39;admin&#39;),<br>        &#39;mail&#39; =&gt; &#39;admin@email.com&#39;,<br>        &#39;first_name&#39; =&gt; &#39;User&#39;,<br>        &#39;last_name&#39; =&gt; &#39;Admin&#39;<br>    ),</pre><ul><li><em>Configurando o IdP</em></li></ul><p>O IdP é configurado por um arquivo metadada armazenado em metadata/saml20-idp-hosted.php. O conteúdo da configuração para o SAML 2.0 IdP seria:</p><pre>&lt;?php<br>$metadata[&#39;__DYNAMIC:1__&#39;] = array(<br>    <em>/*<br>     * The hostname for this IdP. This makes it possible to run multiple<br>     * IdPs from the same configuration. &#39;__DEFAULT__&#39; means that this one<br>     * should be used by default.<br>     */</em><br>    &#39;host&#39; =&gt; &#39;__DEFAULT__&#39;,</pre><pre>    <em>/*<br>     * The private key and certificate to use when signing responses.<br>     * These are stored in the cert-directory.<br>     */</em><br>    &#39;privatekey&#39; =&gt; &#39;server.pem&#39;,<br>    &#39;certificate&#39; =&gt; &#39;server.crt&#39;,</pre><pre>    <em>/*<br>     * The authentication source which should be used to authenticate the<br>     * user. This must match one of the entries in config/authsources.php.<br>     */</em><br>    &#39;auth&#39; =&gt; &#39;example-userpass&#39;,<br>);</pre><ul><li><em>Criando self signed certificate</em></li></ul><p>O SimpleSAML precisa de um certificado para as mensagens SAML. O diretório onde essas informações sao armazenadas, pode ser encontrado no arquivo de configuração (config/config.php).</p><pre>&#39;certdir&#39; =&gt; &#39;cert/&#39;,</pre><p>Para gerar uma <em>private key</em> e um certificado, execute o comando no diretório indicado no arquivo de configuraçao:</p><pre>$ openssl req -new -x509 -days 3652 -nodes -out server.crt -keyout server.pem</pre><h3>Testando seu IdP</h3><p>A maneira mais simples de testar seu IdP é acessando a pagina do SimpleSamlPhP. Na aba <em>Autenticação</em>, você verá um link para testar as fontes de autenticação configuradas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1mrfYmrzZYF5yjoZ2jpRlA.png" /></figure><p>Uma das opções (dependendo de como seu arquivo esteja configurado, pode ser a única opção), você terá <em>example-userpass</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEXY7F8wB_wxzRtmGv4zAw.png" /></figure><p>Clicando na <em>authentication source</em> que configuramos, uma tela de login aparecerá. Utilize os dados de um dos usuários que você criou no arquivo config/authsources.php para logar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXwMYMyWPl5SnYrvZ5vhNQ.png" /></figure><p>Por fim, o IdP retorna os atributos do usuário logado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uefSYhfxEdBvdW2N0PwMrA.png" /></figure><p>Uma outra maneira de testar seu IdP é criando um <a href="https://simplesamlphp.org/docs/1.5/simplesamlphp-sp">SP</a> com o próprio SimpleSamlPHP, e associando ambos.</p><h4>Fonte:</h4><p>[1] <a href="http://developer.okta.com/code/php/simplesamlphp#notes-for-installing-simplesamlphp-on-mac-os-x">http://developer.okta.com/code/php/simplesamlphp#notes-for-installing-simplesamlphp-on-mac-os-x</a></p><p>[2] <a href="https://simplesamlphp.org/docs/1.5/simplesamlphp-idp">https://simplesamlphp.org/docs/1.5/simplesamlphp-idp</a></p><p>[3] <a href="https://www.helloitsliam.com/2014/12/23/install-configure-and-test-simplesamlphp-for-authentication-testing/">https://www.helloitsliam.com/2014/12/23/install-configure-and-test-simplesamlphp-for-authentication-testing/</a></p><p>[4] <a href="https://www.howtoforge.com/how-to-setup-single-sign-on-with-otp-using-simplesaml-php-and-privacyidea">https://www.howtoforge.com/how-to-setup-single-sign-on-with-otp-using-simplesaml-php-and-privacyidea</a></p><p>[5] <a href="http://www.worldgoneweb.com/2013/installing-simplesamlphp-and-use-it-as-sp-and-idp-for-development-env-only/">http://www.worldgoneweb.com/2013/installing-simplesamlphp-and-use-it-as-sp-and-idp-for-development-env-only/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae19a38a2d81" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>