<?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 Otavio H. P. Valadares on Medium]]></title>
        <description><![CDATA[Stories by Otavio H. P. Valadares on Medium]]></description>
        <link>https://medium.com/@valadaresotavio?source=rss-91cf42940d67------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*C7ZHGAA29oWpeIaEiw3w6A.jpeg</url>
            <title>Stories by Otavio H. P. Valadares on Medium</title>
            <link>https://medium.com/@valadaresotavio?source=rss-91cf42940d67------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 00:12:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@valadaresotavio/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[Entendendo o Big O]]></title>
            <link>https://medium.com/@valadaresotavio/https-medium-com-otaviopvaladares-entendendo-o-big-o-9cb55297d2f8?source=rss-91cf42940d67------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cb55297d2f8</guid>
            <category><![CDATA[português]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[big-o]]></category>
            <dc:creator><![CDATA[Otavio H. P. Valadares]]></dc:creator>
            <pubDate>Sun, 16 Dec 2018 18:13:52 GMT</pubDate>
            <atom:updated>2018-12-16T19:46:00.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eg6uha5r6y_lF0YWNCWkZw.jpeg" /><figcaption>Don’t fear the Big O</figcaption></figure><p><em>Todos meus posts eu posto primeiro no meu blog pessoal em inglês onde este post foi postado em fevereiro. Caso tenha interesse pode me seguir no </em><a href="https://twitter.com/opvaladares"><em>twitter</em></a><em> e ficar sabendo quando posto coisa nova. Para ver o post original só clicar </em><a href="https://otaviovaladares.com/2018/02/08/big-o-notation/"><em>aqui</em></a><em>.</em></p><p><em>Big O</em> é uma famosa notação da ciência da computação, porém esse tópico ainda da medo em muitas pessoas (Deixando muitas pessoas assustadas como a pessoa da imagem). Nesse post eu vou explicar o que realmente é <em>Big O</em> e o que você realmente precisa saber.</p><p>Eu vou explicar o básico da notação <em>Big O</em> com exemplos escritos em Ruby.</p><blockquote><em>Gosto de escrever exemplos em Ruby, pois acho a linguagem mais fácil de ser lida por qualquer pessoa que já programe algo, e não gosto de pseudocode. Se você já tem conhecimento em Python ou Javascript acredito que não terá dificuldades.</em></blockquote><p><strong>Isso não pretende ser um guia completo de </strong><em>Big O</em><strong>, se você quer saber tudo sobre, no final do texto vou dar referências de como continuar seu estudo.</strong></p><h3><strong>1. Introdução</strong></h3><p><strong>Esse texto não é recomendado para</strong></p><ul><li>Pessoas com um conhecimento sólido de <em>*Big O*</em></li><li>Pessoas que querem saber tópicos avançados de <em>*Big O*</em></li></ul><p><strong>O que vai ser explicado nesse post</strong></p><ul><li>O que é <em>*Big O*</em></li><li>As notações mais comuns</li><li>Exemplos simples</li><li>Alguns Benchmarks</li></ul><p><strong>1.1 Primeiro de tudo, o que é Big O?</strong></p><p><em>Big O</em> é uma linguagem e métrica/notação (podemos dizer assim) que usamos quando falamos sobre growth rates e eficiência de algoritimos. Podem ser usados para descrever o comportamento de um algoritimo em termos de crescimento no numero de operações conforme o número de elementos aumenta, com essa técnica nós podemos ver como nosso algoritimo se comporta com muitos dados e operações.</p><p><em>Se você quiser, pode ler uma explicação longa e mais profunda </em><a href="http://(https//en.wikipedia.org/wiki/Big_O_notation)"><em>aqui</em></a><em>.</em></p><p><strong>1.2 Por que isso é tão importante? Eu nunca vou usar isso.</strong></p><p>Um monte de métodos e estrutura de dados de muitas linguagens de programação são descritos usando Big O, como por exemplo a busca binária que no ruby é chamada <em>Array#bsearch</em>.</p><p>Primeiro de tudo, se você sempre trabalha com pequenas quantidades de <em>data</em> e operações, provavelmente você nunca vai precisar usar isso muito a fundo. Porém é bom entender os conceitos básicos de algoritimos, pois você pode ajudar você a tomar boas decisões de design no futuro.</p><p>Hoje em dia estamos na era do <em>Big Data</em>, toneladas de informações e operações são realidades. Você vai provavelmente fazer algoritimos pensando na complexidade de tempo e espaço.</p><p>Também é legal entender pois muitos métodos da sua linguagem de programação favorita tem diferentes complexidades, com <em>Big O</em> você pode entender melhor cada um.</p><p><em>Também é importante lembrar que muitas big tech companys como Google, Facebook e Amazon fazem perguntas sobre Big O nas suas entrevistas, isso é tão frequente que o best seller </em><a href="https://www.amazon.com.br/Cracking-Coding-Interview-Programming-Questions/dp/0984782850"><em>Cracking The Code Interview da autora </em>Gayle McDowell</a><em> tem um tópico discutindo apenas isso.</em></p><h3><strong>2. Aprendendo</strong></h3><p><strong>2.1 Visualizando a complexidade</strong></p><p>Usando Big O nos temos um monte de possibilidades de notações, a lista mais comum de runtimes/notações é:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ebd6b7a7fce84d32a56b598c30ae6c9/href">https://medium.com/media/0ebd6b7a7fce84d32a56b598c30ae6c9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*qTpWaGrf3GpkpAs-GMQzGA.png" /></figure><p><strong>2.2 Time or Space?</strong></p><p>Você pode usar Big O para descrever tanto tempo quanto espaço, mas o que isso significa? Simples, um algoritimo que tem um runtime <em>O(N)</em> pode crescer o espaço usado a <em>O(N²)</em>.</p><p><strong>2.3 Tempo para o que?</strong></p><p>Estrutura de dados e algoritimos podem ter tempos diferentes para diferentes ações, por exemplo: Um array tem <em>O(1)</em> para acesso, porém é <em>O(N)</em> para procura (dependendendo de qual algoritimo você usar), tudo depende do escopo do seu código.</p><p>[Nesse site você pode ver a complexidade de cada um dos mais famoso algoritimos e estruturas de dados](http://bigocheatsheet.com/)</p><p><strong>2.4 <em>Big O</em>, <em>Big Omega</em>, <em>Big Theta</em>?</strong></p><p>Nesse post eu não vou falar sobre <em>Big Omega</em> e <em>Big Theta</em> por duas razões:</p><ul><li>Isso é um texto simples e eu não quero mergulhar fundo em conceitos mais avançados.</li><li>A industria tende a usar mais a notação <em>Big O, que já resolve a maioria dos casos.</em></li></ul><h3><strong>3. Mãos a massa</strong></h3><p><em>Para ver o post original em inglês só clicar </em><a href="https://otaviovaladares.com/2018/02/08/big-o-notation/"><em>aqui</em></a><em>.</em></p><p><strong>3.1 Apresentando o nosso problema</strong></p><p>Na sua vida você ja pensou que algumas ações do nosso dia demoram muito tempo para serem feitas, e que você pode fazer algumas coisas simples para reduzir o tempo perdido? Vamos usar um exemplo simples nesse texto, um dicionario, quanto tempo você precisa para achar uma palavra nele? Depende do jeito que você procurar.</p><blockquote>”A segunda edição do 20º Oxford English Dictionary tem 171.476 palavras em uso e 47,156 palavras obsoletas.”</blockquote><p>Isso é um monte de coisa certo? Vamos imaginar que nos estamos construindo um algoritimo para procurar por uma palavra.</p><p><strong>Code</strong></p><p><em>Para fins educacionais, todos exemplos vão usar um array de números, não strings</em></p><p>Vamos criar um array que iremos usar em todos exemplos, esse array vai ser nosso dicionario, mas no lugar de palavras ele vai ter numeros. A palavra <em>“zoo”</em> vai ser a última palavra do nosso dicionario o que no caso seria o numero 1000000. Como você pode ver a seguir:</p><pre>dictionary = []<br></pre><pre>0.upto(1000000) do |number|</pre><pre>  dictionary &lt;&lt; number</pre><pre>end</pre><p>Agora temos uma array com um milhão de numeros. Vamos assumir que esse array de numeros é o nosso dicionario e que a palavra de número 1000000 seria a palavra <em>“zoo”</em> que estamos procurando.</p><p><strong>3.1.1 Primeira Solução <em>O(N)</em></strong></p><p>Considerando que esse dicionario está em ordem alfabética, quanto tempo você vai demorar para achar a palavra <em>“zoo”</em> (our 1000000) se você for palavra por palavra?</p><p>Sim, para char a nossa última palavra nós vamos perder muito tempo, você vai precisar ler todas palavras. Esses cenários quando andamos por todas informações, usando <em>Big O</em> nos chamamos de <em>O(N)</em>, pois, o algoritimo vai demorar N tempo para achar a solução, onde N é o numero de palavras.</p><p><strong>Code</strong></p><p>Vamos assumir que vamos andar palavra por palavra até achar a palavra que estamos procurando:</p><pre>def o_n(dictionary)</pre><pre>  dictionary.each do |word|</pre><pre>    word if word == 1000000</pre><pre>  end</pre><pre>end<br></pre><pre>o_n(dictionary)</pre><p>Isso é bem comum e não é uma solução muito ruim, mas também não é boa. Em termos de dificuldade para entender também não é tão complexo, muitos exemplos de algoritimos <em>O(N)</em> no nosso dia a dia vem de algoritimos de loop em arrays.</p><p><strong>3.1.2 Segunda Solução<em> O(1)</em></strong></p><p><em>O(1)</em> é um algoritimo que independente do tamanho do input ele sempre vai demorar o mesmo tempo para executar, o tempo dele é constante, o maior exemplo dele sem duvidas é acessar um array, no caso do nosso exemplo do dicionario seria como se você já soubesse onde está a palavra:</p><pre>def o_one(dictionary)</pre><pre>  dictionary[1000000]</pre><pre>end<br></pre><pre>o_one(dictionary)</pre><p><em>O(1)</em> sempre é a melhor solução, e você provavelmente usa isso todos os dias, o uso mais comum é o tempo de acesso em um [<a href="https://en.wikipedia.org/wiki/Hash_function">Hash</a>].</p><p>Como muitas linguagens, Ruby já tem hash implementado.</p><p><strong>Code</strong></p><pre>hash = {</pre><pre>  color: “red”</pre><pre>}</pre><pre>hash[:color]</pre><pre># =&gt; “red”</pre><p><strong>3.1.3 Terceira Solução <em>O(log n)</em></strong></p><p>Algumas pessoas tem muita dificuldade em entender esse conceito de <em>O(log N)</em>, mas eu espero que com esse exemplo você possa entender.</p><p>Vamos assumir que você não sabe onde a palavra está localizada, mas você save que se procurar olhando palavra por palavra(<em>O(N)</em>) você vai demorar muito, o que você vai fazer? Você pode começar abrindo o dicionário em uma página aleatória e procurar se as palavras dessa página vem antes ou depois da palavra que você está procurando, se for depois, você abre em uma página depois e continua assim.. repetindo até achar a palavra que está procurando.</p><p>Se você já estudou algoritimos você sab que isso na computação é bem famoso na [<a href="https://en.wikipedia.org/wiki/Binary_search_algorithm">busca binária</a>] e ela também é o exemplo mais famoso de algoritimo <em>O(log n)</em>.</p><p>Vamos ver o código:</p><p><strong>Code</strong></p><p>Para esse exemplo eu vou usar uma simples implementação da busca binária (não recursiva).</p><pre>def binary_search(dictionary, number)</pre><pre>  length = dictionary.length — 1</pre><pre>  low = 0</pre><pre>  while low &lt;= length</pre><pre>    mid = (low + length) / 2</pre><pre>    return dictionary[mid] if dictionary[mid] == number</pre><pre>    if dictionary[mid] &lt; number</pre><pre>      low = mid + 1</pre><pre>    else</pre><pre>      length = mid — 1</pre><pre>    end</pre><pre>  end</pre><pre>  “Number/Word not found”</pre><pre>end<br></pre><pre>puts binary_search(dictionary, 1000000)</pre><p>Para indentificar um algoritimo que é <em>O(log n)</em> você pode seguir dois passos:</p><p>- O próximo elemento que o algoritimo vai performar uma ação é um de algumas possibilidades, e apenas um vai ser escolhido.</p><p>- Os elementos de cada ação performada são digitos de N</p><p><em>Você pode ver mais </em><a href="https://stackoverflow.com/questions/2307283/what-does-olog-n-mean-exactly"><em>aqui</em></a></p><p>A busca binária é um ótimo exemplo disso pois a cada tentativa é cortado pela metade o numero de elementos restantes.</p><p>Como muitas linguagens Ruby já tem a busca binária implementada na classe array, como <em>Array#bsearch</em></p><pre>array = [1,2,3,4,5,6,7,8,9,10]</pre><pre>array.bsearch {|x| x &gt;= 9 }</pre><pre># =&gt; 9</pre><p>Você pode ler mais <a href="http://ruby-doc.org/core-2.2.0/Array.html#method-i-bsearch"><em>aqui</em></a><em>.</em></p><p><a href="https://hackernoon.com/what-does-the-time-complexity-o-log-n-actually-mean-45f94bb5bfbf"><em>Se você quer entender o porque da notação se chamar O(log N) clica aqui</em></a><em>.</em></p><p><em>Se você acha que isso não é o suficiente em explicação, siga os links que eu passo como referencia, não vou entrar em tópicos de matemática pois isso se trata de um texto para iniciantes.</em></p><p><strong>3.1.4 Quarta Solução <em>O(N²)</em></strong></p><p>Imagina que você está procurando palavra por palavra igual no <em>*O(N)*</em> mas por alguma razão você precisa fazer sua busca de novo, isso é o <em>*O(N²)*</em>. Com esse exemplo aplicado ao caso do dicionário é dificil entender pois não faz muito sentido, mas no código é mais facil.</p><p>O trick é basicamente pensar que é passar duas vezes por todas informações presentes, basicamente um loop dentro de um loop, sendo assim seria <em>N*</em>N o que daria <em>O(N²)</em>.</p><p><strong>Code</strong></p><pre>def o_n2(dictionary)</pre><pre>  dictionary.each do |word|</pre><pre>    dictionary.each do |word2|</pre><pre>      word if word == 1000000</pre><pre>    end</pre><pre>  end</pre><pre>end<br></pre><pre>o_n2(dictionary)</pre><p>Não fique apavorado, isso é bem comum, especialmente quando estamos começando que fazemos muitas vezes o famoso <em>bubble sort</em> para ordernar um array, mas esse código não tem uma boa performace para grandes inputs. A melhor coisa a fazer é tentar reduzir ele a <em>O(log n)</em> que quase sempre da para fazer.</p><p><strong>3.1.5 Quinta Solução <em>O(n log n)</em></strong></p><p>Essa é a solução mais dificil para mim, e eu admito que perdi algumas horas procurando na internet porque as definições que achei não foram satisfatorias (E não tinha muitas respostas na internet).</p><p>A maneira mais simples que encontrei de explicar foi:</p><blockquote><em>O(n log n) é basicamente quando você roda N vezes uma ação que custa O(log n).</em></blockquote><p>Ok, isso é obvio, mas faz sentido. Vamos examinar:</p><p>Em uma arvore binária, inserir um novo nó a ela (em uma arvore balanceada) é <em>O(log n)</em>. Inserir uma lista de N elementos em uma arvore vai ser <em>O(n log n)</em>.</p><p>Muitas vezes algoritimos <em>O(n log n)</em> podem ser resultado da otimização de um algoritimo quadratico <em>N²</em>, o exemplo mais famoso desse tipo de algoritimo é o <em>merge sort</em>.</p><p>Para essa definição eu infelizmente não consegui encaixar na historia do dicionario nada. Eu definitivamente não consigo pensar em nada que iria fazer sentido na história do dicionaro.</p><p><em>Se você acha que isso não foi suficiente nas referencias você vai encontrar links para entender melhor.</em></p><p><strong>3.1.6 Sexta Solução <em>O(2^N)</em></strong></p><p><em>O(2^N)</em> é quando um algoritimo é exponencial, é uma definição complexa assim como <em>O(n log n)</em>. Esse tipo de problema é quando um numero de instruções crescem exponencialmente, é comum achar isso em algoritimos recursivos, ou em alguns algoritimos de busca.</p><p><em>Quando temos uma função recursiva que faz diversas chamadas, o runtime vai ser O(2^N).</em></p><p>Se você procurar na internet você provavelmente vai ver muitas pessoas falando que o algoritimo de fibonacci recursivo é um bom exemplo:</p><pre>def fibonacci(number)</pre><pre>  return number if number &lt;= 1</pre><pre>  fibonacci(number — 2) + fibonacci(number — 1)</pre><pre>end<br></pre><pre>puts fibonacci(10)</pre><p>Para achar um <em>O(2^N)</em> você pode começar seguindo uma regra:</p><p>- <em>O(2^N)</em> é um algoritimo que o crescimento dobra a cada adição no input. (Exponencial)</p><p>Para esse exemplo também não irá ter exemplo na história do dicionario, sorry.</p><p><strong>3.1.7 Sétima Solução <em>O(N!)</em></strong></p><p>A solução mais horrivel. Mas infelizmente não vou ter exemplo na história do dicionario também, e não quero pular de cabeça na parte matemática.</p><p><em>O(N!) é toda vez que você calcula todas permutações de um array de tamanho N.</em></p><p>O exeplo mais famoso dessa notação é resolver o problema do caixeiro viajante com brute-force(testando todas soluções possíveis).</p><p>(Um monte de sites como a wikpedia também usam esse exemplo).</p><p><strong>Code</strong></p><p>No Ruby temos um método que retorna todas permutações de um array.</p><pre>array = [1,2,3]</pre><pre>array.permutation(3).to_a</pre><pre># =&gt; [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]</pre><p>Isso é <em>O(N!)</em></p><h3><strong>4. Benchmarking</strong></h3><p><em>Para ver o post original em inglês só clicar </em><a href="https://otaviovaladares.com/2018/02/08/big-o-notation/"><em>aqui</em></a><em>.</em></p><p>Vamos examinar alguns benchmark de alguns exemplos discutindos e comprar, para entender melhor e ver que a notação realmente faz sentido.</p><p>Nessa seção vou usar os algoritimos dos exemplos anteriores e usar o modulo do Ruby <a href="http://ruby-doc.org/stdlib-2.0.0/libdoc/benchmark/rdoc/Benchmark.html"><em>Benchmark</em></a> para comprar os tempos de execução.</p><p><strong>4.1 <em>O(1)</em> vs <em>O(N)</em></strong></p><p>Para esse exemplo vamos usar o mesmo array dos exemplos anteriores com um milhão de numeros.</p><pre>0.upto(1000000) do |number|</pre><pre>  dictionary &lt;&lt; number</pre><pre>end</pre><p>Então se a gente rodar os algoritimos criados no capitulo anterior:</p><pre>Benchmark.bm { |bench| bench.report(“o(1)”) { o_one(dictionary) } }</pre><pre>Benchmark.bm { |bench| bench.report(“o(n)”) { o_n(dictionary) } }<br></pre><pre># user system total real</pre><pre># o(1) 0.000000 0.000000 0.000000 ( 0.000005)</pre><pre># user system total real</pre><pre># o(n) 0.060000 0.000000 0.060000 ( 0.052239)</pre><p>Uma diferença bem pequena, e é por isso que <em>O(N)</em> no grafico de complexidade não é tão ruim assim, com um milhão de numeros ele precisou de apenas <em>0.052239s</em>, mas e se a gente subir nosso dataset para 15 milhões de numeros? A solução <em>O(N)</em> vai ser boa? Vamos ver:</p><pre>user system total real</pre><pre>  o(1) 0.000000 0.000000 0.000000 ( 0.000004)</pre><pre>user system total real</pre><pre>  o(n) 0.750000 0.000000 0.750000 ( 0.741515)</pre><p>O tempo da solução <em>O(N)</em> cresceu algo em torno de 12.5x comparado com o array de um milhão de numeros, enquanto a solução <em>O(1)</em> continuou constante.</p><p><strong>4.2 <em>O(N)</em> vs <em>O(N²)</em></strong></p><p>Primeiro, vamos criar de novo o nosso array, mas desta vez com um pouco menos de numeros:</p><pre>data = []<br></pre><pre>0.upto(20000) do |number|</pre><pre>  data &lt;&lt; number</pre><pre>end</pre><p>Sim, duzentos mil é o suficiente para essa exemplo, porque <em>O(N²)</em> é muito ruim, e se aumentarmos nosso array você provavelmente vai usar 100% da sua cpu no processo do Ruby e o sistema operacional vai matar esse processo.</p><p>Vamos examinar o runtime dos algoritimos que fizemos de <em>O(N)</em> e <em>O(N²)</em> no array criado acima:</p><pre>Benchmark.bm { |bench| bench.report(“o(n)”) { o_n(data) } }</pre><pre>Benchmark.bm { |bench| bench.report(“o(n²)”) { o_n2(data) } }</pre><pre><br># user system total real</pre><pre># o(n) 0.010000 0.000000 0.010000 ( 0.000963)</pre><pre># user system total real</pre><pre># o(n²) 19.550000 0.000000 19.550000 ( 19.560149)</pre><p>Essa diferença é muito grande, e é ai que o <em>Big O</em> aparece, o nosso algoritimo <em>O(N²)</em> demorou 19.5 segundos para executar.</p><p><em>Estamos falando do comportamento do algoritimo em função do crescimento do input e das operações.</em></p><p>Ok, você vai me falar que certamente 200 mil inputs é muito alto para o dia a dia da maioria das pessoas, e se a gente testar com 5 mil numeros?</p><pre>user system total real</pre><pre>  o(n) 0.000000 0.000000 0.000000 ( 0.000252)</pre><pre>user system total real</pre><pre>  o(n²) 1.330000 0.000000 1.330000 ( 1.329480)</pre><p>O código demorou 1.3 segundos para ser executado e temos que admitir que 5 mil inputs não é algo grande, ainda mais se tratando de numeros. Isso em uma aplicação final pode ser muito, pois vamos supor que seu cliente espere <em>1.329480</em> três vezes por dia, isso em uma semana vai dar <em>27.9s</em>, isso apenas trabalhando com 5 mil numeros, imagina com mais.</p><p>Então em casos de <em>O(N²)</em> temos que tentar reduzir eles para <em>O(n log n)</em> como falado mais a cima, e o mais importante, evitar usar algoritimos lentos como o bubble sort em grandes quantidades de input.</p><p><strong>4.2 <em>O(N!)</em></strong></p><p>Isso é um teste bem legal pois se a gente usar um milhão de numeros, no meu computador pode demorar algo em torno de 10 horas, e se usarmos cinco mil (igual no exemplo passado) vai demorar um bom tempo também, então para mostrar o <em>O(N!)</em> vou usar apenas 500 numeros para ver a demora.</p><p>Nesse exemplo vou usar o método <em>Array#permutation</em>, do Ruby.</p><pre>dictionary = []<br></pre><pre>0.upto(500) do |number|</pre><pre>  dictionary &lt;&lt; number</pre><pre>end<br></pre><pre>Benchmark.bm { |bench| bench.report(“o(!n)”) { dictionary.permutation(3).to_a } }</pre><p>E o output final é assustador:</p><pre># user system total real</pre><pre># o(!n) 25.530000 1.650000 27.180000 ( 28.155015)</pre><p><em>28.1s</em> com 500 numeros.</p><h3><strong>5. Encerrando</strong></h3><p>Eu não vou fazer benchmark de todos algoritimos e estrutura de dados (pois seria impossivel), mas eu recomendo que se você se interessou continue seus estudos em direção aos tópicos avançados.</p><h4><strong>5.1 What’s next?</strong></h4><p>Se você quer ter uma boa referência quando se trata de <em>Big O</em> keep studying.</p><p>Você pode ler alguns livros que indico, alguns em português e outros dois em inglês:</p><ul><li><a href="https://www.amazon.com.br/Entendendo-Algoritmos-Aditya-Y-Bhargava/dp/8575225634?tag=goog0ef-20&amp;smid=A1ZZFT5FULY4LN&amp;ascsubtag=go_726685122_54292137521_242594579893_pla-395601669245_c_"><em>Entendendo Algoritmos</em></a></li><li><a href="https://mitpress.mit.edu/books/introduction-algorithms"><em>Introduction to Algorithms, Third Edition</em></a></li><li><a href="https://www.amazon.com.br/Algoritmos-Teoria-Pr%C3%A1tica-Thomas-Cormen/dp/8535236996?tag=goog0ef-20&amp;smid=A1ZZFT5FULY4LN&amp;ascsubtag=go_729680143_34002717090_172477348789_pla-577130272232_c_"><em>Algoritmos. Teoria e Prática</em></a><em> (Esse é a versão em português do livro acima)</em></li><li><a href="https://www.amazon.com/Cracking-Coding-Interview-Gayle-McDowell/dp/0984782850/ref=as_li_ss_tl?ie=UTF8&amp;linkCode=sl1&amp;tag=careercup-ctciwebsite-20&amp;linkId=173f3d8878a1d7f0d131a85fbfc9f67f"><em>Cracking the Coding Interview</em></a></li></ul><p>Como já falado, esse último livro tem um capitulo falando apenas de Big O para entrevistas!</p><p>Você também pode seguir os links que vou passar a seguir para continuar estudando por você mesmo.</p><h3><strong>6. Final thoughts</strong></h3><p>Esse post foi longo e eu sei disso! Mas eu acredito que entender muito bem os principios do Big O é muito bom para Engenheiros de Software não apenas para o dia-a-dia mas também para as entrevistas de emprego.</p><p>Se você tem alguma pergunta que eu possa ajudar, por favor pergunte! Pode me enviar email (<em>otaviopvaladares@gmail.com</em>) ou me mandar perguntas no <a href="https://twitter.com/opvaladares"><em>twitter</em></a> ou comentar esse post.</p><p>(Também vou adorar conversar sobre o conteúdo desse post)</p><h3><strong>7. Referência</strong></h3><ul><li><a href="https://pt.stackoverflow.com/questions/56836/defini%C3%A7%C3%A3o-da-nota%C3%A7%C3%A3o-big-o/56842"><em>Definição da notação “Big O”</em></a></li><li><a href="http://www.dca.fee.unicamp.br/~ting/Courses/ea869/faq1.html#item7"><em>Bom conteúdo da UNICAMP</em></a></li><li><a href="http://mitrev.net/ruby/2015/08/28/benchmarking-ruby/"><em>How to benchmark ruby</em></a></li><li><a href="https://stackoverflow.com/questions/2307283/what-does-olog-n-mean-exactly"><em>What does O(log n) mean</em></a></li><li><a href="https://stackoverflow.com/questions/3255/big-o-how-do-you-calculate-approximate-it"><em>How to calculate Big O</em></a></li><li><a href="https://stackoverflow.com/questions/18023576/linear-time-v-s-quadratic-time"><em>Linear time vs Quadratic Time</em></a></li><li><a href="https://stackoverflow.com/questions/13467674/determining-complexity-for-recursive-functions-big-o-notation"><em>How to calculate the complexity of recursive functions</em></a></li><li><a href="https://hackernoon.com/what-does-the-time-complexity-o-log-n-actually-mean-45f94bb5bfbf"><em>O(log n), why is that name?</em></a></li><li>A little<a href="https://stackoverflow.com/questions/5201013/on-log-log-n-time-complexity"><em> bit more about O(log n)</em></a></li><li><a href="https://stackoverflow.com/questions/36318159/big-on-log-n-explanation"><em>And more about O(log n)</em></a></li><li><a href="https://en.wikipedia.org/wiki/Time_complexity"><em>Time complexity Wikipedia</em></a></li><li><a href="https://www.youtube.com/watch?v=MyeV2_tGqvw"><em>Bom video sobre</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cb55297d2f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diferença entre map, collect, select e each no Ruby]]></title>
            <link>https://medium.com/collabcode/diferen%C3%A7a-entre-map-collect-select-e-each-no-ruby-4d8dc853711f?source=rss-91cf42940d67------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d8dc853711f</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Otavio H. P. Valadares]]></dc:creator>
            <pubDate>Thu, 29 Mar 2018 17:28:54 GMT</pubDate>
            <atom:updated>2018-03-29T17:28:54.694Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUza-3w5jFvgxaRZJGMc-w.jpeg" /><figcaption>Enumerable é um iceberg gigante, nesse post vamos aprender a ponta dele.</figcaption></figure><p>Quando se está começando a programar Ruby, vejo que muitas pessoas (inclusive eu), tiveram duvidas quando se trata da diferença entre os métodos map, select e each, eu por exemplo sempre usava each para quase tudo e com isso perdia muitas funcionalidades que a linguagem me proporciona.</p><h3>Each</h3><p><em>O </em><em>each executa para cada elemento a logica passada no bloco.</em></p><p>Se você for iterar um array em Ruby usando um simples for igual as outras linguagens, provavelmente você irá fazer algo parecido com isso:</p><pre>places = [&#39;restaurant&#39;, &#39;mall&#39;, &#39;park&#39;, &#39;theater&#39;] </pre><pre>for place in places <br>  puts place <br>end<br> <br># =&gt; restaurant <br># =&gt; mall <br># =&gt; park <br># =&gt; theater</pre><p>Porém no Ruby, a maneira mais indicada de iterar em uma coleção é usando o each, então ficaria assim:</p><pre>places.each do |place| <br>  puts place <br>end </pre><pre># =&gt; restaurant <br># =&gt; mall <br># =&gt; park <br># =&gt; theater</pre><p>Ou até mesmo usando o inline, que você vai obter o mesmo resultado:</p><pre>places.each { |place| puts place }</pre><h3>Outro exemplo</h3><pre>numbers = [1, 2, 3, 4, 5] </pre><pre>numbers.each { |number| puts number * 2 } </pre><pre># =&gt; 2 <br># =&gt; 4 <br># =&gt; 6 <br># =&gt; 8 <br># =&gt; 10 <br># =&gt; [1, 2, 3, 4, 5]</pre><p>Vale lembrar que o each não altera o array que foi passado no exemplo:</p><pre>puts numbers </pre><pre># =&gt; 1 <br># =&gt; 2 <br># =&gt; 3 <br># =&gt; 4 <br># =&gt; 5 <br># =&gt; nil</pre><p>E também vale lembrar que o each não retorna nada se tentarmos salvar o bloco em uma variavel, diferente do map que veremos a seguir.</p><pre>a = numbers.each { |number| puts number * 2 } </pre><pre>puts a <br># =&gt; [1, 2, 3, 4, 5]</pre><h3>Por baixo dos panos</h3><p>O each entre todos os métodos que iremos ver a seguir é o único que não pertence ao modulo Enumerable, e o que isso significa?</p><p>Enumerable é um modulo no ruby, que traz junto com ele varios métodos, como podemos ver a seguir:</p><pre>Enumerable.instance_methods <br># =&gt; [:to_a, :to_h, :include?, :find, :entries, :sort, :sort_by, :grep, :grep_v, :count, :detect, :find_index, :find_all, :select, :reject, :collect, :map, :flat_map, :collect_concat, :inject, :reduce, :partition, :group_by, :first, :all?, :any?, :one?, :none?, :min, :max, :minmax, :min_by, :max_by, :minmax_by, :member?, :each_with_index, :reverse_each, :each_entry, :each_slice, :each_cons, :each_with_object, :zip, :take, :take_while, :drop, :drop_while, :cycle, :chunk, :slice_before, :slice_after, :slice_when, :chunk_while, :lazy]  </pre><pre>Enumerable.class <br># =&gt; Module</pre><p>E como é um modulo, eu posso incluir ele em qualquer classe e ganhar todos esses métodos, para isso tudo que minha classe precisa ter é um método each implementado que retorna os itens da coleção. Parece confuso? Com o exemplo a seguir se torna fácil de entender.</p><pre>class OddNumbers <br>  include Enumerable <br>  <br>  def each <br>    yield 1 <br>    yield 3 <br>    yield 5 <br>  end<br>end</pre><p>Apos fazer isso, já podemos ver todos os métodos proporcionados pelo Enumerable na nossa classe, entre eles o map, select, inject entre outros.</p><pre>OddNumbers.instance_methods <br># =&gt; [:each, :to_a, :to_h, :include?, :find, :entries, :sort, :sort_by, :grep, :grep_v, :count, :detect, :find_index, :find_all, :select, :reject, :collect, :map, :flat_map, :collect_concat, :inject, :reduce, :partition, :group_by, :first, :all?, :any?, :one?, :none?, :min, :max, :minmax, :min_by, :max_by, :minmax_by, :member?, :each_with_index, :reverse_each, :each_entry, :each_slice, :each_cons, :each_with_object, :zip, :take, :take_while, :drop, :drop_while, :cycle, :chunk, :slice_before, :slice_after, :slice_when, :chunk_while, :lazy, :instance_of?, :public_send, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :private_methods, :kind_of?, :instance_variables, :tap, :method, :public_method, :singleton_method, :is_a?, :extend, :define_singleton_method, :to_enum, :enum_for, :&lt;=&gt;, :===, :=~, :!~, :eql?, :respond_to?, :freeze, :inspect, :display, :object_id, :send, :to_s, :nil?, :hash, :class, :singleton_class, :clone, :dup, :itself, :taint, :tainted?, :untaint, :untrust, :trust, :untrusted?, :methods, :protected_methods, :frozen?, :public_methods, :singleton_methods, :!, :==, :!=, :__send__, :equal?, :instance_eval, :instance_exec, :__id__]</pre><p>E podemos ver o modulo Enumerable nos módulos inclusos.</p><pre>OddNumbers.included_modules <br># =&gt; [Enumerable, Kernel]</pre><p>Nota: Podemos notar que se nossa classe não responder a nenhum método each, o modulo Enumerable não ira funcionar, pois para ele fazer esses métodos todos funcionarem ele precisa que a classe já tenha o each implementado.</p><p>E o que isso muda? A principio nada, pois a maioria das pessoas sempre utilizam esses métodos com Hash ou Array, que ja tem o método each implementado e consequentemente o Enumerable incluso.</p><pre>Array.included_modules <br># =&gt; [Enumerable, Kernel]  <br>Hash.included_modules <br># =&gt; [Enumerable, Kernel]</pre><h3>Map</h3><p>Voltando a explicação dos métodos, com o map as coisas já ficam mais interessantes, ele pode ser aplicado a qualquer classe que tenha o modulo Enumerable incluso.</p><p>Diferente do each visto a cima em vários aspectos, o mais visível sem dúvidas é a sua característica de retornar um Array com o resultado do bloco aplicado para cada elemento recebido.</p><pre>numbers.map { |number| number * 2 } <br># =&gt; [2, 4, 6, 8, 10]</pre><p>Outro exemplo:</p><pre>places = [&#39;restaurant&#39;, &#39;mall&#39;, &#39;park&#39;, &#39;theater&#39;] <br>places_upcase = places.map { |place| place.upcase } </pre><pre>places_upecase <br># =&gt; [&quot;RESTAURANT&quot;, &quot;MALL&quot;, &quot;PARK&quot;, &quot;THEATER&quot;]</pre><h3>Collect</h3><p>O collect é a mesma coisa que o map, sendo apenas um alias.</p><h3>Select</h3><p>Conhecido como o filter em outras linguagens, o select executa a expressão passada para cada elemento do array, se a expressão retornar true, ela e adicionada ao array de output.</p><pre>numbers = [1, 2, 3, 4, 5] numbers.select { |number| number &gt; 3 } <br># =&gt; [4, 5]</pre><p>Podemos ver no exemplo a cima que o retorno do bloco veio apenas com os dois números maiores que 3, respeitando a expressão passada ao bloco.</p><p>No exemplo abaixo temos outro exemplo, onde só pegamos os elementos impares de um array, e como nos outros métodos, salvamos a saída em uma variável.</p><pre>odd_numbers = numbers.select { |number| number.odd? } </pre><pre>odd_numbers <br># =&gt; [1, 3, 5]</pre><h3>Conclusão</h3><p>Embora muita gente se confunda achando que os dois métodos são a mesma coisa (e isso é normal!!!), eles não são, e cada um pode ser útil da sua forma. No modulo Enumerable ainda existe uma infinidade de métodos muito úteis (e outros nem tanto, vamos ser sinceros), que podem te ajudar no seu dia a dia ou até em situações muito especificas, <a href="https://ruby-doc.org/core-2.5.0/Enumerable.html">e eu recomendo que caso tenha interesse estude profundamente o modulo</a>, pois ele pode aumentar muito sua produtividade.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d8dc853711f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/collabcode/diferen%C3%A7a-entre-map-collect-select-e-each-no-ruby-4d8dc853711f">Diferença entre map, collect, select e each no Ruby</a> was originally published in <a href="https://medium.com/collabcode">CollabCode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating simple REST API with Rails 5]]></title>
            <link>https://medium.com/otavio-henrique/creating-simple-rest-api-with-rails-5-1ba71b37cad?source=rss-91cf42940d67------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ba71b37cad</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Otavio H. P. Valadares]]></dc:creator>
            <pubDate>Sun, 19 Nov 2017 16:20:07 GMT</pubDate>
            <atom:updated>2018-12-16T18:08:17.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QIFnOJhLRYlzZ4HltFJ8JQ.jpeg" /><figcaption>Rails logo</figcaption></figure><h3>Table of Contents</h3><ul><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#d2bd">1.0 Introducion</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#a2b6">2.0 Creating and Setting Up</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#b199">2.1 Installind Rspec</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#253e">2.2 Setting API Subdomain</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#8d21">2.3 Set up /etc/hosts</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#6580">2.4 Setting API Versioning</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#556f">3.0 Creating Book Model</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#2cc9">3.1 Index All Books</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#ebcd">4.0 Active Model Serializer</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#841b">4.1 Custom Method on Serializer</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#11bb">4.2 Json API Adapter</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#288e">5.0 Creating the Others Actions</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#e6da">5.1 Action Create</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#5d41">5.2 Action Show</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#d6f1">5.3 Action Update</a></li><li><a href="https://medium.com/@Otavio.henrique/1ba71b37cad#0318">5.4 Action Destroy</a></li></ul><h3>1 . 0 Introduction</h3><p>On this post I’ll teach how to make an rest api in few minutes using rails 5 api only, I know this is to late (ruby 5 was released in more than year ago), but I’ll try to make a good tutorial that need only some minutes and only one post.</p><p>Let’s start!</p><p><em>Note: This post don’t use TDD or any test, but everybody knows that it’s necessary, try to make your own tests.</em></p><p><em>In this tutorial you need rails 5+ installed.</em></p><h3>2.0 Creating and Setting Up</h3><p>First of all, we will start a new rails project with mysql database using the api mode introduced on rails 5. I passed -T flag to skip test unit because I’ll use rspec on this project, but if you prefer Minitest you can use this.</p><pre>rails new library --api -d mysql -T</pre><h4>2.1 Installing Rspec</h4><p>Accessing the <a href="https://github.com/rspec/rspec-rails">github of rspec</a>.</p><p>For install just add to your GEMFILE on the development/test group:</p><pre>group :development, :test do<br>  gem &#39;rspec-rails&#39;, &#39;~&gt; 3.6&#39;<br>end</pre><p>And to avoid future work, add <a href="https://github.com/thoughtbot/factory_girl">factory girl</a> to your gemfile too.</p><pre>gem &#39;factory_girl&#39;</pre><p>After this, just run bundle install and wait the end of processs, after this, run rails generate rspec:install and you&#39;ll see rspec creating his folders and files.</p><p><em>Rails output</em></p><pre>create  .rspec<br>create  spec<br>create  spec/spec_helper.rb<br>create  spec/rails_helper.rb</pre><p>After this we finished the configuration of our test suit.</p><h4>2.2 Setting API subdomain</h4><p>Open your routes.rb and I think it will look like this:</p><pre>Rails.application.routes.draw do<br>end</pre><p>And replace to this:</p><pre>Rails.application.routes.draw do<br>  constraints subdomain: &#39;api&#39; do<br>  end<br>end</pre><p>With this we’re telling to rails that our application can be accessed on url api.&lt;some_name&gt;.com/ (With api subdomain).</p><h4>2.3 Set up /etc/hosts</h4><p>To work with subdomain on localhost (development), you need to set up the subdomain on /etc/hosts (On UNIX base SO’s) to receive you api subdomain + domain.</p><p>Open you terminal and open the /etc/hosts file with sudo permission, I personally prefer to do this with vim, but feel free to choose what you prefer.</p><p>After open your /etc/hosts simple add the fallowing lines:</p><pre>127.0.0.1 api.library.com</pre><p>And that’s all. Now you can develop using curl/postman easily.</p><p><em>Note: If you’re using windows, please fallow this </em><a href="https://www.howtogeek.com/howto/27350/beginner-geek-how-to-edit-your-hosts-file/"><em>tutorial</em></a><em>.</em></p><h4>2.4 Setting API Versioning</h4><p>Open your GEMFILE to add the fallowing gems:</p><pre># A plugin for versioning Rails based RESTful APIs.<br>gem &#39;versionist&#39;</pre><p>And just run bundle install and wait. After installing your dependencies we can configure our project to work with versionist gem, this gem easily provide api versioning for our project, and I&#39;ll show you.</p><p>If you’re the guy who prefer to create things by command line, I don’t hate you, and you can make everything I’m going to do next with the fallowing line:</p><p>rails generate versionist:new_api_version v1 V1 --path=value:v1</p><p><em>Note that if you do with this generator rails will create a lot of things for you, not just the route</em></p><p><em>Rails output</em></p><pre>create  app/controllers/v1<br>create  app/controllers/v1/base_controller.rb<br>create  spec/controllers/v1<br>create  spec/controllers/v1/base_controller_spec.rb<br>create  spec/requests/v1<br>create  spec/requests/v1/base_controller_spec.rb<br>create  app/presenters/v1<br>create  app/presenters/v1/base_presenter.rb<br>create  spec/presenters/v1<br>create  spec/presenters/v1/base_presenter_spec.rb<br>create  app/helpers/v1<br>create  spec/helpers/v1<br>create  public/docs/v1<br>create  public/docs/v1/index.html<br>create  public/docs/v1/style.css</pre><p><em>But if you do that your routes will look like this:</em></p><pre>constraints subdomain: &#39;api&#39; do<br>end<br>api_version(:module =&gt; &quot;V1&quot;, :path =&gt; {:value =&gt; &quot;v1&quot;}) do<br>end</pre><p>And you will need to put:</p><pre>api_version(:module =&gt; &quot;V1&quot;, :path =&gt; {:value =&gt; &quot;v1&quot;}) do<br>end</pre><p>Inside your namespace. But if you want to do with your fingers just write this api_version(...) with your hands!</p><h3>3.0 Creating book model</h3><p>Our first model will be book, the core of the library. Our book table will have some attributes, and will look like this:</p><p>idtitleauthorweightpublisherlanguagepagespublicationDate1Atlas ShruggedAyn Rand3.4 poundsDuttonEnglish1168April 21, 20052Murder on the Orient ExpressAgatha Christie12.6 ouncesWilliam MorrowEnglish272October 24, 2017</p><p>For create this automatically just type:</p><pre>rails g model Book title:string author:string weight:string publisher:string language:string pages:integer publication_date:datetime</pre><p><em>Rails output</em></p><pre>invoke  active_record<br>create    db/migrate/20171018035914_create_books.rb<br>create    app/models/book.rb<br>invoke    rspec<br>create      spec/models/book_spec.rb</pre><p>So now, rails created the model, the migration and the spec for us.</p><p>Run rake db:create for create the database, and after this, run rake db:migrate to create book table. Now you can see your file at app/models/book.rb path.</p><h4>3.1 Index All Books</h4><p>Go to your routes.rb and add:</p><pre>resources :books</pre><p>After this, create the books controller inside version 1</p><p>Books controller path: app/controllers/v1/books_controller.rb</p><p>After this, enter in you file and type:</p><pre># frozen_string_literal: true</pre><pre>class V1::BooksController &lt; ApplicationController<br>  def index<br>    books = Book.all<br>    render json: { books: books }, status: :ok<br>  end<br>end</pre><p>and we’re done, but for test we need to create some books on database. Type rails c on your terminal and let&#39;s do that.</p><pre>Book.create(title: &quot;Atlas Shrugged&quot;, author: &quot;Ayn Rand&quot;, weight: &quot;3.4 pounds&quot;, publisher: &quot;Dutton&quot;, language: &quot;English&quot;, pages: 1168, publication_date: &quot;April 21, 2005&quot;)</pre><p>Feels free to alter this data and create different books for you.</p><p>Now just start your rails server and go to your postman and GET http://api.library.com:3000/v1/books and you will see the API returning your book data, like this(using my data):</p><p><em>API output</em></p><pre>{<br>    &quot;books&quot;: [<br>        {<br>            &quot;id&quot;: 1,<br>            &quot;title&quot;: &quot;Atlas Shrugged&quot;,<br>            &quot;author&quot;: &quot;Ayn Rand&quot;,<br>            &quot;weight&quot;: &quot;3.4 pounds&quot;,<br>            &quot;publisher&quot;: &quot;Dutton&quot;,<br>            &quot;language&quot;: &quot;English&quot;,<br>            &quot;pages&quot;: 1168,<br>            &quot;publication_date&quot;: &quot;2005-04-21T00:00:00.000Z&quot;,<br>            &quot;created_at&quot;: &quot;2017-10-20T02:39:53.000Z&quot;,<br>            &quot;updated_at&quot;: &quot;2017-10-20T02:39:53.000Z&quot;<br>        },<br>        {<br>            &quot;id&quot;: 2,<br>            &quot;title&quot;: &quot;Murder on the Orient Express&quot;,<br>            &quot;author&quot;: &quot;Agatha Christie&quot;,<br>            &quot;weight&quot;: &quot;12.6 ounces&quot;,<br>            &quot;publisher&quot;: &quot;12.6 ounces&quot;,<br>            &quot;language&quot;: &quot;English&quot;,<br>            &quot;pages&quot;: 272,<br>            &quot;publication_date&quot;: &quot;2017-10-24T00:00:00.000Z&quot;,<br>            &quot;created_at&quot;: &quot;2017-10-20T02:40:15.000Z&quot;,<br>            &quot;updated_at&quot;: &quot;2017-10-20T02:40:15.000Z&quot;<br>        }<br>    ]<br>}</pre><p>And we’re done. We finished our “Hello world” in rest APIs.</p><h3>4.0 Active Model Serializer</h3><p>Active model serializer it’s a fabulous gem, thats brings convention over configuration to our API’s JSON, he works with serializers and adapters and I’ll show you how to use.</p><p>First of all, open your gemfile and add:</p><pre>gem &#39;active_model_serializers&#39;, &#39;~&gt; 0.10.0&#39;</pre><p>And run bundle</p><p>Afther this, you can create any serializer with the fallowing command (On the example I’m creating to book model):</p><p>rails g serializer v1/book</p><p><em>Rails output</em></p><pre>create  app/serializers/v1/book_serializer.rb</pre><p>Now, go to your v1/books_controller.rb and on your index action, remove json: { books: books } and put just json: books for we start using the AMS.</p><p>The final code of the index action of books_controller.rb will be like:</p><pre>def index<br>  books = Book.all<br>  render json: books, status: :ok<br>end</pre><p>Now if we restart our server and make the same GET http://api.library.com:3000/v1/books will we see this output:</p><p><em>API output</em></p><pre>[<br>     {<br>         &quot;id&quot;: 1<br>     },<br>     {<br>         &quot;id&quot;: 2<br>     }<br> ]</pre><p>Don’t panic, this is normal! We’ll see only Ids of the books because we don’t set up our books serializer to output others attributes, to fix this, open your app/serializers/v1/book_serializer.rb and you will see only this:</p><pre>class V1::BookSerializer &lt; ActiveModel::Serializer<br>  attributes :id<br>end</pre><p>The only attribute that is outputing is id and we need to add more things, add the others things of the model that you want to show (I will add everything except created_at and updated_at because I don&#39;t think necessary), and my code will look like:</p><pre>class V1::BookSerializer &lt; ActiveModel::Serializer<br>  attributes :id, :title, :author, :weight, :publisher, :language, :pages, :publication_date<br>end</pre><p>Now if we call our API again, we will get:</p><p><em>API output</em></p><pre>[<br>    {<br>        &quot;id&quot;: 1,<br>        &quot;title&quot;: &quot;Atlas Shrugged&quot;,<br>        &quot;author&quot;: &quot;Ayn Rand&quot;,<br>        &quot;weight&quot;: &quot;3.4 pounds&quot;,<br>        &quot;publisher&quot;: &quot;Dutton&quot;,<br>        &quot;language&quot;: &quot;English&quot;,<br>        &quot;pages&quot;: 1168,<br>        &quot;publication_date&quot;: &quot;2005-04-21T00:00:00.000Z&quot;<br>    },<br>    {<br>        &quot;id&quot;: 2,<br>        &quot;title&quot;: &quot;Atlas Shrugged&quot;,<br>        &quot;author&quot;: &quot;Ayn Rand&quot;,<br>        &quot;weight&quot;: &quot;3.4 pounds&quot;,<br>        &quot;publisher&quot;: &quot;Dutton&quot;,<br>        &quot;language&quot;: &quot;English&quot;,<br>        &quot;pages&quot;: 1168,<br>        &quot;publication_date&quot;: &quot;2005-04-21T00:00:00.000Z&quot;<br>    }<br> ]</pre><p>Looks pretty much sexy, right?</p><h4>4.1 Custom Methods On Serializer</h4><p>One thing is troubling me on this response, it’s publication_date format, look on the last json, 2005-04-21T00:00:00.000Z is not good for me, let&#39;s fix this, on the BookSerializer add this method:</p><pre>def publication_date<br>  object.publication_date.strftime &quot;%Y-%m-%d&quot;<br>end</pre><p>With this, we’re taking the object that is book record in this context and formating date, remember that you can add any custom method using this, just remeber to add in the attributes on the top of your serializer and make your custom method.</p><p>Now our json is looking like this:</p><p><em>API output</em></p><pre>[<br>    {<br>        &quot;id&quot;: 1,<br>        &quot;title&quot;: &quot;Atlas Shrugged&quot;,<br>        &quot;author&quot;: &quot;Ayn Rand&quot;,<br>        &quot;weight&quot;: &quot;3.4 pounds&quot;,<br>        &quot;publisher&quot;: &quot;Dutton&quot;,<br>        &quot;language&quot;: &quot;English&quot;,<br>        &quot;pages&quot;: 1168,<br>        &quot;publication_date&quot;: &quot;2005-04-21&quot;<br>    },<br>    <br>   ....<br>]</pre><h4>4.2 Json API Adapter</h4><p>One of the advantages of use active model serializer gem is that this gem alterady have an adapter to use <a href="http://jsonapi.org/">jsonapi.org</a> convention in your API, for whos don’t know, this shared conventions pattern the json resposes. I really recommend that you read more about <a href="http://jsonapi.org/">here</a>.</p><p>Create a file named active_record_serializer.rb at config/initializers/ and put this inside:</p><pre>ActiveModelSerializers.config.adapter = :json_api</pre><p>Restart your application, make the same call for your API and see the difference.</p><p><em>API output</em></p><pre>{<br>    &quot;data&quot;: [<br>        {<br>            &quot;id&quot;: &quot;1&quot;,<br>            &quot;type&quot;: &quot;books&quot;,<br>            &quot;attributes&quot;: {<br>                &quot;title&quot;: &quot;Atlas Shrugged&quot;,<br>                &quot;author&quot;: &quot;Ayn Rand&quot;,<br>                &quot;weight&quot;: &quot;3.4 pounds&quot;,<br>                &quot;publisher&quot;: &quot;Dutton&quot;,<br>                &quot;language&quot;: &quot;English&quot;,<br>                &quot;pages&quot;: 1168,<br>                &quot;publication-date&quot;: &quot;2005-04-21&quot;<br>            }<br>        },<br>        {<br>            &quot;id&quot;: &quot;2&quot;,<br>            &quot;type&quot;: &quot;books&quot;,<br>            &quot;attributes&quot;: {<br>                &quot;title&quot;: &quot;Atlas Shrugged&quot;,<br>                &quot;author&quot;: &quot;Ayn Rand&quot;,<br>                &quot;weight&quot;: &quot;3.4 pounds&quot;,<br>                &quot;publisher&quot;: &quot;Dutton&quot;,<br>                &quot;language&quot;: &quot;English&quot;,<br>                &quot;pages&quot;: 1168,<br>                &quot;publication-date&quot;: &quot;2005-04-21&quot;<br>            }<br>        }<br>    ]    <br>}</pre><p>Your api response are now fallowing jsonapi specification without pains.</p><h3>5. 0 Creating the others actions (Create, Show, PUT/Patch, Delete)</h3><p>Now that I explained all the things of this project architecture we just need to finish our CRUD actions and and we’re done. We already have our routes created because we write resources :books at our routes.rb, so if you run the rake routeson the project we will have:</p><p><em>Rails output</em></p><pre>Prefix Verb   URI Pattern             Controller#Action<br>v1_books GET    /v1/books(.:format)     v1/books#index {:subdomain=&gt;&quot;api&quot;}<br>         POST   /v1/books(.:format)     v1/books#create {:subdomain=&gt;&quot;api&quot;}<br> v1_book GET    /v1/books/:id(.:format) v1/books#show {:subdomain=&gt;&quot;api&quot;}<br>         PATCH  /v1/books/:id(.:format) v1/books#update {:subdomain=&gt;&quot;api&quot;}<br>         PUT    /v1/books/:id(.:format) v1/books#update {:subdomain=&gt;&quot;api&quot;}<br>         DELETE /v1/books/:id(.:format) v1/books#destroy {:subdomain=&gt;&quot;api&quot;}</pre><h4>5.1 Action Create</h4><p>Let’s start with creating action of our books. Since we already have the create route created we just need to code create action on, v1/books_controller.rb, open this file, and write:</p><pre>def create<br>  book = Book.new(book_params)</pre><pre>  if book.save<br>    render json: book, status: :created<br>  else<br>    render json: { errors: book.errors }, status:    :unprocessable_entity<br>  end</pre><pre>  private<br>  <br>  def book_params<br>    params.require(:book).permit(:title, :author, :weight, :publisher, :language, :pages, :publication_date)<br>  end</pre><p>Go yo your postman to test our new action, and POST http://api.library.com:3000/v1/books and make a request with this body:</p><p><em>API output</em></p><pre>{<br>    &quot;book&quot;: {<br>	&quot;title&quot;: &quot;The Information: A History, a Theory, a Flood&quot;,<br>	&quot;author&quot;: &quot;James Gleick&quot;,<br>	&quot;weight&quot;: &quot;1.2 pounds&quot;,<br>	&quot;publisher&quot;: &quot;Vintage&quot;,<br>	&quot;language&quot;: &quot;English&quot;,<br>	&quot;pages&quot;: 544,<br>	&quot;publication_date&quot;: &quot;March 6, 2012&quot;<br>    }<br>}</pre><p>And we will got 201 status response and a json with our new book information, now if you go to your rails c and type Book.last you will get our book created:</p><p><em>Rails output</em></p><pre>=&gt; #&lt;Book id: 5, title: &quot;The Information: A History, a Theory, a Flood&quot;, author: &quot;James Gleick&quot;, weight: &quot;1.2 pounds&quot;, publisher: &quot;Vintage&quot;, language: &quot;English&quot;, pages: 544, publication_date: &quot;2012-03-06 00:00:00&quot;, created_at: &quot;2017-10-21 19:12:33&quot;, updated_at: &quot;2017-10-21 19:12:33&quot;&gt;</pre><p><em>Note: I pretty recommend that if you are a begginer, make every time this tests, it’s cool to see your application running.</em></p><h4>5.2 Action Show</h4><p>The same thing of action create, but you need to write this at controller:</p><pre>def show<br>  book = Book.find(params[:id])<br>  render json: book, status: :ok<br>end</pre><p>And go to your postman and make this request: GET http://api.library.com:3000/v1/books/1 and you will see your id: 1 book on response. (You can pass any valid id and return the corresponding book).</p><p><em>Note: on the final of request you’re passing the id of your book, on this example I used 1.</em></p><p><em>API output</em></p><pre>{<br>    &quot;data&quot;: {<br>        &quot;id&quot;: &quot;5&quot;,<br>        &quot;type&quot;: &quot;books&quot;,<br>        &quot;attributes&quot;: {<br>            &quot;title&quot;: &quot;The Information: A History, a Theory, a Flood&quot;,<br>            &quot;author&quot;: &quot;James Gleick&quot;,<br>            &quot;weight&quot;: &quot;1.2 pounds&quot;,<br>            &quot;publisher&quot;: &quot;Vintage&quot;,<br>            &quot;language&quot;: &quot;English&quot;,<br>            &quot;pages&quot;: 544,<br>            &quot;publication-date&quot;: &quot;2012-03-06&quot;<br>        }<br>    }<br>}</pre><p><em>Note: You can find every book of your database, just pass a valid id.</em></p><h4>5.3 Action Update</h4><p>Update it’s like the action create with some changes:</p><pre>def update<br>    book = Book.find(params[:id])</pre><pre>    if book.update(book_params)<br>      render json: book, status: :ok<br>    else<br>      render json: { errors: book.errors }, status: :unprocessable_entity<br>    end<br>  end</pre><p>Now just PUT http://api.library.com:300/v1/books/5 with this json:</p><pre>{<br>	&quot;publisher&quot;: &quot;Vintage Books&quot;<br>}</pre><p>This json with this request will change the punblisher of the book with id: 5 in my database to &quot;Vintage Books&quot; (Actually is only &quot;Vintage&quot;), make this request and see the response.</p><p><em>NOTE: On this example I used the </em><em>id: 5 book because on my database was this id, on your database depending of what you done, this id can change. You can do this example with any book of your database, just change for something that you want.</em></p><p><em>API output</em></p><pre>{<br>    &quot;data&quot;: {<br>        &quot;id&quot;: &quot;5&quot;,<br>        &quot;type&quot;: &quot;books&quot;,<br>        &quot;attributes&quot;: {<br>            &quot;title&quot;: &quot;The Information: A History, a Theory, a Flood.&quot;,<br>            &quot;author&quot;: &quot;James Gleick&quot;,<br>            &quot;weight&quot;: &quot;1.2 pounds&quot;,<br>            &quot;publisher&quot;: &quot;Vintage Books&quot;,<br>            &quot;language&quot;: &quot;English&quot;,<br>            &quot;pages&quot;: 544,<br>            &quot;publication-date&quot;: &quot;2012-03-06&quot;<br>        }<br>    }<br>}</pre><h4>5.4 Action Destroy</h4><p>Destroy it’s the easiest action of the CRUD, you just need to write:</p><pre>def destroy<br>  book = Book.find(params[:id])<br>  book.destroy<br>  head 204<br>end</pre><p>And that’s all, to test, make a request DELETE http://api.library.com:3000/v1/books/2 and you will delete the second book of your database. The API will not return anything but the request status will be 204. If you go to your rails console and try to find the book with id: 2, using Book.find 2 you will get this error:</p><pre>ActiveRecord::RecordNotFound: Couldn&#39;t find Book with &#39;id&#39;=2</pre><p>Telling that this book dont exist anymore.</p><p><strong><em>Note: We can’t revert this action. “Remember, with great power comes great responsibility”</em></strong></p><h3>Finishing</h3><p>Everything is done, if you have any question, please ask.</p><p>That’s all for today folks, don’t forget to follow my blog and my <a href="https://twitter.com/opvaladares">twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ba71b37cad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/otavio-henrique/creating-simple-rest-api-with-rails-5-1ba71b37cad">Creating simple REST API with Rails 5</a> was originally published in <a href="https://medium.com/otavio-henrique">Garagelab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Enemy AI System for Unity3D]]></title>
            <link>https://medium.com/otavio-henrique/simple-enemy-ai-system-for-unity3d-ed22f389974c?source=rss-91cf42940d67------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed22f389974c</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[unity3d]]></category>
            <dc:creator><![CDATA[Otavio H. P. Valadares]]></dc:creator>
            <pubDate>Wed, 09 Aug 2017 22:36:46 GMT</pubDate>
            <atom:updated>2017-11-19T16:26:53.181Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I am going to explain how I have developed a simple AI system for the enemies of my final project on technical college. The idea is a simple script that made the enemy’s walks randomly on the on the scene, chase and attack the player.</p><p>The IA script that I developed is based on several games, especially in stealth games. The enemy will select a random destination when the game is started and will walking in this direction, when he comes close to the selected random destination, and another random destination is selected and it starts all the process again. If while he is walking toward a point he sees the player, he starts chasing the player and if he reaches the player, he is going to attack attack him.</p><p>For this example I will use Unity 5 game engine but you can easily make changes and use in other engines like Unreal.</p><p>I will not explain basics features of Unity in this post or programming logic, If you have any question please read the reference links or ask me here or on my Twitter.</p><h3>First Step: Build Scene</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*EL4ftSsWXOJgTGFL.png" /></figure><p>For this example I have build a simple maze using 3D blocks and positioned the enemy(blue sphere) on the right top corner and our player on lower left corner (red sphere).<br>Our player its a simple FPSController (You can find this script on Unity Standard Assets), read more <a href="https://docs.unity3d.com/Manual/class-CharacterController.html">here</a>.</p><h3>Second Step: Create Navigation Mesh</h3><p>For our enemy walk on the scene the easiest method is create a navigation mesh on the scene and add a Nav Mesh Agent on the components of our enemy (3D sphere).</p><p><em>“The navigation system allows you to create characters that can intelligently move around the game world, using navigation meshes that are created automatically from your Scene geometry.“</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/0*dHTf-6OyBjSKrluP.png" /></figure><p><em>Pay atention on your navigation mesh, it must be bypassing all walls, if not your enemy will not work correctly.</em></p><p>This simple step will make the next things easy.</p><h3>Third Step: Our script</h3><p>To start we need to declare and define our random destination using Random.range function and get navMeshAgent component. After this our code looks like this:</p><pre><strong>public</strong> <strong>int</strong> currentRandomPoint;<br><strong>private</strong> NavMeshAgent navMesh;</pre><pre><strong>void</strong> Start () {<br>  currentRandomPoint = Random.Range(0, randomPoints.Length);<br>  navMesh = transform.GetComponent&lt;NavMeshAgent&gt;();<br>}</pre><p>If you will use annimator component to use animations on the enemy you should declare and use on the void start too, like this:</p><pre><strong>protected</strong> Animator animator;</pre><pre>  animator = GetComponent&lt;Animator&gt;();</pre><p>On void update the first thing we need to do is calculate player distance and the random point distance, for this we use Vector3.</p><pre>playerDist = Vector3.Distance(Player.transform.position, transform.position);<br>randomPointDist = Vector3.Distance(randomPoints[currentRandomPoint].<br>transform.position, transform.position)</pre><p>And declare a RaycastHit, this raycasthit will will ensure that our enemy does not see the player behind walls.</p><pre>RaycastHit hit;</pre><p>You can read about <em>Physics.Raycast</em> <a href="https://docs.unity3d.com/ScriptReference/Physics.Raycast.html">here</a>.</p><pre><strong>if</strong> (Physics.Raycast (transform.position, direction, <strong>out</strong> hit, 1000) &amp;&amp; <br>    playerDist &lt; perceptionDistance ) {<br>      <strong>if</strong> (hit.collider.gameObject.CompareTag(&quot;Player&quot;)) {<br>        seeingPlayer = <strong>true</strong>;<br>      } <strong>else</strong> {<br>        seeingPlayer = <strong>false</strong>;<br>    }<br>}</pre><pre>And walk while our player distance is greater than perception distance.</pre><pre><strong>if</strong> ( playerDist &gt; perceptionDistance)<br>  walk();</pre><p>And our walk method is basically set navMesh acceleration, speed and destination, like this:</p><pre><strong>void</strong> walk () {<br>  <strong>if</strong> (chasing == <strong>false</strong>) {<br>    navMesh.acceleration = 1;<br>    navMesh.speed = walkVelocity;<br>    navMesh.destination = randomPoints[currentRandomPoint].position;<br>  } <strong>else</strong> <strong>if</strong> (chasing == <strong>true</strong>) {<br>    chaseTime = <strong>true</strong>;<br>  }<br>}</pre><p>And now with RaycastHit, player distance and random point distance our script is making something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/0*ifSApAWKUH3wDLuq.png" /></figure><p>The orange dotted thick line it’s our script calculating the player distance, the blue dotted line it’s the random point distance and the green arrow is our RaycastHit.</p><p>And here the other 3 behaviors of our enemy:</p><pre><strong>void</strong> look () {<br>  navMesh.speed = 0;<br>  transform.LookAt (Player);<br>}<br><strong>void</strong> chase () {<br>  navMesh.acceleration = 5;<br>  navMesh.speed = chaseVelocity;<br>  navMesh.destination = Player.position;<br>}<br><strong>void</strong> attack () {<br>  navMesh.acceleration = 0;<br>  navMesh.speed = 0;<br>  attacking = <strong>true</strong>;<br>}</pre><p>If you are working with animator and animations you can call your animator variables here, like this example:</p><pre>animator.SetFloat(&quot;Speed&quot;, 0.5f);</pre><p>The next steps is make a lot of checkings to attack, chase, stop chasing and all that stuffs, I will not going into details, but if you have doubts you can contact me as I told above.</p><p>Here’s the next checkings:</p><pre><strong>if</strong> ( playerDist &lt;= perceptionDistance &amp;&amp; playerDist &gt; chaseDistance) {<br>  <strong>if</strong> (seeingPlayer == <strong>true</strong>)<br>    look();<br>  <strong>else</strong><br>    walk();<br>  }</pre><pre>  <strong>if</strong> ( playerDist &lt;= chaseDistance &amp;&amp; playerDist &gt; attackDistance) {<br>    <strong>if</strong> (seeingPlayer == <strong>true</strong>) {<br>      chase();<br>      chasing = <strong>true</strong>;<br>    }<strong>else</strong> {<br>      walk();<br>    }<br>  }</pre><pre>  <strong>if</strong> (playerDist &lt;= attackDistance &amp;&amp; seeingPlayer == <strong>true</strong>)<br>    attack();</pre><pre>  <strong>if</strong> (randomPointDist &lt;= 8) {<br>    currentRandomPoint = Random.Range(0, randomPoints.Length);<br>    walk();<br>  }</pre><pre>  <strong>if</strong> (chaseTime == <strong>true</strong>)<br>    chaseStopwatch += Time.deltaTime;</pre><pre>  <strong>if</strong> (chaseStopwatch &gt;= 5 &amp;&amp; seeingPlayer == <strong>false</strong>) {<br>    chaseTime = <strong>false</strong>;<br>    chaseStopwatch = 0;<br>    chasing = <strong>false</strong>;<br>  }</pre><pre>  <strong>if</strong> (attacking == <strong>true</strong>)<br>    attackingStopwatch += Time.deltaTime;</pre><p>And the attack checking:</p><pre><strong>if</strong> (attackingStopwatch &gt;= attackTime &amp;&amp; playerDist &lt;= attackDistance) {<br>  attacking = <strong>true</strong>;<br>  attackingStopwatch = 0;<br>      <br>  <strong>if</strong> (attackingStopwatch &gt;= attackTime &amp;&amp; playerDist &gt; attackDistance) {<br>    attacking = <strong>false</strong>;<br>    attackingStopwatch = 0;<br>  }<br>}</pre><p>If you want to cause damage on player you should add something like this:</p><pre>playerLife = playerLife - enemyDamage;</pre><pre><strong>if</strong> (playerLife &lt;= 5) {<br>  Application.LoadLevel(GameOverSceneName);<br>} <strong>else</strong> <strong>if</strong> (attackingStopwatch &gt;= attackTime &amp;&amp; playerDist &gt; attackDistance) {<br>  attacking = <strong>false</strong>;<br>  attackingStopwatch = 0;<br>}</pre><p>I really recommend your playerLife be a variable of an script of the player.</p><p>Finally, if you want that’s your player can attack the enemy you can add rigidBody component to your enemy and make this:</p><pre><strong>void</strong> OnCollisionEnter (Collision col) {<br>  <strong>if</strong>(col.transform.tag == &quot;Bullet&quot;){<br>    enemyLife -= 10;<br>    <strong>if</strong> (enemyLife &lt;= 0) {<br>      Destroy (gameObject);<br>    }<br>  }<br>}</pre><p>And now we finished our simple artificial intelligence script and you can use for your simple game, study and improve, in a few months I will post the second part explaining how to improve this script, adding field of vision, sounds and etc..</p><p>You can view the full script/project on my github, and sorry for the quality of the project/code, I was 16 years old when I wrote this.</p><p><a href="https://github.com/OtavioHenrique/simpleAI">https://github.com/OtavioHenrique/simpleAI</a></p><p>And ask me on my Twitter or Linkedin</p><p><strong>Thanks guys, see you soon.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed22f389974c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/otavio-henrique/simple-enemy-ai-system-for-unity3d-ed22f389974c">Simple Enemy AI System for Unity3D</a> was originally published in <a href="https://medium.com/otavio-henrique">Garagelab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>