<?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 Alexis Lucattini on Medium]]></title>
        <description><![CDATA[Stories by Alexis Lucattini on Medium]]></description>
        <link>https://medium.com/@awlucattini_60867?source=rss-5b91b179ba57------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*dcqA2yliorCvUwC5KqQzNg.jpeg</url>
            <title>Stories by Alexis Lucattini on Medium</title>
            <link>https://medium.com/@awlucattini_60867?source=rss-5b91b179ba57------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:18:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@awlucattini_60867/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[Car-diff — a tale of two Civics]]></title>
            <link>https://medium.com/@awlucattini_60867/car-diff-a-tale-of-two-civics-b79d4b68b13e?source=rss-5b91b179ba57------2</link>
            <guid isPermaLink="false">https://medium.com/p/b79d4b68b13e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[cars]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alexis Lucattini]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 04:49:56 GMT</pubDate>
            <atom:updated>2024-06-28T05:17:24.790Z</atom:updated>
            <content:encoded><![CDATA[<h3>Car-diff — a tale of two Civics</h3><h4>A quick (but complicated) way to compare cars through carsales.com.au with html -&gt; yaml -&gt; dyff</h4><p>Sadly, the time has come to part ways with our 2006 manual-transmission Honda Jazz (which we purchased off a friend for just $2.5 K!). It has done us very well, the perfect, pre-scratched + dented, nothing-to-lose car.</p><p>If this car were a child, it would be legally old enough to drive itself, which I think is a fair indicator that it’s time to move on.</p><p>On paper, the Honda HR-V looks like the perfect upgrade, but the main issue is that neither my partner or I are ‘car-people’. We’ve test driven a few cars (all around the 2016–2017 era), and everything just seems perfectly smooth in comparison to our current metal box.</p><p>Looking to capitalise on any EOFY deals that are happening over the next week, the good deals are being snatched up as soon as we contact the seller. It’s a difficult (and time consuming) task of comparing the features of the various car brands, years, models and even model variants!</p><p>Noticing that the <a href="https://www.carsales.com.au/research/">research page on carsales.com.au</a> has a standard format for specs as seen below, let’s see if we can exploit this to just see the differences between two models!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V2dxdd6ZbWAKUIdb-SG-Hg.png" /><figcaption>The Honda HR-V VTiS Features</figcaption></figure><p>In this guide we will use the python library <a href="https://beautiful-soup-4.readthedocs.io/en/latest/">BeatifulSoup4</a> to scrape the relevant HTML Element followed by <a href="https://yaml.readthedocs.io/en/latest/">ruamel.yaml</a> to produce the car specs as a yaml document.</p><h4>Part 1 — Collecting the HTML ‘div’</h4><p>Head to the <a href="https://www.carsales.com.au/research/">carsales.com.au research page</a> and navigate to your first car of interest, including the year and variant of interest.</p><p>Open up the inspect console (F12 or right-click + inspect) on your browser.</p><p>Head to the selection tool (Ctrl + Shift + C) and hover the mouse between the ‘Features’ tab and the ‘Audio, visual &amp; communication’ header</p><p>Hover the mouse, then head to the highlighted div in the insepection console and copy the element — this will copy the html element to your clipboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sM1h-J2WG_qhEJKhFoMezQ.png" /><figcaption>Copy the HTML Element to your Clipboard</figcaption></figure><h4>Part 2 — Inspecting our element</h4><p>Copying our element into a scratch file we can see that it follows the following div patterns:</p><ul><li>headers are part of the their own separate class section — see those with the ‘id’ attribute with the ‘-header’ suffix.</li><li>Contents are under the matching id attribute without the -header suffix</li><li>These two combinations can get us our list of headers</li></ul><pre>&lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc _1lalutr31i _1lalutr1oo _1lalutr1op _1lalutr1oq _1lalutr1ox _1lalutr1oy _1lalutr1oz&quot;&gt;<br>    &lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc&quot;&gt;<br>        &lt;div class=&quot;iompba0 iompba3 _1ukdc9ck _1ukdc9cl _1ukdc9co&quot;&gt;<br>            &lt;div class=&quot;iompba0 iompba3 _1ukdc9cq _1ukdc9cr _1ukdc9cu  _1ukdc9cz&quot; id=&quot;audiovisualcommunication-header&quot;<br>                 aria-controls=&quot;audiovisualcommunication&quot; aria-expanded=&quot;false&quot; role=&quot;button&quot; tabindex=&quot;0&quot;&gt;Audio, visual<br>                &amp;amp; communication<br>                &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;24&quot; height=&quot;24&quot; viewBox=&quot;0 0 24 24&quot;<br>                     class=&quot;iompba0 iompba3  _1mgmi6k2&quot; fill=&quot;currentColor&quot; aria-hidden=&quot;true&quot;&gt;<br>                    &lt;path fill-rule=&quot;evenodd&quot;<br>                          d=&quot;M5.293 8.293a1 1 0 0 1 1.32-.083l.094.083L12 13.585l5.293-5.292a1 1 0 0 1 1.32-.083l.094.083a1 1 0 0 1 .083 1.32l-.083.094-6 6a1 1 0 0 1-1.32.083l-.094-.083-6-6a1 1 0 0 1 0-1.414Z&quot;<br>                          clip-rule=&quot;evenodd&quot;&gt;&lt;/path&gt;<br>                &lt;/svg&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;&quot;&gt;<br>                &lt;div class=&quot;iompba0 iompba3 animated _1ukdc9c4 _1ukdc9c5&quot; id=&quot;audiovisualcommunication&quot;<br>                     aria-labelledby=&quot;audiovisualcommunication-header&quot; role=&quot;region&quot;&gt;<br>                    &lt;div class=&quot;iompba0 iompba3 _1ukdc9cc _1ukdc9ch _1ukdc9ce&quot;&gt;<br>                        &lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc _1lalutrnu _1lalutrnv _1lalutrnw _1lalutrnx _1lalutrny _1lalutrnz _1lalutr31i&quot;&gt;<br>                            &lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc _1lalutrm0 _1lalutrm1 _1lalutrn8 _1lalutrn9 _1lalutrna _1lalutrnb _1lalutr31i&quot;&gt;<br>                                &lt;span class=&quot;iompba0 _1lalutrg0 _1tlv1fe8g a6hzxte a6hzxt0 a6hzxt0&quot;&gt;Inputs&lt;/span&gt;<br>                                &lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc _1lalutrn0 _1lalutrn1 _1lalutrn2 _1lalutrn3 _1lalutrn4 _1lalutrn5 _1lalutr31i _1lalutr21o _1lalutr21p _1lalutr222 _1lalutr223 _1lalutr224 _1lalutr225&quot;&gt;<br>                                    &lt;span class=&quot;iompba0 _1lalutrg0 _1tlv1fe8e a6hzxte a6hzxt0 a6hzxt0&quot;&gt;Aux input USB socket &lt;/span&gt;&lt;span<br>                                        class=&quot;iompba0 _1lalutrg0 _1tlv1fe8e a6hzxte a6hzxt0 a6hzxt0&quot;&gt;HDMI input for audio/video&lt;/span&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc _1lalutrm0 _1lalutrm1 _1lalutrn8 _1lalutrn9 _1lalutrna _1lalutrnb _1lalutr31i&quot;&gt;<br>                                &lt;span class=&quot;iompba0 _1lalutrg0 _1tlv1fe8g a6hzxte a6hzxt0 a6hzxt0&quot;&gt;Bluetooth&lt;/span&gt;<br>                                &lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc _1lalutrn0 _1lalutrn1 _1lalutrn2 _1lalutrn3 _1lalutrn4 _1lalutrn5 _1lalutr31i _1lalutr21o _1lalutr21p _1lalutr222 _1lalutr223 _1lalutr224 _1lalutr225&quot;&gt;<br>                                    &lt;span class=&quot;iompba0 _1lalutrg0 _1tlv1fe8e a6hzxte a6hzxt0 a6hzxt0&quot;&gt;Bluetooth&lt;/span&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc _1lalutrm0 _1lalutrm1 _1lalutrn8 _1lalutrn9 _1lalutrna _1lalutrnb _1lalutr31i&quot;&gt;<br>                                &lt;span class=&quot;iompba0 _1lalutrg0 _1tlv1fe8g a6hzxte a6hzxt0 a6hzxt0&quot;&gt;Controls&lt;/span&gt;<br>                                &lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc _1lalutrn0 _1lalutrn1 _1lalutrn2 _1lalutrn3 _1lalutrn4 _1lalutrn5 _1lalutr31i _1lalutr21o _1lalutr21p _1lalutr222 _1lalutr223 _1lalutr224 _1lalutr225&quot;&gt;<br>                                    &lt;span class=&quot;iompba0 _1lalutrg0 _1tlv1fe8e a6hzxte a6hzxt0 a6hzxt0&quot;&gt;Multi-function control screen - colour&lt;/span&gt;&lt;span<br>                                        class=&quot;iompba0 _1lalutrg0 _1tlv1fe8e a6hzxte a6hzxt0 a6hzxt0&quot;&gt;Speed dependant volume stereo&lt;/span&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc _1lalutrm0 _1lalutrm1 _1lalutrn8 _1lalutrn9 _1lalutrna _1lalutrnb _1lalutr31i&quot;&gt;<br>                                &lt;span class=&quot;iompba0 _1lalutrg0 _1tlv1fe8g a6hzxte a6hzxt0 a6hzxt0&quot;&gt;CD / DVD&lt;/span&gt;<br>                                &lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc _1lalutrn0 _1lalutrn1 _1lalutrn2 _1lalutrn3 _1lalutrn4 _1lalutrn5 _1lalutr31i _1lalutr21o _1lalutr21p _1lalutr222 _1lalutr223 _1lalutr224 _1lalutr225&quot;&gt;<br>                                    &lt;span class=&quot;iompba0 _1lalutrg0 _1tlv1fe8e a6hzxte a6hzxt0 a6hzxt0&quot;&gt;CD player&lt;/span&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc _1lalutrm0 _1lalutrm1 _1lalutrn8 _1lalutrn9 _1lalutrna _1lalutrnb _1lalutr31i&quot;&gt;<br>                                &lt;span class=&quot;iompba0 _1lalutrg0 _1tlv1fe8g a6hzxte a6hzxt0 a6hzxt0&quot;&gt;Speakers&lt;/span&gt;<br>                                &lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc _1lalutrn0 _1lalutrn1 _1lalutrn2 _1lalutrn3 _1lalutrn4 _1lalutrn5 _1lalutr31i _1lalutr21o _1lalutr21p _1lalutr222 _1lalutr223 _1lalutr224 _1lalutr225&quot;&gt;<br>                                    &lt;span class=&quot;iompba0 _1lalutrg0 _1tlv1fe8e a6hzxte a6hzxt0 a6hzxt0&quot;&gt;6 speaker stereo&lt;/span&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;iompba0 iompba3  _1ukdc9c9&quot;&gt;<br>                    &lt;div class=&quot;iompba0 iompba3 _1xd2s7e0 _1xd2s7e1 _1xd2s7e3&quot; role=&quot;separator&quot;&gt;&lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;iompba0 iompba3 _1ukdc9ck _1ukdc9cl _1ukdc9co&quot;&gt;<br>            &lt;div class=&quot;iompba0 iompba3 _1ukdc9cq _1ukdc9cr _1ukdc9cu  _1ukdc9cz&quot; id=&quot;safetysecurity-header&quot;<br>                 aria-controls=&quot;safetysecurity&quot; aria-expanded=&quot;false&quot; role=&quot;button&quot; tabindex=&quot;0&quot;&gt;Safety &amp;amp; Security<br>                &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;24&quot; height=&quot;24&quot; viewBox=&quot;0 0 24 24&quot;<br>                     class=&quot;iompba0 iompba3  _1mgmi6k2&quot; fill=&quot;currentColor&quot; aria-hidden=&quot;true&quot;&gt;<br>                    &lt;path fill-rule=&quot;evenodd&quot;<br>                          d=&quot;M5.293 8.293a1 1 0 0 1 1.32-.083l.094.083L12 13.585l5.293-5.292a1 1 0 0 1 1.32-.083l.094.083a1 1 0 0 1 .083 1.32l-.083.094-6 6a1 1 0 0 1-1.32.083l-.094-.083-6-6a1 1 0 0 1 0-1.414Z&quot;<br>                          clip-rule=&quot;evenodd&quot;&gt;&lt;/path&gt;<br>                &lt;/svg&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;&quot;&gt;<br>                &lt;div class=&quot;iompba0 iompba3 animated _1ukdc9c4 _1ukdc9c5&quot; id=&quot;safetysecurity&quot;<br>                     aria-labelledby=&quot;safetysecurity-header&quot; role=&quot;region&quot;&gt;<br>                    &lt;div class=&quot;iompba0 iompba3 _1ukdc9cc _1ukdc9ch _1ukdc9ce&quot;&gt;<br>                        &lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc _1lalutrnu _1lalutrnv _1lalutrnw _1lalutrnx _1lalutrny _1lalutrnz _1lalutr31i&quot;&gt;<br>                            &lt;div class=&quot;iompba0 iompba3 _1lalutrfo _1lalutrhc _1lalutrm0 _1lalutrm1 _1lalutrn8 _1lalutrn9 _1lalutrna _1lalutrnb _1lalutr31i&quot;&gt;<br>                                &lt;span class=&quot;iompba0 _1lalutrg0 _1tlv1fe8g a6hzxte a6hzxt0 a6hzxt0&quot;&gt;Airbags&lt;/span&gt;</pre><h4>Part 3 — Print our headers</h4><p>Let’s test this theory and print out our headers</p><pre>#!/usr/bin/env python<br><br># Imports<br>import sys<br>from bs4 import BeautifulSoup<br>from ruamel.yaml import YAML<br><br># Set HTML Content<br>html_content = &quot;&quot;&quot;<br>INSERT HTML DIV ELEMENT HERE<br>&quot;&quot;&quot;<br><br># Create a BeautifulSoup object<br>soup = BeautifulSoup(html_content, &#39;html.parser&#39;)<br><br># Create a dictionary to hold the YAML data<br>yaml_data = {}<br><br># Iterate over each main header [&#39;Audio, visual &amp; communication, &#39;Safety &amp; Security&#39;, ...]<br>for header_div in soup.find_all(&#39;div&#39;, id=lambda x: x and x.endswith(&#39;-header&#39;)):<br>    # Get header name<br><br>    ### DEBUG ###<br>    print(header_div.text.strip() + &quot;:&quot;)<br>    #############</pre><p>Gives us the following output</p><pre>Audio, visual &amp; communication:<br>Safety &amp; Security:<br>Comfort &amp; convenience:<br>Lights &amp; windows:<br>Interior:<br>Seating:<br>Instruments &amp; controls:<br>Exterior:<br>Body:<br>Electrical:<br>Engine:<br>Transmission &amp; drivetrain:<br>Steering:<br>Brakes:<br>Wheels &amp; tyres:</pre><p>Great start!</p><h4>Part 4 — Finding the subheadings</h4><p>Finding our subheadings is less straight forward — how do our elements for the subheading <em>Inputs</em> compare to the item <em>Aux input USB Socket</em>?</p><p>If we inspect closely on the class items, the third item differs, _1tlv1fe8gagainst _1tlv1fe8efor <em>Inputs</em> and <em>Aux input USB Socket</em> respectively.</p><p>Rather than ‘hard-code’ this class name, we can assume that the heading will always come before a subheading.</p><p>To prove this, we can collect the class from the first item in the content and then search for all spans of this class.</p><pre>#!/usr/bin/env python<br><br># Imports<br>import sys<br>from bs4 import BeautifulSoup<br>from ruamel.yaml import YAML<br><br># Set HTML Content<br>html_content = &quot;&quot;&quot;<br>INSERT HTML DIV ELEMENT HERE<br>&quot;&quot;&quot;<br><br># Create a BeautifulSoup object<br>soup = BeautifulSoup(html_content, &#39;html.parser&#39;)<br><br># Create a dictionary to hold the YAML data<br>yaml_data = {}<br><br># Iterate over each main header [&#39;Audio, visual &amp; communication, &#39;Safety &amp; Security&#39;, ...]<br>for header_div in soup.find_all(&#39;div&#39;, id=lambda x: x and x.endswith(&#39;-header&#39;)):<br>    # Get header name<br>    category_name = header_div.text.strip()<br>  <br>    # Collect content div<br>    content_div = soup.find(&#39;div&#39;, id=header_div.attrs[&#39;id&#39;].replace(&quot;-header&quot;, &quot;&quot;))<br><br>    # Get class name for subheadings<br>    subheadings_class = &#39; &#39;.join(content_div.find_next(&quot;span&quot;).attrs[&#39;class&#39;])<br><br>    ### DEBUG ###<br>    # Print the first category and it&#39;s sub headings<br>    print(category_name + &quot;:&quot;)<br>    for span in content_div.find_all(&#39;span&#39;):<br>        if &#39; &#39;.join(span.attrs[&#39;class&#39;]) == subheadings_class:<br>          print(&quot;  &quot; + span.text.strip() + &quot;:&quot;)<br>    break<br>    ############</pre><p>Gives us</p><pre>Audio, visual &amp; communication:<br>  Inputs:<br>  Bluetooth:<br>  Controls:<br>  CD / DVD:<br>  Speakers:</pre><p>Woo-hoo! Now to also iterate over the items in each sub-category</p><h3>Part 5 — Collect the subcategories and generating our YAML file</h3><p>We make the assumption that if the class is not a subheadings class, then it’s an item.</p><p>If we come across another subheading in our ‘span’ for-loop, we assume that it’s a new sub-category!</p><p>We can also now use our ruamel.yaml library to present our dictionary as a yaml file.</p><pre>#!/usr/bin/env python<br><br># Imports<br>import sys<br>from bs4 import BeautifulSoup<br>from ruamel.yaml import YAML<br><br># Set HTML Content<br>html_content = &quot;&quot;&quot;<br>INSERT DIV CONTENT HERE<br>&quot;&quot;&quot;<br><br># Create a BeautifulSoup object<br>soup = BeautifulSoup(html_content, &#39;html.parser&#39;)<br><br># Create a dictionary to hold the YAML data<br>yaml_data = {}<br><br># Iterate over each main header [&#39;Audio, visual &amp; communication, &#39;Safety &amp; Security&#39;, ...]<br>for header_div in soup.find_all(&#39;div&#39;, id=lambda x: x and x.endswith(&#39;-header&#39;)):<br>    # Get header name<br>    category_name = header_div.text.strip()<br><br>    # Find content<br>    content_div = soup.find(&#39;div&#39;, id=header_div.attrs[&#39;id&#39;].replace(&quot;-header&quot;, &quot;&quot;))<br><br>    # Get class name for subheadings<br>    subheadings_class = &#39; &#39;.join(content_div.find_next(&quot;span&quot;).attrs[&#39;class&#39;])<br><br>    # Initialise the category name and contents<br>    subheading = None<br>    category_data = {}<br><br>    for span in content_div.find_all(&#39;span&#39;):<br>        if &#39; &#39;.join(span.attrs[&#39;class&#39;]) == subheadings_class:<br>            # Set the subheading<br>            subheading = span.text.strip()<br>            # Initialise the category data content<br>            category_data[subheading] = []<br>            continue<br>        if subheading is None:<br>            continue<br>        category_data[subheading].append(span.text.strip())<br><br>    # Add the category and its items to the dictionary<br>    yaml_data[category_name] = category_data<br><br># Convert the dictionary into a YAML document<br>yaml = YAML()<br><br>yaml.block_seq_indent = 2<br><br>yaml.dump(yaml_data, sys.stdout)</pre><p>Let’s save this python script as ‘car_1.py’</p><p>Now run python3 car_1.py &gt; car_1.yaml</p><h4>Part 6 — Repeat for our second car</h4><p>Repeat part 1 and part 5 for our second car, save this file as car_2.py and run python3 car_2.py &gt; car_2.yaml</p><h4>Part 7 — Running dyff</h4><p>Install <a href="https://github.com/homeport/dyff#installation">dyff as per the instructions</a>, noting to avoid ‘snap’ installations if possible.</p><p>Use type dyff on your terminal to ensure dyff has been correctly installed.</p><p>Now run dyff between car_1.yaml car_2.yaml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*QRK-B-JMgZvFOpaHplCmSg.png" /><figcaption>Differences between the standard Honda HR-V 2016 VTi and the Honda HR-V 2016 VTiL</figcaption></figure><h4>Conclusion</h4><p>Automating this process obviously took a lot longer than doing one comparison by hand. However, now that we have a process for quickly generating converting HTML content of the carsales.com.au site into YAML format for our cars of interest, we can quickly compare features, or specifications between two cars of interest!</p><p>I hope this helps someone else in either the near (or me in the hopefully very distant future)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b79d4b68b13e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using conda to version control aws-cdk]]></title>
            <link>https://medium.com/@awlucattini_60867/using-conda-to-version-control-aws-cdk-89c542bb6dc5?source=rss-5b91b179ba57------2</link>
            <guid isPermaLink="false">https://medium.com/p/89c542bb6dc5</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[conda]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Alexis Lucattini]]></dc:creator>
            <pubDate>Mon, 13 Dec 2021 17:06:46 GMT</pubDate>
            <atom:updated>2021-12-15T17:58:03.320Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using conda to version control cdk</h3><p><em>This article may offend a lot of people. I am okay with that.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9__OfNv3sUQx7y7c3_AnJA.png" /><figcaption>Image source: <a href="https://openclipart.org/detail/218159/python">Python — Openclipart</a> / edits by author through Paint3D</figcaption></figure><h4>Background / Justification</h4><ul><li>Installing CDK globally isn’t appropriate when a user has both cdk v1 and v2 projects.</li><li>As an alternative, the cdk version ought to be bound to the project.</li><li>I use multiple computers and <a href="https://medium.com/@awlucattini_60867/i-backup-my-cloned-github-repositories-on-onedrive-54b176192950">sync my local GitHub repositories between them over OneDrive</a>.</li><li>This is slightly problematic as the venv folder inside a cdk project is not compatible between my mac and windows machines.</li><li>This means project dependencies also need to be installed locally</li><li>I use <a href="https://conda.io/">conda</a> for a lot of my projects and hence don’t see why I shouldn’t use it for my cdk projects.</li><li>This applies even if the cdk project is not in python.</li></ul><h4>Step 1: Create the environment</h4><p>Creating / setting a conda environment for cdk.</p><p>In this example we will call the conda env workshop--cdk .<br>I like to add the --cdk suffix to all of my cdk conda envs.</p><p>This is often to distinguish them from the project logic itself which may be called workshop.</p><pre>$ conda create --yes \<br>    --name &#39;workshop--cdk&#39; \<br>    --channel &#39;conda-forge&#39; \<br>    nodejs==&quot;16.13.0&quot; \<br>    pip</pre><h4>Step 2: Add in the activation script</h4><p>Activate the environment and install aws-cdk.</p><pre>conda activate workshop--cdk</pre><p>Let’s ensure that the node environment variables are set <br>when we activate the cdk project.</p><p>We can do that by adding in a quick shell script into the conda environment’s activate.d directory.</p><p>Firstly let’s create the activate.d with the following.</p><pre>$ mkdir -p &quot;${CONDA_PREFIX}/etc/conda/activate.d&quot;</pre><p>Now let’s add in the activation script into that directory under the name node.sh with the following contents:</p><pre>#!/usr/bin/env bash<br><br># Set both NPM_CONFIG_PREFIX and NODE_PATH env vars<br>export NPM_CONFIG_PREFIX=&quot;${CONDA_PREFIX}&quot;<br>export NODE_PATH=&quot;${NPM_CONFIG_PREFIX}/node_modules:${NODE_PATH}&quot;</pre><pre># Create the node modules directory<br>mkdir -p &quot;${NPM_CONFIG_PREFIX}/node_modules&quot;</pre><pre># Add in the bin path for each of the node modules that we install<br>for bin_path in `find &quot;${NPM_CONFIG_PREFIX}/node_modules&quot; -mindepth 2 -maxdepth 2 -name &quot;bin&quot;`; do<br>    export PATH=&quot;${bin_path}:${PATH}&quot;<br>done</pre><h4>Step 3: Re-activate the environment</h4><p>This ensures that all of our environment scripts are activated correctly.</p><pre>$ conda deactivate<br><br>$ conda activate workshop--cdk</pre><h4>Step 4: Install aws-cdk</h4><p>For this app, we will install version 2.<br>We need to set the prefix for the first npm installation into this directory.</p><pre>$ npm install aws-cdk@^2 --prefix &quot;${NPM_CONFIG_PREFIX}&quot;</pre><p>Activate and deactivate the environment</p><pre>$ conda deactivate<br>$ conda activate workshop--cdk</pre><h4>Step 5: Test out your cdk version</h4><p>We can see that the cdk is the right cdk (inside the conda prefix) and is the version we expect.</p><pre>$ which cdk<br>/home/alexiswl/miniforge3/envs/cdk--cdk-workshop-v2/node_modules/aws-cdk/bin/cdk</pre><pre>$ cdk --version<br>2.1.0 (build f4f18b1)</pre><h4>Step 6: Create your cdk app</h4><p>Change directory to where you wish to initialise your app and then run cdk init .</p><pre>$ cd /path/to/cdk/dir<br>$ cdk init sample-app --language python</pre><h4>Step 7 (optional): Install project requirements into conda</h4><p>If we set the project as a <em>python </em>project in the previous step, we need to install the requirements into our conda env. Typescript projects can skip this step.</p><pre>pip install -r requirements.txt</pre><p>And we’re done!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89c542bb6dc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing YAML files with python]]></title>
            <link>https://medium.com/data-science/writing-yaml-files-with-python-a6a7fc6ed6c3?source=rss-5b91b179ba57------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6a7fc6ed6c3</guid>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[yaml]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alexis Lucattini]]></dc:creator>
            <pubDate>Sat, 23 Oct 2021 04:52:16 GMT</pubDate>
            <atom:updated>2021-10-24T16:56:25.336Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using ruamel.yaml to annotate configuration files</h4><p><em>This article expects the reader to have a basic understanding of the </em><a href="https://docs.python.org/3/"><em>python programming language</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkfqkaJDBO4OFivpB4Qc5g.jpeg" /><figcaption>Src: <a href="https://pxhere.com/en/photo/492303">https://pxhere.com/en/photo/492303</a></figcaption></figure><p>Yaml files have been around for over twenty years now¹. They’re extremely useful for showing data structures and are a popular format for configuration files. From <a href="https://aws.amazon.com/cloudformation/">AWS CloudFormation</a>², <a href="https://www.commonwl.org/user_guide/">Common Workflow Language</a>³ to <a href="https://www.home-assistant.io/">Home Assistant</a>⁴, yamls are a fundamental backbone for configuration files of the internet. They’re significantly easier to read than other formats like <a href="https://en.wikipedia.org/wiki/JSON">JSON</a>, support comments and easy to version control — try running git merge on two slightly different json files and you’ll appreciate what I mean. Despite this, when it comes to writing yaml files in our beloved language python, our options are quite limited. Only <a href="https://pyyaml.org/wiki/PyYAMLDocumentation">PyYAML</a> and <a href="https://yaml.readthedocs.io/en/latest/">ruamel.yaml</a> have registries in the <a href="https://matrix.yaml.io/">yaml conformance test matrix</a>, and of these only ruamel.yaml supports handling comments.</p><p>Being able to write comments into your configuration files is particularly useful if user may need to tinker with said files manually at a later stage. Another advantage is enum support, by adding comments to a yaml file, a user can see what all of the available options are for a setting without having to scroll through documentation to find them! Even better, comments in configuration files can let one include links to the documentation on where they can read up on that section of the configuration file!</p><p>So let’s get started with writing some yaml through python</p><h4>An example yaml file:</h4><pre>employees:<br>  - name: Jeffrey Bezos<br>    job title: CEO<br>    annual salary (USD): 1000000000000<br>  - name: John Smith<br>    job title: factory worker<br>    annual salary (USD): 20000</pre><p>This yaml file is the python equivalent of a dictionary with one key <em>“</em>employees” that contains a list of two elements. <br>Each element in the nested list contains the three same keys: “name”, “job title” and “annual salary (USD)”.</p><p>One of the cool things about yaml files is being able to annotate them with comments using the “#” symbol</p><pre>employees:<br>  # Start with CEO<br>  - name: Jeffrey Bezos  # Goes by Jeff<br>    job title: CEO # ...entrepreneur, born in 1964... <br>    annual salary (USD): 1000000000000  # This is too much<br>  # List of factory workers below<br>  - name: John Smith<br>    job title: factory worker<br>    annual salary (USD): 20000  # Probably deserves a raise</pre><h4>Installation of ruamel.yaml</h4><p>Below we will be trying to load this yaml file into python with <a href="https://yaml.readthedocs.io/en/latest/">ruamel.yaml</a>. If you need to install ruamel.yaml, we will be working with version 0.17.4 , here a few commands for assistance.</p><p>Installation option 1:</p><pre>pip install ruamel.yaml==0.17.4</pre><p>Installation option 2:</p><pre>conda install -c conda-forge ruamel.yaml==0.17.4</pre><h4>Importing ruamel into python and loading the yaml file</h4><pre># Imports<br>from ruamel.yaml.main import round_trip_load as yaml_load</pre><pre>employees_dict = yaml_load(&quot;&quot;&quot;<br>employees:<br>  # Start with CEO<br>  - name: Jeffrey Bezos  # Goes by Jeff<br>    job title: CEO # / Entrepreneur, born in 1964...<br>    annual salary (USD): 1000000000000  # This is too much<br>  # List of factory workers below<br>  - name: John Smith<br>    job title: factory worker<br>    annual salary (USD): 20000  # Probably deserves a raise<br>&quot;&quot;&quot;)</pre><pre>print(employees_dict)<br>print(f&quot;Type: {type(employees_dict}&quot;)</pre><p>Output:</p><pre>ordereddict([(&#39;employees&#39;, [ordereddict([(&#39;name&#39;, &#39;Jeffrey Bezos&#39;), (&#39;job title&#39;, &#39;CEO&#39;), (&#39;annual salary (USD)&#39;, 1000000000000)]), ordereddict([(&#39;name&#39;, &#39;John Smith&#39;), (&#39;job title&#39;, &#39;factory worker&#39;), (&#39;annual salary (USD)&#39;, 20000)])])])<br>Type: &lt;class &#39;ruamel.yaml.comments.CommentedMap&#39;&gt;</pre><p>Cool! That was pretty simple. Now let’s try building a yaml file from scratch!</p><h3>Building a yaml file from scratch</h3><h4>Let’s first set out our imports and global variables</h4><pre># Regular imports<br>from copy import deepcopy<br><br># Yaml loaders and dumpers<br>from ruamel.yaml.main import \<br>    round_trip_load as yaml_load, \<br>    round_trip_dump as yaml_dump<br><br># Yaml commentary<br>from ruamel.yaml.comments import \<br>    CommentedMap as OrderedDict, \<br>    CommentedSeq as OrderedList<br><br># For manual creation of tokens<br>from ruamel.yaml.tokens import CommentToken<br>from ruamel.yaml.error import CommentMark</pre><pre># Globals<br># Number of spaces for an indent <br>INDENTATION = 2 <br># Used to reset comment objects<br>tsRESET_COMMENT_LIST = [None, [], None, None]</pre><p>And create a shopping list using the OrderedDict<em> </em>and OrderedList attributes.</p><pre>shopping_list = OrderedDict({<br>    &quot;Shopping List&quot;: OrderedDict({<br>        &quot;eggs&quot;: OrderedDict({<br>            &quot;type&quot;: &quot;free range&quot;,<br>            &quot;brand&quot;: &quot;Mr Tweedy&quot;,<br>            &quot;amount&quot;: 12<br>        }),<br>        &quot;milk&quot;: OrderedDict({<br>            &quot;type&quot;: &quot;pasteurised&quot;,<br>            &quot;litres&quot;: 1.5,<br>            &quot;brands&quot;: OrderedList([<br>                &quot;FarmFresh&quot;,<br>                &quot;FarmHouse gold&quot;,<br>                &quot;Daisy The Cow&quot;<br>            ])<br>        })<br>    })<br>})</pre><pre># Dump the yaml file<br>print(yaml_dump(shopping_list, preseve_quotes=True))</pre><p>Output:</p><pre>Shopping List:<br>  eggs:<br>    type: free range<br>    brand: Mr Tweedy<br>    amount: 12<br>  milk:<br>    type: pasteurised<br>    litres: 1.5<br>    brands:<br>      - FarmFresh<br>      - FarmHouse gold<br>      - Daisy The Cow</pre><p>Creating our data structure was quite tedious. It’s also not likely our data structure we wish to write out to yaml would already be in this format. It’s much more likely to be in standard dictionary and/or list format. That’s okay, we can dump and load instead to convert standard dict and list formats into our OrderedList (CommentedMap) and OrderedList (CommentedSeq).</p><pre># Original object<br>shopping_list = {<br>    &quot;Shopping List&quot;: {<br>        &quot;eggs&quot;: {<br>            &quot;type&quot;: &quot;free range&quot;,<br>            &quot;brand&quot;: &quot;Mr Tweedy&quot;,<br>            &quot;amount&quot;: 12<br>        },<br>        &quot;milk&quot;: {<br>            &quot;type&quot;: &quot;pasteurised&quot;,<br>            &quot;litres&quot;: 1.5,<br>            &quot;brands&quot;: [<br>                &quot;FarmFresh&quot;,<br>                &quot;FarmHouse gold&quot;,<br>                &quot;Daisy The Cow&quot;<br>            ]<br>        }<br>    }<br>}<br><br># To yaml object<br>shopping_list = yaml_load(yaml_dump(shopping_list), preseve_quotes=True)</pre><pre># Show object type<br>print(type(shopping_list))</pre><p>Output:</p><pre>&lt;class &#39;ruamel.yaml.comments.CommentedMap&#39;&gt;</pre><p>Perfect!</p><h4>Add a header to the yaml file</h4><p>We can use the yaml_set_start_comment attribute which will add a comment above the map object</p><pre>shopping_list.yaml_set_start_comment(&quot;Shopping Lists for date: &quot;<br>                                     &quot;23 Oct 2021&quot;)<br>print(yaml_dump(shopping_list, <br>                indent=INDENTATION, <br>                block_seq_indent=INDENTATION))</pre><p>Output:</p><pre># Shopping Lists for date: 21 Oct 2021<br>Shopping List:<br>  eggs:<br>    type: free range<br>    brand: Mr Tweedy<br>    amount: 12<br>  milk:<br>    type: pasteurised<br>    litres: 1.5<br>    brands:<br>      - FarmFresh<br>      - FarmHouse gold<br>      - Daisy The Cow</pre><h4>Add a comment before a nested key</h4><p>Lets say we really don’t want to forget eggs, let’s write above the egg key ‘Please don’t forget eggs!’. Since the ‘Shopping List’ attribute of the shopping_list object is also an OrderedDict or OrderedList, we can use the yaml_set_comment_before_after_key method on the Shopping Listattribute.</p><pre>shopping_list.get(&quot;Shopping List&quot;).\<br>    yaml_set_comment_before_after_key(key=&quot;eggs&quot;,<br>                                      before=&quot;Please don&#39;t forget &quot;<br>                                             &quot;eggs!&quot;)<br>print(yaml_dump(shopping_list, <br>                indent=INDENTATION, <br>                block_seq_indent=INDENTATION))</pre><p>Output:</p><pre># Shopping Lists for date: 21 Oct 2021<br>Shopping List:<br>#  Please don&#39;t forget eggs!<br>  eggs:<br>    type: free range<br>    brand: Mr Tweedy<br>    amount: 12<br>  milk:<br>    type: pasteurised<br>    litres: 1.5<br>    brands:<br>      - FarmFresh<br>      - FarmHouse gold<br>      - Daisy The Cow</pre><p>Ugh, this isn’t ideal! That comment should be indented. Let’s delete it and make sure to use the indent parameter next time. To delete the comment, we need to reset the <em>eggs</em> key in the ca attribute of the OrderedDict and try again.</p><h4>Deleting a comment object</h4><pre>shopping_list.get(&quot;Shopping List&quot;).ca.\<br>    items[&quot;eggs&quot;] = deepcopy(RESET_COMMENT_LIST)<br>print(yaml_dump(shopping_list, <br>                indent=INDENTATION, <br>                block_seq_indent=INDENTATION))</pre><p>Output:</p><pre># Shopping Lists for date: 21 Oct 2021<br>Shopping List:<br>  eggs:<br>    type: free range<br>    brand: Mr Tweedy<br>    amount: 12<br>  milk:<br>    type: pasteurised<br>    litres: 1.5<br>    brands:<br>      - FarmFresh<br>      - FarmHouse gold<br>      - Daisy The Cow</pre><p>Let’s try that again with the indent parameter (set to 2 spaces)</p><pre>object_depth = 1 # Shopping List<br><br>shopping_list.get(&quot;Shopping List&quot;).\<br>    yaml_set_comment_before_after_key(<br>        key=&quot;eggs&quot;,<br>        before=&quot;Don&#39;t forget the eggs&quot;,<br>        indent=object_depth*INDENTATION<br>    )</pre><pre>print(yaml_dump(shopping_list, <br>                indent=INDENTATION, <br>                block_seq_indent=INDENTATION))</pre><p>Output:</p><pre># Shopping Lists for date: 21 Oct 2021<br>Shopping List:<br>  # Don&#39;t forget the eggs<br>  eggs:<br>    type: free range<br>    brand: Mr Tweedy<br>    amount: 12<br>  milk:<br>    type: pasteurised<br>    litres: 1.5<br>    brands:<br>      - FarmFresh<br>      - FarmHouse gold<br>      - Daisy The Cow</pre><h4>Add a comment after a key</h4><p>We can also add a comment after a key too</p><pre>object_depth = 2 # Shopping List -&gt; Eggs<br>shopping_list.get(&quot;Shopping List&quot;).\<br>    yaml_set_comment_before_after_key(<br>        key=&quot;eggs&quot;,<br>        after=&quot;Please don&#39;t forget eggs!&quot;,<br>        after_indent=object_depth*INDENTATION<br>    )<br>print(yaml_dump(shopping_list, <br>                indent=INDENTATION, <br>                block_seq_indent=INDENTATION))</pre><p>Output:</p><pre># Shopping Lists for date: 21 Oct 2021<br>Shopping List:<br>  # Don&#39;t forget the eggs<br>  eggs:<br>    # Please don&#39;t forget eggs!<br>    type: free range<br>    brand: Mr Tweedy<br>    amount: 12<br>  milk:<br>    type: pasteurised<br>    litres: 1.5<br>    brands:<br>      - FarmFresh<br>      - FarmHouse gold<br>      - Daisy The Cow</pre><h4>Lets add an end-of-line comment to a key</h4><p>Put in a courteous reminder that two litres of milk is just too much milk!</p><pre>shopping_list.get(&quot;Shopping List&quot;).\<br>    get(&quot;milk&quot;).\<br>    yaml_add_eol_comment(<br>        key=&quot;litres&quot;,<br>        comment=&quot;2 litres is too much milk!&quot;<br>    )</pre><pre>print(yaml_dump(shopping_list, <br>                indent=INDENTATION, <br>                block_seq_indent=INDENTATION))</pre><p>Output:</p><pre># Shopping Lists for date: 21 Oct 2021<br>Shopping List:<br>  # Don&#39;t forget the eggs<br>  eggs:<br>    # Please don&#39;t forget eggs!<br>    type: free range<br>    brand: Mr Tweedy<br>    amount: 12<br>  milk:<br>    type: pasteurised<br>    litres: 1.5  # 2 litres is too much milk!<br>    brands:<br>      - FarmFresh<br>      - FarmHouse gold<br>      - Daisy The Cow</pre><h4>Add a comment in a list</h4><p>Lets note that <em>FarmHouse gold</em> and <em>Daisy The Cow</em> are last resort options. By using the before parameter on the index of the FarmHouse gold item of the list. For comments in lists, only the before parameter is supported.</p><pre>object_depth = 3 # Shopping List -&gt; Milk -&gt; Brands<br>shopping_list.get(&quot;Shopping List&quot;).\<br>    get(&quot;milk&quot;).\<br>    get(&quot;brands&quot;).\<br>    yaml_set_comment_before_after_key(<br>        key=1, # &quot;Farmhouse gold&quot; is the second item in the list<br>        before=&quot;Last Resorts&quot;,<br>        indent=object_depth*INDENTATION<br>    )<br>print(yaml_dump(shopping_list, <br>                indent=INDENTATION, <br>                block_seq_indent=INDENTATION))</pre><p>Output:</p><pre># Shopping Lists for date: 21 Oct 2021<br>Shopping List:<br>  # Don&#39;t forget the eggs<br>  eggs:<br>    type: free range<br>    brand: Mr Tweedy<br>    amount: 12<br>  milk:<br>    type: pasteurised<br>    litres: 1.5  # 2 litres is too much milk!<br>    brands:<br>      - FarmFresh<br>      # Last Resorts<br>      - FarmHouse gold<br>      - Daisy The Cow</pre><h4>Add an end-of-line comment to an item in a list</h4><pre>object_depth = 3 # Shopping List -&gt; Milk -&gt; Brands<br>shopping_list.get(&quot;Shopping List&quot;).\<br>    get(&quot;milk&quot;).\<br>    get(&quot;brands&quot;).\<br>    yaml_add_eol_comment(<br>        key=1, <br>        comment=&quot;Too creamy&quot;<br>    )<br>print(yaml_dump(shopping_list, <br>                indent=INDENTATION, <br>                block_seq_indent=INDENTATION))</pre><p>Output:</p><pre>TypeError: &#39;CommentToken&#39; object is not iterable</pre><p>Oh no! This is a <a href="https://sourceforge.net/p/ruamel-yaml/tickets/404/">known bug</a>, and we’re going to have to use the ca attribute of the brands object to add this to the list.</p><h4>A breakdown of the ca attribute:</h4><p>Let’s see what we’re dealing with first:</p><pre>print(shopping_list.get(&quot;Shopping List&quot;).get(&quot;milk&quot;).get(&quot;brands&quot;).ca)</pre><p>Output:</p><pre>Comment(<br>  start=None,<br>  items={<br>    1: [None, [CommentToken(&#39;# Last Resorts\n&#39;, col: 6)], None, None]<br>  })</pre><p>Only the first two elements in the values for the items attribute are used in a CommentedSeq. The first element is the eol comments, while the second one is the list of before comments. For a CommentedMap, the first element represents the ‘start comments’, the second element is the before comments, the third is the eol comments and the fourth is the after comments. This has been summarised in the <em>Resources</em> section of this article.</p><h4>Manually adding in a CommentToken object</h4><p>We need to set the first element of the items to be our desired comment. <br>When manually adding in a CommentToken object, we prefix with \ # and end with a new line character \n. <br>We initialise the start_mark parameter with a minimal CommentMark object and set the end_mark parameter to None.</p><pre>shopping_list.get(&quot;Shopping List&quot;).\<br>    get(&quot;milk&quot;).\<br>    get(&quot;brands&quot;).ca.\<br>    items[1][0] = CommentToken(value=&quot; # Too creamy\n&quot;,<br>                               start_mark=CommentMark(0),<br>                               end_mark=None)<br>print(yaml_dump(shopping_list, <br>                indent=INDENTATION, <br>                block_seq_indent=INDENTATION))</pre><p>Output:</p><pre># Shopping Lists for date: 21 Oct 2021<br>Shopping List:<br>  # Don&#39;t forget the eggs<br>  eggs:<br>    type: free range<br>    brand: Mr Tweedy<br>    amount: 12<br>  milk:<br>    type: pasteurised<br>    litres: 1.5  # 2 litres is too much milk!<br>    brands:<br>      - FarmFresh<br>      # Last Resorts<br>      - FarmHouse gold  # Too creamy<br>      - Daisy The Cow</pre><h3>A summary of workarounds</h3><p>From this, you can see that ruamel.yaml has some room for improvement:</p><ol><li>One needs to set the indentation when using the before or after parameters with the yaml_set_comment_before_after_key method. This also means one needs to know how deep the nested is on creation of the comment.</li><li>One cannot use the yaml_add_eol_comment method on an element in a list if a before comment already exists on said method.</li><li>At the time of writing this, the latest version of ruamel (0.17.16) had a bug such that many of the outputs omitted many of the comments.</li><li>There is nothing in the ruamel.yaml docs on writing comments into yaml files.</li></ol><h4>A small rant on my findings</h4><p>How does one of the internet’s most important configuration format structures not have a fully supported parser from one of the world’s most popular programming languages? I’m sure there must be thousands of python developers out there that have had the same thought as I have.</p><p>Before anyone is too quick to comment ‘<em>you should raise this with the developer</em>’, I have⁵ ⁶ ⁷. In doing so, I can assume why so many before me never bothered. ruamel.yaml is hosted on <a href="https://sourceforge.net/projects/ruamel-yaml/">SourceForge</a> and when visiting this website, you’ll feel like you’ve entered the 90s (from a UX context, the 90s is a bad place to be). Unlike GitHub, SourceForge doesn’t let you edit issues after creation. The interface is clunky, the search algorithm is way too sensitive when searching for an existing issue (everything comes up!) and the notification service is ancient — rather than a notifications tab, you’ll receive an email upon a new comment being added to your issue (including your own), alternatively you can subscribe to an RSS feed.</p><p>Whist PyYAML appears to have regained maintenance⁸, current developers are left in a sticky situation where many pieces of software rely on PyYAML without specifying a version⁹. Updating the code to merge / import much of the work done in ruamel.yaml such as support comments, YAML 1.2 format or other general improvements, come at the risk of breaking backwards compatibility and ergo many users’ code breaking. This would be a good lesson for those not version-controlling their dependencies, but I’m not sure everyone also sees it this way.</p><p>I personally don’t know what the right solution is, a new name like PyYAML2 that can onboard the work of ruamel.yaml while maintaining backwards compatibility for those using the set PyYAML? More support for ruamel.yaml?</p><p>This article is by no means an attack on the maintainers of PyYAML or ruamel.yaml. I do not envy them in the slightest and I sincerely hope more support is on its way. I also give full permission for this code to be copied / edited and used as documentation for handling yaml in python. At a minimum, I hope this article is at least useful to some developers out there wanting to write albeit limited and hacky commentary into yaml files and saves someone else from reverse engineering the source code through trial-and-error.</p><h4>Resources:</h4><p>StackOverflow: <a href="https://stackoverflow.com/questions/40704916/how-to-insert-a-comment-line-to-yaml-in-python-using-ruamel-yaml">https://stackoverflow.com/questions/40704916/how-to-insert-a-comment-line-to-yaml-in-python-using-ruamel-yaml</a></p><p>MyBinder.org: <a href="https://mybinder.org/v2/gist/alexiswl/7fe1b3a90d86313c9785992bd0ce6e19/HEAD">https://mybinder.org/v2/gist/alexiswl/7fe1b3a90d86313c9785992bd0ce6e19/HEAD</a></p><p>ruamel.yaml documentation: <a href="https://yaml.readthedocs.io/en/latest/">https://yaml.readthedocs.io/en/latest/</a></p><p>CommentToken Objects Structures:</p><ul><li>CommentedMap:<br>0: Comments set withyaml_set_start_comment method.<br>1: Comments set from yaml_set_comment_before_after_key method with beforeparameter.<br>2: Comments set from yaml_set_eol_comment <br>3: Comments set from yaml_set_comment_before_after_key method with afterparameter.</li><li>CommentedSeq:<br>0: Comments set from yaml_set_eol_comment<br>1: Comments set from yaml_set_comment_before_after_key method with beforeparameter.<br>2: Not Used<br>3: Not Used</li></ul><h4>References:</h4><p>[1]: <a href="https://yaml.org/about.html">https://yaml.org/about.html</a> <br>[2]: <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-formats.html">https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-formats.html</a><br>[3]: <a href="https://www.commonwl.org/user_guide/02-1st-example/index.html">https://www.commonwl.org/user_guide/02-1st-example/index.html</a><br>[4]: <a href="https://www.home-assistant.io/docs/configuration/yaml/">https://www.home-assistant.io/docs/configuration/yaml/</a><br>[5]: <a href="https://sourceforge.net/p/ruamel-yaml/tickets/400/">https://sourceforge.net/p/ruamel-yaml/tickets/400/</a><br>[6]: <a href="https://sourceforge.net/p/ruamel-yaml/tickets/402/">https://sourceforge.net/p/ruamel-yaml/tickets/402/</a><br>[7]: <a href="https://sourceforge.net/p/ruamel-yaml/tickets/404/">https://sourceforge.net/p/ruamel-yaml/tickets/404/</a><br>[8]: <a href="https://github.com/yaml/pyyaml/issues/31">https://github.com/yaml/pyyaml/issues/31</a><br>[9]: <a href="https://github.com/yaml/pyyaml/issues/46">https://github.com/yaml/pyyaml/issues/46</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6a7fc6ed6c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/writing-yaml-files-with-python-a6a7fc6ed6c3">Writing YAML files with python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating from Docker to Podman]]></title>
            <link>https://medium.com/@awlucattini_60867/migrating-from-docker-to-podman-8a862d7a84dd?source=rss-5b91b179ba57------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a862d7a84dd</guid>
            <category><![CDATA[podman]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Alexis Lucattini]]></dc:creator>
            <pubDate>Tue, 21 Sep 2021 23:32:43 GMT</pubDate>
            <atom:updated>2021-09-21T23:32:43.123Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building and pushing native built cross-platform images with podman</h4><h3>The Back Story:</h3><p>Contrary to Adele, my docker swarms DID have it all. The swarm comprised of a second-hand <a href="https://www.intel.com.au/content/www/au/en/products/details/nuc.html">intel-nuc</a> (amd64) running Ubuntu and a <a href="https://www.raspberrypi.org/">raspberry pi</a> (arm64) running Debian. I could, with one single buildx command, have a docker image built simultaneously across both devices with said images pushed as a multi-arch <a href="https://docs.docker.com/engine/reference/commandline/manifest/">manifest list</a> to <a href="http://dockerhub.com/">Docker Hub</a> (so ARM Macs and Intel computers could run my containers).</p><p>With Docker Desktop WSL2 integration crashing on my system twice last week, I was done. It was inevitable anyway. I would no longer, legally, be able to use Docker Desktop by January 2022 with their <a href="https://www.arnnet.com.au/article/690955/docker-desktop-no-longer-free-enterprise-users/">new licensing</a>. Furthermore, Docker Hub’s introduction of <a href="https://aws.amazon.com/blogs/containers/advice-for-customers-dealing-with-docker-hub-rate-limits-and-a-coming-soon-announcement/">rate limiting</a> on free accounts and updates to pricing on organisational accounts had also pushed us as a team to move to <a href="https://quay.io/">quay.io</a>. <br>My brilliant Docker swarm, multi-node / multi-arch ‘single-buildx-command’ deployment was <a href="https://github.com/quay/quay/discussions/878">not compatible with quay.io</a>. It too would also have to go.</p><p>It was a Friday. It was day 200-something of cumulative lockdown. It was time to cry… and channel that pain into energy. It would be needed in migrating from docker to <a href="https://podman.io/">podman</a>.</p><ul><li>Was this easy? No.</li><li>Are there pitfalls? Yes.</li><li>Am I satisfied? Of course! The system works and it’s here to stay.</li></ul><h4>Will you find the rest of this article useful?</h4><p>This article is for you if you meet the following criteria:</p><p>1. You use a Canonical-based linux distribution such as Ubuntu / Debian <br>2. You need to build multi-arch images and have devices with said architecture and would like to push them to image repositories such as quay.io<br>3. Like me, you don’t have the expertise to do item 2 with <a href="https://kubernetes.io/docs/home/">Kubernetes</a> or <a href="https://developers.redhat.com/products/openshift/">OpenShift</a>.</p><p>OR</p><p>You are just generally interested in the world of containers, please feel free to skim through.</p><h4>Some background on podman and buildah:</h4><p>podman, on the face, is very similar to docker. This means a easy transition for the everyday commands for an experienced docker user. Almost all of the subcommands are identical such that one can set alias docker=podmanin their ~/.bashrc and not need to change a thing on the cli! podman is supported by <a href="https://www.redhat.com/en">RedHat </a>and brings with it a new concept of <em>rootless</em> containers. Whereby a docker user would need elevated privileges to build and run a docker container, podman does not. This makes podman images significantly safer to use. I would hope that <br> <br>Buildah is the <em>builder </em>of podman images. We can use buildah bud as a replacement for docker build. The <em>bud</em> is an acronym for <em>build using dockerfile</em>.</p><h3>Migration Steps:</h3><p>We will go through the following steps in this tutorial:</p><p><strong>Setup</strong></p><ul><li>Installing podman and buildah</li><li>Creating a local image registry on our device</li><li>Logging into the registry on each of our devices</li></ul><p><strong>Building and Pushing Images</strong></p><ul><li>Building Images on each device</li><li>Creating the manifest list</li><li>Pushing the manifest list to our repository on quay.io</li></ul><h3>Setup</h3><h4>Installing podman and buildah</h4><p>podman is supported on Ubuntu 20.10 or later and Debian 11 or later. Please run cat /etc/*-release to see your current version of linux.</p><p>If you have met these requirements please run the following command to get started with podman (you will need to do this on all devices you are building images on)</p><pre># Install podman and buildah<br>(intel-nuc) $ sudo apt-get install podman buildah -y</pre><pre># Confirm installation<br>(intel-nuc) $ podman --version<br>podman version 3.0.1</pre><pre>(intel-nuc) $ buildah --version<br>buildah version 1.19.6 (image-spec 1.0.1, runtime-spec 1.0.2-dev)</pre><h4>Creating a local registry</h4><p>The registry sits as a repository for our different devices to push to over LAN and allows us to store the different architecture image builds in the one place. I will be creating my registry on my intel-nuc device as it has a bit more grunt than the raspberry pi.</p><p>To do this, you will need to read through the <a href="https://www.redhat.com/sysadmin/simple-container-registry">guide here</a>. It goes through creating a self-signed certificate, creating a username and password and then initialising the registry. The registry is created from the super-user account and thus it assumes you have sudo access. all commands should be prefixed with sudo.</p><p>Since the guide linked above is based on a RedHat linux I recommend the following adaptations for Ubuntu/Debian users:</p><p><strong>Installing </strong><strong>htpasswd :<br></strong>Instead of sudo yum install -y httpd-tools you should run sudo apt-get install -y apache2-utils .</p><p><strong>Creating the certificate:<br></strong>The certificate generated by the guide above gives me the following error when trying to run the podman login step:</p><pre>x509: certificate relies on legacy Common Name field, use SANs or temporarily enable Common Name matching with GODEBUG=x509ignoreCN=0</pre><p>Instead I would recommend adding in the v3_req extension to add in the SAN (Subject Alt Name).</p><pre># Copy over the default ssl conf to your workspace<br>cp /usr/lib/ssl/openssl.cnf podman-registry.cnf</pre><p>Find the line # req_extensions = v3_req and remove the # (uncommenting the line). Then add the following lines to the podman-registry.conf</p><pre>subjectAltName = @alt_names</pre><pre>[ alt_names ]<br>DNS.1 = intel-nuc</pre><p>You should swap out intel-nuc for the host name you plan to run the registry on.</p><p>Now generate the certificate with the following command:</p><pre>sudo openssl req -newkey rsa:4096 -nodes -sha256 -keyout /opt/registry/certs/domain.key -x509 -days 365 -subj &quot;/C=AU/ST=Victoria/L=Melbourne/O=UMCCR/CN=intel-nuc&quot; -extensions v3_req -config podmad-registry.cnf -out /opt/registry/certs/domain.crt</pre><p>You should swap out the -subj value with a string that is appropriate.</p><ul><li>C = Two-letter country code</li><li>ST = State</li><li>L = Location</li><li>O = Organisation</li><li>CN = Common Name (often the hostname where the certificate is housed)</li></ul><h4>Log in to the registry</h4><blockquote>First make sure that the registry is running with the following command (we need to use sudo since the podman container was created with the super user account). All other containers we create in this be created with your user account and should not have the sudo prefix in front of them:<br><em>(intel-nuc) $ sudo podman containers list</em></blockquote><p>Your username and password should be as set in the guide above.</p><pre>(intel-nuc) $ podman login intel-nuc:5000<br>(pi) $ podman login intel-nuc:5000</pre><h3>Building and pushing images</h3><h4>A note of caution with buildah bud</h4><blockquote>One main difference between buildah bud and docker build is their interpretations of the FROM instruction in the Dockerfile. Buildah expects a user to specify the repository source for the image and does not assume the image is from Docker Hub if not specified. This may mean instead of having the source repository line set as FROM continuumio/anaconda:latest it would instead be FROM docker.io/continuumio/anaconda:latest</blockquote><blockquote>After installing buildah you will see there are some <em>shorthand </em>registries set in /etc/containers/registries.conf.d/shortnames.conf that do not need their repository source. You should also be wary of some of the configurations in the shorthand registries. Some do NOT contain multi-arch images such as centos:8 and do not have docker.io as their default registry source.</blockquote><blockquote>Try running the following two commands to see the difference for yourself</blockquote><blockquote><em>podman manifest inspect centos:8</em></blockquote><blockquote>podman manifest inspect docker.io/centos:8</blockquote><h4>Building an image that installs jq</h4><p>As a guide we will be using <a href="https://github.com/umccr/docker-who/blob/main/repositories/alpine-jq/1.6/Dockerfile">this tiny alpine docker file</a>. The following lines will get you started</p><pre>(intel-nuc) $ mkdir alpine-jq-1.6<br>(intel-nuc) $ cd alpine-jq-1.6<br>(intel-nuc) $ wget --output-document Dockerfile &quot;https://raw.githubusercontent.com/umccr/docker-who/main/repositories/alpine-jq/1.6/Dockerfile&quot;</pre><p><strong>Building on the node locally<br></strong>The following commands will build (and push) the alpine-jq image to the local registry. In this tutorial we build separate images for each architecture then merge them as a manifest at the end.</p><pre>(intel-nuc) $ buildah bud -t intel-nuc:5000/alexiswl4/alpine-jq:1.6--amd64 .</pre><pre>(intel-nuc) $ podman push intel-nuc:5000/alexiswl4/alpine-jq:1.6--amd64</pre><p><strong>Building over ssh<br></strong>Rather than having to re-clone / recreate the Dockerfile environment on our other nodes, we can just copy and run over ssh, the following lines may be of use:</p><pre># Create a scratch directory on the raspberry pi<br>(intel-nuc) $ pi_workdir=&quot;$(ssh pi mktemp -d)&quot;</pre><pre># Copy over Dockerfile and any other relevant files<br>(intel-nuc) $ rsync --archive &quot;./&quot; &quot;pi:${pi_workdir}/&quot;</pre><pre># Confirm copy was completed successfully<br>(intel-nuc) $ ssh &quot;pi&quot; &quot;ls ${pi_workdir}/&quot; <br>Dockerfile</pre><pre># Build over ssh<br>(intel-nuc) $ ssh pi &quot;(cd &#39;${pi_workdir}&#39; &amp;&amp; buildah bud -t &#39;intel-nuc:5000:alexiswl4/alpine-jq:1.6--arm64&#39; .)&quot;</pre><pre># Push to registry (over ssh)<br>(intel-nuc) $ ssh pi &quot;podman push &#39;intel-nuc:5000:alexiswl4/alpine-jq:1.6--amd64&#39;&quot;</pre><h4>Creating the manifest</h4><p>The manifest is created on a single device, which will need to pull all the relevant containers from our local registry.</p><pre># Pull in both images to the intel-nuc device<br>(intel-nuc) $ podman pull intel-nuc:5000:alexiswl4/alpine-jq:1.6--amd64<br>(intel-nuc) $ podman pull intel-nuc:5000:alexiswl4/alpine-jq:1.6--arm64</pre><p>Now we can initialise our manifest</p><pre># Create the manifest<br>(intel-nuc) $ podman manifest create alexiswl4/alpine-jq:1.6</pre><p>Then add each of the images to the manifest</p><pre>(intel-nuc) $ podman manifest add intel-nuc:5000:alexiswl4/alpine-jq:1.6 podman pull intel-nuc:5000:alexiswl4/alpine-jq:1.6--amd64</pre><pre>(intel-nuc) $ podman manifest add intel-nuc:5000:alexiswl4/alpine-jq:1.6 podman pull intel-nuc:5000:alexiswl4/alpine-jq:1.6--arm64</pre><p>Now push to quay.io, you will need an <a href="https://quay.io/signin/">RedHat account</a> for this step and have logged in to quay.io with podman login quay.io on your device. You will need to substitute quay.io/alexiswl4 with your own quay.io account id.</p><pre>(intel-nuc) $ podman manifest push intel-nuc:5000:alexiswl4/alpine-jq:1.6 quay.io/alexiswl4/alpine-jq:1.6</pre><p>And we’re done! Now both arm64 (new macs and IoT devices) and amd64 users (the rest of the world!) can use your image.</p><h3>Conclusion</h3><p>In summary, podman and buildah are compatible substitutes for docker and docker buildx. The introduction of rootless containers hopefully paves the way for use in HPC environments. Creating a registry is more difficult than a docker swarm setup and this leaves a market for a toolkit that acts as a simple multi-node compiler, so we (I) can revert do building multi-arch images with just one single command. If you have any suggestions for improvements on this article, please let me know!</p><p>Alexis</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a862d7a84dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with WSL2]]></title>
            <link>https://medium.com/@awlucattini_60867/getting-started-with-wsl2-c11826654776?source=rss-5b91b179ba57------2</link>
            <guid isPermaLink="false">https://medium.com/p/c11826654776</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[wsl-2]]></category>
            <dc:creator><![CDATA[Alexis Lucattini]]></dc:creator>
            <pubDate>Sun, 22 Aug 2021 06:59:02 GMT</pubDate>
            <atom:updated>2021-08-22T07:00:00.036Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Using Windows Terminal, enabling clipboard and browser interaction</blockquote><h3>Intro</h3><p>Microsoft have come a long way with their Windows Subsystem for Linux. This tutorial will set you up running Ubuntu 20.04 inside Windows Terminal. The additional steps of enabling xclip (copying your linux console outputs to your windows clipboard) and displays (opening up a browser window from inside your linux console) will make you feel at home with WSL2.</p><h3>Part 1 — Installation</h3><blockquote>About 20 minutes (with a couple of system restarts)</blockquote><h4>1.1 Install Ubuntu</h4><p>You will need to download the Ubuntu linux distribution from the <a href="https://www.microsoft.com/store/productId/9N6SVWS3RX71">Microsoft Store</a>. Use version 20.04, as this is supported until 2025.</p><h4>1.2 Install WSL2</h4><p>Now install WSL2 — if you are yet to do so please install WSL2 from the <a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10">WSL Home page</a>. Follow the prompts for installation. You may need to restart your computer after this step. To confirm the installation open up PowerShell and run the following command: wsl.exe --list --all --verbose</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*JMkspoaXTO6avd_xBH7-rQ.png" /></figure><p>We should expect to see one row for <em>Ubuntu </em>with the WSL2 Version set to <em>2</em></p><h4>1.3 Install Windows Terminal</h4><p>We can then install Windows Terminal (much nicer than the ancient command prompt). Again head to <a href="https://www.microsoft.com/en-au/p/windows-terminal/9n0dx20hk701">Microsoft</a> to download Windows Terminal.<br>Open up windows terminal. We should see Ubuntu available in the dropdown menu!</p><h4>1.3 Configure Windows Terminal</h4><p>Let’s quickly make sure that Ubuntu is our default terminal.</p><p>Open up Windows Terminal and head to the settings section</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JX1m-MjIR_1xpmUKDr8KHA.png" /></figure><p>Then select Ubuntu as the default profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNAXI0-6JAj9Ygwqve_DlA.png" /></figure><p>Open up a new terminal and we should see Ubuntu prompt. <br>Well done! You’ve passed Part 1!!</p><p>Open up a Ubuntu tab in Windows Terminal and runsudo apt-get update and sudo apt-get upgrade before continuing to ensure your new linux system is installed with the latest security features.</p><h3>Part 2: Setting the root directory mount</h3><blockquote>About 5 minutes</blockquote><p>You may notice that your C drive is mounted at /mnt/c . This can cause some problems and it’s likely that you wish this to just be mounted at /c .</p><p>We can update the directory mount to /c with the following updates to /etc/wsl.conf</p><pre>[automount]<br>enabled = true<br>root = /</pre><p>Remember to use sudo to update an admin file. The following command may help you: sudo vim /etc/wsl.conf</p><p>In order for the effects to be present you must first restart wsl . Open up PowerShell again and run the following command wsl.exe --shutdown . This will restart the wsl virtual env. Open up Windows Terminal and WSL2 will start up automatically.</p><h3>Part 3: Enabling the clipboard</h3><blockquote>About 30 minutes</blockquote><p>Copying from the console is something Linux and MacOS users have had for sometime. This is the longest part of this tutorial and has a few steps</p><h4>3.1 Installing VcXsrv</h4><p>You can download VcXsrv through <a href="https://sourceforge.net/projects/vcxsrv/">SourceForge</a>. Choose to install all items</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*euA7N0A_MMUiCyWgmtoQXA.png" /><figcaption>It’s important all items are selected for installation</figcaption></figure><h4>3.2 Installing the Ubuntu X11 Apps and xclip</h4><p>Open up an Ubuntu console (through Windows Terminal) and run</p><pre>sudo apt install x11-apps xclip xdg-utils</pre><h4>3.3 Setting the DISPLAY environment variable</h4><p>It’s important that we set the DISPLAY environment variable to XXX.XX.XX.X:0 where XXX...X is the local IPv4 address of the computer (rather than the Virtual Machine itself). The 0 is the default <em>sequence </em>number (see <a href="https://datacadamia.com/ssh/x11/display">here</a> for more info).</p><p>Since our IPv4 address can change from time to time, it’s important that this is set dynamically. Open up your ubuntu terminal and open the file ~/.bashrc and add the following line:</p><pre>export DISPLAY=&quot;$(grep &#39;^nameserver &#39; /etc/resolv.conf | cut -d&#39; &#39; -f2):0&quot;</pre><p>This way our DISPLAY variable is correct regardless of if our IPv4 address changes!</p><p>To confirm this has worked, open up a new Ubuntu Terminal tab and run the following:</p><pre>echo &quot;$DISPLAY&quot;</pre><h4>3.4 ‘Hacking’ Xlaunch</h4><p>Much credit goes to Bhupathy’s <a href="https://bhupathy.medium.com/install-terminator-on-windows-with-wsl-2826591d2156">WSL1 tutorial</a> for this step. XLaunch is a shortcut to VcXsrv, we are going to update the shortcut to include the desired parameters. We will then add XLaunch to the startup apps in the next step</p><p>Head to the ‘File Location’ for XLaunch (the image below may assist you).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*D4HOI4u4QCNyqfnrGrpGCQ.png" /></figure><p>Right click on ‘Properties’ and under the ‘Shortcut’ menu update the ‘Target’ to the following</p><pre>&quot;C:\Program Files\VcXsrv\vcxsrv.exe&quot; :0 -ac -terminate -lesspointer -multiwindow -clipboard -wgl -dpi auto</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*BvDaiDrcHR4gYfw5vNQoZA.png" /></figure><h4>3.5 Adding XLaunch to the start up apps</h4><p>Open up the file location for the XLaunch shortcut (as shown in the step above). <br>Meanwhile, open up the Run console with Win + R, and type shell:startup. This should open up another folder at:<br>%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup</p><p>Copy the XLaunch shortcut into the Start up folder.</p><p>When the computer is restarted, XLaunch will automatically be started. For now, click on the XLaunch shortcut to start it up.</p><p>In a new Ubuntu terminal console type echo foo | xclip . You should see ‘foo’ has been added to your clipboard. Try Ctrl+V to paste this into a new text document or search bar?</p><h4>3.6 Troubleshooting</h4><p>If this isn’t working for you and you’ve triple checked that XLaunch is running, and your DISPLAY variable is set correctly, it could possibly be a firewall issue.<br>You may also find that everything works fine at home and then xclip hangs when you’re in your local library.</p><p>To fix this, open up your Firewall settings page and click ‘Allow an app through firewall’.</p><p>Search for VcXsrv windows server and make sure that both Private and Public are enabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*Xverc9yz7Dzz9BGBTnBCRw.png" /></figure><h3>Part 4: Setting the browser variable</h3><blockquote>About 4 minutes</blockquote><p>This is quite important if you have any linux applications that require SSO through a web browser (i.e the AWS cli).</p><p>We can add the following line to our ~/.bashrc to make sure that WSL can launch a browser if it needs to.</p><pre>export BROWSER=&quot;wslview&quot;</pre><p>Open up a new terminal and type:</p><pre>xdg-open &quot;https://www.google.com&quot;</pre><p>You should see a new tab open up in your web browser</p><h3>Conclusion:</h3><p>If you’ve made it so far, thank you so much for all of your patience and persistence. Please let me know if you had any issues in any of the steps. All feedback welcome!</p><p>Alexis out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*0SmvDs_5HtkOWfvqW4DyXQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c11826654776" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[jq; a saviour for sanitising inputs, not just outputs]]></title>
            <link>https://medium.com/data-science/jq-a-saviour-for-sanitising-inputs-not-just-outputs-1fd6728c0dc4?source=rss-5b91b179ba57------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fd6728c0dc4</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[jq]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[aws-cli]]></category>
            <dc:creator><![CDATA[Alexis Lucattini]]></dc:creator>
            <pubDate>Tue, 06 Apr 2021 08:55:26 GMT</pubDate>
            <atom:updated>2021-04-14T03:44:18.784Z</atom:updated>
            <content:encoded><![CDATA[<h3>jq: A Saviour for Sanitising Inputs, Not Just Outputs</h3><p>Many examples and tutorials exist out there for using <a href="https://github.com/stedolan/jq/blob/master/README.md">jq</a> for handling JSON outputs or quickly accessing items in a JSON body. I have linked a couple of my favourites in the resources below.</p><p>Yet, few know of its benefits when one requires a json as a CLI input. A prime example of such a use case is interacting with the AWS CLI, as I will show you throughout this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1RxKRXuTaJiDXD_0m-dSA.jpeg" /><figcaption>Image Source: Author’s own</figcaption></figure><h4>A typical programmer’s problem:</h4><p>Let’s say we want to use the aws ssm send-command tool to submit a command to an ec2-instance. This may be particularly useful when sshis not available.</p><blockquote>It is common to not have port 22 (ssh) open or for it to be at least very restricted to only a few IP addresses. This <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html">AWS post</a> summarises the security risks of unrestricted ssh access</blockquote><p>In order to send a command over <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html">ssm</a> we can use the following code:</p><pre>instance_id=&quot;i-123456789&quot;<br>aws ssm send-command \<br>  --document-name &quot;AWS-RunShellScript&quot; \<br>  --targets &quot;Key=InstanceIds,Values=${instance_id}&quot; \<br>  --parameters &quot;{&#39;commands&#39;:[&#39;echo foo&#39;]}&quot;</pre><p>Easy right?</p><p>Well, not quite, the command is sent to the super user <em>sudo, </em>but in many use cases, it’s likely we want to submit to a non-administrative user like <em>ec2-user. </em>We can do this by wrapping the command in su &quot;-&quot; &quot;ec2-user&quot; -c &#39;$command’ — since we’re already using double quotes over the parameters argument, the single quotes around $command won’t accidentally write it as a ‘literal’.</p><p>However, we’re still likely to come across some short falls here. Let’s say we are writing a function that takes the command from stdin, we may then wish to write this as a one-liner like below and save it as submit_to_ec2_instance.sh .</p><pre>#!/usr/bin/env bash</pre><pre>: &#39;<br>Simple script that submits the command string from stdout in<br>to the instance id (sysarg 1)<br>&#39;</pre><pre># The first input, should start with &#39;i-&#39;<br>instance_id=&quot;$1&quot;  </pre><pre># Send our command from stdin to $instance_id<br>aws ssm send-command \<br>  --document-name &quot;AWS-RunShellScript&quot; \<br>  --targets &quot;Key=InstanceIds,Values=${instance_id}&quot; \<br>  --parameters &quot;{&#39;commands&#39;:[\&quot;su - ec2-user -c &#39;$(&lt;/dev/stdin)&#39;\&quot;}&quot;</pre><p>If a user decides to run this with</p><pre>echo &quot;sleep &#39;5&#39;; echo &#39;done here&#39;&quot; | \<br>submit_to_ec2_instance.sh i-123456789</pre><p>then the su function on our instance id is going to receive the following arguments:</p><ul><li>-</li><li>ec2-user</li><li>-c</li><li>sleep 5; echo done</li><li>here</li></ul><p>Oh dear.. the last two arguments here are meant to be wrapped into one argument through the single quotes. It seems that our single quotes around stdin have clashed with the user’s single quotes in their command!</p><blockquote>Arguments on the command line are separated by spaces but can be interpreted as one argument by the use of single quotes, double quotes, or by escaping the space.<br>In this case, the single quotes ended prematurely. … -c &#39;sleep 5; echo &#39;done here&#39;&#39;was incorrectly split. The interpreter could not tell the difference between the inside single quotes specified by the user and the outside single quotes set inside our shell script function.</blockquote><h4>A list of “unviable” workarounds</h4><p>Each of the following may be workable but all have at least one caveat:</p><ol><li><strong>Just tell the user not to use single quotes</strong></li></ol><p>But what if they don’t always have control over the input? They may be blindly parsing through an output of another command into this one?</p><p>2. <strong>Use a tool like </strong><strong>sed to make sure we are turning all </strong><strong>&#39; in the user’s input to </strong><strong>\&#39;</strong></p><p>A good idea, but what happens if they already have escaped single quotes, we’d then need to make sure escaped single quotes are double escaped… writing a <a href="https://docs.python.org/3/library/shlex.html">shlex-like</a> parser could get very complicated and time consuming.</p><p>3. <strong>Go back to escaped double quotes around stdin</strong></p><p>The user would then need to escape any double quotes. Escaped quotes would also need to be double-escaped. Again, we’d be either expecting the user to escape quotes or writing another shlex tool.</p><p>Blimey, this is getting complicated for just one command!</p><h4>jq to the rescue!</h4><p>Let’s go back to square one and consider that the --parameters arg as a json object in string representation. In the references below, we’ve noted that jq is highly useful for querying json outputs and for simple data collation purposes. <br>It’s also really useful for generating json inputs. Below we will use jq along with the &lt;&lt;&lt; bash <a href="https://tldp.org/LDP/abs/html/x17837.html">here-string</a> to initialise a json object, populate using jq which will do all of the escape handling for us, and then set this as our --parameters value.</p><p>Let’s start together with the most basic jq input:</p><pre>$ jq &lt;&lt;&lt; &quot;{}&quot;<br>{}</pre><p>Now lets create a minimal json object with my_arg and my_val</p><pre>$ jq &#39;.&quot;my_arg&quot;=&quot;my_val&quot;&#39; &lt;&lt;&lt; {}<br>{<br>  &quot;my_arg&quot;: &quot;my_val&quot;<br>}</pre><blockquote>One small caveat is that <em>jq </em>recommends to use single quotes around the its filter string. In order to get our command line variables inside this string, we will need to use the --arg parameter.</blockquote><p>Let’s use the jq <em>arg </em>parameter to try and get a json object that looks something like what’s expected for the aws ssm send-command <em>parameters </em>CLI value. The square braces,[] are used since <em>commands </em>is actually a list of commands.</p><pre>$ command=&quot;sleep &#39;5&#39;; echo &#39;done here&#39;&quot;<br>$ jq \<br>  --arg key &quot;commands&quot; \<br>  --arg value &quot;$command&quot; \<br>  &#39;.[$key]=[$value]&#39; &lt;&lt;&lt; {}<br>{<br>  &quot;commands&quot;: [<br>    &quot;sleep &#39;5&#39;; echo &#39;done here&#39;&quot;<br>  ]<br>}</pre><p>Neat! This output puts it all into one argument, as discussed above, this would run on the <em>sudo </em>account not the <em>ec2-user</em> account. To prefix our <em>value</em> argument, we can use the + filter command to insert our prefix.</p><pre>$ command=&quot;sleep &#39;5&#39;; echo &#39;done here&#39;&quot;<br>$ jq \<br>  --arg key &quot;commands&quot; \<br>  --arg value &quot;$command&quot; \<br>  &#39;.[$key]=[&quot;su - ec2-user -c &quot; + $value]&#39; &lt;&lt;&lt; {}<br>{<br>  &quot;commands&quot;: [<br>    &quot;su - ec2-user -c sleep &#39;5&#39;; echo &#39;done here&#39;&quot;<br>  ]<br>}</pre><p>We’re so close! This still has the quoting issues from before, fortunately we can use the tojson method to escape any double quotes in command.</p><blockquote>The \() inside a jq filter-string is the equivalent of shell’s $() command invocation.</blockquote><pre>$ command=&quot;sleep &#39;5&#39;; echo &#39;done here&#39;&quot;<br>$ jq \<br>  --arg key &quot;commands&quot; \<br>  --arg value &quot;$command&quot; \<br>  &#39;.[$key]=[&quot;su - ec2-user -c &quot; + &quot;\($value | tojson)&quot;]&#39; &lt;&lt;&lt; {}<br>{<br>  &quot;commands&quot;: [<br>    &quot;su - ec2-user -c \&quot;sleep &#39;5&#39;; echo &#39;done here&#39;\&quot;&quot;<br>  ]<br>}</pre><p>Woo hoo! let’s also add a couple of already escaped quotes to see what jq does to them</p><pre>$ command=&quot;sleep &#39;5&#39;; echo &#39;done here&#39; \&quot;with escaped quotes\&quot;&quot;<br>$ jq \<br>  --arg key &quot;commands&quot; \<br>  --arg value &quot;$command&quot; \<br>  &#39;.[$key]=[&quot;su - ec2-user -c &quot; + &quot;\($value | tojson)&quot;]&#39; &lt;&lt;&lt; {}<br>{<br>  &quot;commands&quot;: [<br>    &quot;su - ec2-user -c \&quot;sleep &#39;5&#39;; echo &#39;done here&#39; \\\&quot;with escaped quotes\\\&quot;\&quot;&quot;<br>  ]<br>}</pre><p>Splendid! We can now write our submit_to_ec2_instance.sh like so</p><pre><strong>#!/usr/bin/env bash<br><br></strong>: &#39;<br>Takes in command from stdin and an instance-id positional argument<br>Submits command to ec2-user on instance-id<br>&#39;<br><br># Step one -&gt; Collect the instance id<br>instance_id=&quot;$1&quot;  # The first input, should start with &#39;i-&#39;<br><br># Escape quotes from command, set up parameter arg as json string<br># This should evaluate to (with escape quotes as necessary)<br># {<br>#   &quot;commands&quot;: [<br>#     &quot;su - ec2-user -c &quot;my-command arg1 arg2...&quot;<br>#   ]<br># }<br>parameter_arg=&quot;$(jq --raw-output \<br>  --arg key &quot;commands&quot; \<br>  --arg value &quot;$(&lt;/dev/stdin)&quot; \<br>  &#39;.[$key]=[&quot;su - ec2-user -c &quot; + &quot;\($value | tojson)&quot;]&#39; &lt;&lt;&lt; {})&quot;<br><br># Now run the aws ssm send-command function with our instance id<br>aws ssm send-command \<br>  --document-name &quot;AWS-RunShellScript&quot; \<br>  --targets &quot;Key=InstanceIds,Values=${instance_id}&quot; \<br>  --parameters &quot;${parameter_arg}&quot;</pre><h4>When should I use this?</h4><p>Ideally, if we were routinely interacting with AWS on the CLI, we’d be using modules like <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html">boto3</a> in a python script to organize our parameters. The above code however is useful in situations where such modules and high-level languages might not be readily available.</p><p>An example of such situations may be an external CI/CD executor, such as <a href="https://github.com/features/actions">GitHub Actions </a>or <a href="https://travis-ci.org/">TravisCI </a>where we would need to install a high-level language (like python) and any required modules every time the code is executed. By using something like a simple shell script above, the CI/CD would can take a fresh ubuntu installation, install <em>jq</em> through <em>apt-get</em>, then run a quick bash script to submit our request to our desired endpoint.</p><p>Another use case may be setting this script as a simple function in your .bashrc, whereas your accessibility to python and boto3 might be dependent on the current <em>venv</em> or <em>conda</em> environment. Here, using jq would be more appropriate, as the bash function could always be expected to work — assuming jq has been installed globally.</p><p>Finding the balance here is an art. When things get more complicated, one should move away from simple scripting languages like bash to a high-level language such as python. High-level languages will likely improve your code readability, save you time in writing and maintaining code and do a better job of catching/handling errors.</p><h4>Resources</h4><ul><li><a href="https://stackoverflow.com/a/38862221/6946787">StackOverflow answer</a> that inspired this article</li><li><a href="https://stedolan.github.io/jq/tutorial/">jq manual</a></li><li>a <a href="https://www.baeldung.com/linux/jq-command-json">jq tutorial</a> from Jonathan Cook that delves into some collating of json inputs</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fd6728c0dc4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/jq-a-saviour-for-sanitising-inputs-not-just-outputs-1fd6728c0dc4">jq; a saviour for sanitising inputs, not just outputs</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I backup my cloned GitHub repositories on OneDrive]]></title>
            <link>https://medium.com/@awlucattini_60867/i-backup-my-cloned-github-repositories-on-onedrive-54b176192950?source=rss-5b91b179ba57------2</link>
            <guid isPermaLink="false">https://medium.com/p/54b176192950</guid>
            <category><![CDATA[working-from-home]]></category>
            <category><![CDATA[onedrive]]></category>
            <category><![CDATA[pycharm]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Alexis Lucattini]]></dc:creator>
            <pubDate>Sun, 31 Jan 2021 00:10:57 GMT</pubDate>
            <atom:updated>2021-01-31T02:12:10.379Z</atom:updated>
            <content:encoded><![CDATA[<h3>I backup my local git repositories on OneDrive</h3><h4>It’s actually not as stupid of an idea as it sounds</h4><p><em>“GitHub and OneDrive are now both Microsoft products”</em> — this was my single justification one day for deciding “<em>f***-it, what’s the worst that could happen if I dragged and dropped all of my local GitHub directories into OneDrive? At least it would be a funny anecdote to tell to my colleagues in the virtual Monday morning meeting”.</em> <br>As it turns out, so far, touch wood, disaster is yet to strike. In fact the benefits, have greatly outweighed any consequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0k9AQmpUHME9xSqataph3g.png" /><figcaption>Placing my local repos through my OneDrive has reduced my need for the endless adding/committing/pushing unready files to GitHub just to start working from another device</figcaption></figure><h4>The over-flexible work dilemma</h4><p>Like many of us, I’ve been stuck working at home for the last year. I have a (until recently dormant) MacOS desktop in my office, a Windows 10 desktop that I’m writing from right now in my bedroom, and a Windows 10 laptop for when I want to work from somewhere else in the house. Working from three separate disconnected devices made working with git a nightmare.</p><p>Even pre-pandemic, any uncommitted late-night work from home wasn’t available for me to continue working on when I rocked up at the office the next morning, nor were any of the large test datasets that are too large or not appropriate to be git-controlled. I’ve also recently found myself with sweat sticking my legs to the chair as I desperately commit and push unfinished scripts to GitHub on my bedroom desktop where the room has reached 30<strong>°</strong> C, just so I could work off my laptop in the lounge under our air-conditioner.</p><p>This continuous committing and pushing leads to poor developer practices; half-finished code chunk commits, rushed commit messages, and the wrong files being added to the repo.</p><h4>Solving the Git Overhead</h4><p>Do not get me wrong, <strong>GIT IS GREAT!!</strong> For our team where we’re all working remotely, GitHub has been essential for us to share / validate / branch and version control our scripts and software. git does, however, have its overhead as mentioned above. If only there was something that synced all my stuff automatically, including the things that I don’t want to commit to public repos — say secrets in text files, that I would like to have available to me on my other devices…</p><p>…Introducing OneDrive! While commands such as git stash / git merge / git rebase will throw the little blue cloud icon in the corner of my screen into chaos mode, it quickly recovers into a synced state . The set of files I want to currently put out of the way but not delete— known as a stash — are available to me instantly should I decide to ‘pop’ them when working from another device. Whether I’m working from the lounge room, a café, or from the office again, I no longer need to worry about syncronising my work from my home desktop.</p><h4>You’re playing with fire, surely something has to go wrong?</h4><p>My only caveat so far, are the files that you <strong>don’t</strong> want synced between computers. The main culprit of these for me have been PyCharm JetBrains <em>.idea</em> files that sit in the top directory of each repository / project. Unfortunately, OneDrive doesn’t let you ignore files of a certain type or in a certain folder in the same way git does. Therefore, every time I switch from my Windows to Mac or vice-versa, my PyCharm project configuration breaks for each repo.</p><p>My solution to this has been to sit the project files outside of OneDrive and add the git repo into the content root of the project. That way, each device has its own isolated copy of the project configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJD8vyXAiogl3CE6fgckMA.png" /><figcaption>The PyCharm project can be created in a local directory to prevent conflicting ‘.idea’ folders. The git controlled repo can then be added via the Project Structure settings in PyCharm.</figcaption></figure><h4>OneDrive, the git --regret saviour</h4><p>Again, I need not remind you that git is great. Yet, there’s always a risk of accidentally deleting very large amounts of important code by not realizing the consequences of the the commands that you’re running. <br>git pull --force, git reset --hard, and git checkout --are three commands to which all software engineers have run at some points in their career that have then been followed by tears.</p><p>Yet, the part that chuffs me the most about this daring experiment has been the discovery that my hesitations working with git now has a safety net. OneDrive works with time-based version controlling. Any poor choices I make can be easily fixed by going through OneDrive’s ‘restore’ setting and rolling back in time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8O8SdHRjx7D-krdQ-TtKxg.png" /><figcaption>OneDrive allows for a restoration of files with changes listed in chronological order</figcaption></figure><h4>Proceeding with caution</h4><p>I can’t say this is an option for everyone. I am always careful that I don’t ever shut down my computer immediately after running any git commands, but I am also fortunate that both my home and work desktops are connect to the internet via Cat6-ethernet cables — the kilobytes of file changes are synced in a few seconds. I dare say there may come a time where my luck falls apart and I’m asked to resolve a OneDrive conflict. Until that day, I’ll continue this insanity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54b176192950" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can we rid that ‘one password for everything’ habit?]]></title>
            <link>https://medium.com/@awlucattini_60867/can-we-rid-that-one-password-for-everything-habit-af55c1f4c469?source=rss-5b91b179ba57------2</link>
            <guid isPermaLink="false">https://medium.com/p/af55c1f4c469</guid>
            <category><![CDATA[password-management]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[passwords]]></category>
            <dc:creator><![CDATA[Alexis Lucattini]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 00:11:06 GMT</pubDate>
            <atom:updated>2020-04-17T01:41:30.310Z</atom:updated>
            <content:encoded><![CDATA[<p>Throwback to the year 2004 — or there about. You first signed into MSN (Windows Live in its twilight years). Complementing your Hotmail username was your first password, a witty string of characters — comprising the name of your pet, proceeded by one or two numbers. <br>Oh! what simple times these were.</p><p>If, for whatever reason, you and your computer literacy skills seem to be stuck in 2004, and have maintained that same password ever since — or slight derivatives of it to meet the marginally stricter requirements of current day web servers — I kindly urge you to fix this. You have no excuse. Today is a Sunday, it’s raining, you’ve been given an extra hour in your day… and you’re forced to stay inside anyway! Today is the day, you installed a password management system in your life.</p><h4>Here’s four reasons why you should do this:</h4><p>1. Imagine your password is like a house key. Using the same password for your emails, Facebook, that niche online retail site, is like leaving a copy of your house keys in every place you shop… and if that shop has poor security measures, which many of them do, every worker in that shop can access that key and knows where you live.</p><p>2. What would your boss say if they told you all data on the servers had been compromised through your account? Is this a better outcome that having all that data removed? Or the data is held to seven-figure ransom? If $100 was taken out of your salary every week, how long would it be before you paid the ransom back?</p><p>3. When I last looked at my password bank, I had over 350 different logins that I’d registered over the last eight or so years. Using derivatives of the same password doesn’t help you remember if you’ve signed up to a site/service before, nor tell you which email you’d used to sign up to the service. How do you keep of all the different Slack workspaces you’ve been invited to?</p><p>4. It also allows you to give only the information you think is relevant to the site. Fun fact, Amazon can perform their delivery duties without needing to know when your birthday is. Whilst I personally am not phased by companies wasting research into targeted advertising for astrological signs, unnecessary information such as your date of birth can be used to link you to your accounts from other sites. With a password bank, you can store the false values you give to sites you feel don’t need that information, along with any security questions that you no longer need to remember the answer to. The longer and abstract your passphrase to a security question the safer it’ll be, and the more creative you get to be too. Rather than answering What’s your favourite kind of tea<em>: </em>with <em>English Breakfast</em>, try something like: <em>one where the bag is still in and the milk is provided in a separate cup of china</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*7dLmErIWfhg38ELt3ltGUQ.jpeg" /><figcaption>Many workplaces have policies to increase cyber-security. Although this may lead to other bad habits. Copyright 2016 John Klossner <a href="http://www.jklossner.com/">www.jklossner.com</a>, used by permission of Dark Reading, <a href="http://www.darkreading.com/">www.darkreading.com</a></figcaption></figure><h4>These are all good reasons to get a password manager. <br>So what’s next? Do I have to pay?</h4><p>No, below I’ve detailed two free password managers: <a href="https://keepass.info/download.html"><strong>KeePass</strong> </a>and <a href="https://www.lastpass.com/"><strong>LastPass</strong></a>. The former being a password protected file containing a data bank of your credentials, run by open-source software. The latter being a cloud-based solution with enterprise pricing for companies too. Both provide methods to auto-generate passwords for you and provide you with a security rating of your current passwords.</p><p>KeePass provides a very basic interface and the learning curve can be a little steep without someone looking over your shoulder telling you which four keyboard shortcuts are the only ones you will ever need to use:</p><p>· Crtl + I — A new entry</p><p>· Ctrl + B — Copy username/email to clipboard</p><p>· Ctrl + C — Copy password to clipboard</p><p>· Ctrl + F — Search for an entry</p><p>Third-party mobile apps also exist for KeePass and can access your password bank, given you place the file on your personal cloud server such as Microsoft OneDrive, Google Drive or DropBox. The file itself is smaller than a word document and will not force you to pay for an additional-tier of storage. <br>The third party apps can be a little clunkly particularly with syncing files and this means all new entries to the software ought to be made on a computer to prevent change conflicts.</p><figure><img alt="keepass login window" src="https://cdn-images-1.medium.com/max/488/1*8tclcgMHzA9TeX5d2Bj8Mg.png" /><figcaption>The KeePass login window. A password is required to enter the data bank. A key file may also be added for extra security — meaning the hacker would need your password AND the file to break into your password bank. Key files are not discussed in this post but may be highlighted in an additional post.</figcaption></figure><p>LastPass on the other hand, has a sleek interface with its own apps for iOS and Android with add-ons for all common internet browsers. This allows for seamless syncing of passwords between multiple devices. In addition, LastPass allows for additional two-factor authentication to increase security.<br>LastPass is easily the most popular password management app for its user friendly interface and convenience.</p><p>It’s from this huge popularity, that my own reluctance towards LastPass arises. If someone wants to access my passwords on KeePass they have to <br>a) break through into my cloud that has two-factor authentication enabled<br>b) find my KeePass file<br>c) break into my KeePass file through brute force (trial and error millions of times!)<br>Yielding the hacker with just my set of passwords for their effort. This reward dwarfs that of infiltrating the LastPass servers and gaining the credentials of millions of users over millions of sites. <br>Since LastPass is a closed system, no one outside of LastPass knows how secure it is. It’s popularity and content (containing the many credentials of millions of users) makes it a large target for hackers. You can read LastPass’s security white paper <a href="https://assets.cdngetgo.com/1d/ee/d051d8f743b08f83ee8f3449c15d/lastpass-technical-whitepaper.pdf">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*ysRJnP75lAVQXn1kvcHOeQ.jpeg" /><figcaption>LastPass has all devices covered. Whether you’re on Apple Watch or a tablet, you can download the LastPass app. All show a very user-friendly interface.</figcaption></figure><blockquote>Note: Your passwords are only as safe as the login credentials you provide to your password manager.. Try to use a phrase rather than a family member’s name. Something like “idontlikeworkingfromhome” is much safer than “alexis”</blockquote><p>In conclusion, password manager apps, like those listed above are a secure way of generating, and securely accessing the credentials for sites you visit.<br>I’m confident you’ll be able to configure either of these two solutions to fit your needs… today!</p><h4>Future reading:</h4><p>Thinking that secure passwords alone will protect you is like bringing a knife to a gunfight. In a few weeks I intend to go through phishing scams, two-factor authentication and cookies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af55c1f4c469" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas query method saves double handling of variables]]></title>
            <link>https://medium.com/data-science/pandas-query-method-saves-double-handling-of-variables-9293d703b804?source=rss-5b91b179ba57------2</link>
            <guid isPermaLink="false">https://medium.com/p/9293d703b804</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <dc:creator><![CDATA[Alexis Lucattini]]></dc:creator>
            <pubDate>Sun, 12 Jan 2020 21:01:56 GMT</pubDate>
            <atom:updated>2020-01-12T21:01:56.577Z</atom:updated>
            <content:encoded><![CDATA[<h4>Last Updated: Jan 2020</h4><h4>Using .query() can save us from having to type the variable name of a dataframe multiple times over a single line of code when selecting data.</h4><p>Standard methods to retrieve rows with certain conditions in a pandas DataFrame object requires ‘double handling’; it’s not particularly elegant.</p><p>For example, we want to retrieve rows where column <em>A </em>is greater than 1, this is the standard way to do it using the <em>.loc</em> attribute.</p><pre><em>## Setup ##</em></pre><pre><em># Import pandas<br></em><strong>import </strong>pandas <strong>as </strong>pd</pre><pre><em># Create dataframe from dict<br></em># Specify the type in the suffix of each column name<br>my_df = pd.DataFrame({<strong>&quot;A_int&quot;</strong>: [1, 2, -3],<br>                      <strong>&quot;B_float&quot;</strong>: [7.5, 1.9, 8.4],<br>                      <strong>&quot;C_str&quot;</strong>: [<strong>&#39;eight&#39;</strong>, <strong>&#39;nine&#39;</strong>, <strong>&#39;Ten&#39;</strong>],<br>                      <strong>&quot;D_str&quot;</strong>: [<strong>&#39;Mar 2017&#39;</strong>, <strong>&#39;May 2018&#39;</strong>, <strong>&#39;Jun 2016&#39;</strong>]}<br>                    )</pre><pre><em># Convert to datetime column<br></em>my_df[<strong>&#39;D_date&#39;</strong>] = pd.to_datetime(my_df[<strong>&#39;D_str&#39;</strong>])</pre><pre>&quot;&quot;&quot;<br>&gt;&gt;&gt; my_df<br>   A_int  B_float  C_str     D_str     D_date<br>0      1      7.5  eight  Mar 2017 2017-03-01<br>1      2      1.9   nine  May 2018 2018-05-01<br>2     -3      8.4    Ten  Jun 2016 2016-06-01<br>&quot;&quot;&quot;</pre><pre>## Show loc example 1 ##</pre><pre>ex_1_loc = my_df.loc[my_df[<strong>&#39;A_int&#39;</strong>] &gt; 0, :]</pre><pre>&quot;&quot;&quot;<br>&gt;&gt;&gt; ex_1_loc<br>   A_int  B_float  C_str     D_str     D_date<br>0      1      7.5  eight  Mar 2017 2017-03-01<br>1      2      1.9   nine  May 2018 2018-05-01<br>&quot;&quot;&quot;</pre><p>Here we obtain the Boolean series of rows where column A is greater than 0 for that given row. The <em>.loc </em>is used to pull out rows set to True. Note that the variable <em>my_df </em>is used twice here in a single line of code.<br>It is fortunate that this variable name is not very long. I find this ‘double handling’ of the variable syntactically similar to base methods in R, particularly intimidating when nested and overall quite unnecessary.</p><p>Some other languages can perform this filtering in a much more readable format:</p><pre>## SQL EXAMPLE ##<br>SELECT *<br>FROM my_df<br>WHERE A &gt; 0</pre><pre>## R-TIDYVERSE EXAMPLE ##<br>library(tidyverse)<br>my_df %&gt;%<br>  dplyr::filter(A &gt; 0)</pre><p>For python, we can do this simpler (and similar to the SQL / R-Tidyverse structure above) with pandas ‘query’ method. <em>query</em> returns only the rows that match the given condition, all columns remain present in the dataframe.</p><pre>#ex_1_loc = my_df.loc[my_df[<strong>&#39;A_int&#39;</strong>] &gt; 0, :]<br>ex_1_query = my_df.query(&quot;A &gt; 0&quot;)<br># Or use @ when referencing a variable<br>pivot_val = 0<br>ex_1a_query = my_df.query(&quot;A &gt; @pivot_val&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UEjMJDpF6Vxmg7Ks1bHVw.jpeg" /><figcaption>Standard pandas methods can often leave us seeing double — Image src: <a href="https://pixabay.com/photos/panda-family-pandas-cute-bamboo-3811734/">https://pixabay.com/photos/panda-family-pandas-cute-bamboo-3811734/</a></figcaption></figure><p>Let&#39;s see six more examples where query is an appropriate replacement to the <em>.loc</em> approach</p><h4>2. Filter on an external list</h4><p>Given an external list, obtain rows of the dataframe where a certain column matches an element in that list</p><pre><em># Create a list of legitimate entries<br></em>legit_entries = [<strong>&#39;eight&#39;</strong>, <strong>&#39;nine&#39;</strong>, <strong>&#39;ten&#39;</strong>]</pre><pre><em># Filter column &#39;C_str&#39; by the array<br></em>ex_2_loc = my_df.loc[my_df[<strong>&#39;C_str&#39;</strong>].isin(legit_entries), :]<br>ex_2_query = my_df.query(<strong>&quot;C_str in @legit_entries&quot;</strong>)</pre><pre>&quot;&quot;&quot;<br>   A_int  B_float  C_str     D_str     D_date<br>0      1      7.5  eight  Mar 2017 2017-03-01<br>1      2      1.9   nine  May 2018 2018-05-01<br>&quot;&quot;&quot;</pre><h4>3. Column comparison</h4><p>Compare two columns — this requires triple handling in the <em>.loc </em>example.</p><pre><em># Return rows where &#39;A_int&#39; is greater than &#39;B_float&#39;<br></em>ex_3_loc = my_df.loc[my_df[<strong>&#39;A_int&#39;</strong>] &gt; my_df[<strong>&#39;B_float&#39;</strong>], :]<br>ex_3_query = my_df.query(<strong>&quot;A_int &gt; B_float&quot;</strong>)</pre><pre>&quot;&quot;&quot;<br>   A_int  B_float C_str     D_str     D_date<br>1      2      1.9  nine  May 2018 2018-05-01<br>&quot;&quot;&quot;</pre><h4>4. Multi-conditional filtering</h4><p>Filter using multiple conditions over potentially multiple columns. Both <em>&amp; </em>and <em>| </em>bitwise operators are allowed.</p><pre><em># Return rows where &#39;A_int&#39; is greater than zero<br># And where C_str is in the legit_entries array<br></em>ex_4_loc = my_df.loc[(my_df[<strong>&quot;A_int&quot;</strong>] &gt; 0) &amp;<br>                     (my_df[<strong>&#39;C_str&#39;</strong>].isin(legit_entries)), :]<br>ex_4_query = my_df.query(<strong>&quot;A_int &gt; 0 &amp; C_str in @legit_entries&quot;</strong>)</pre><pre>&quot;&quot;&quot;<br>   A_int  B_float  C_str     D_str     D_date<br>0      1      7.5  eight  Mar 2017 2017-03-01<br>1      2      1.9   nine  May 2018 2018-05-01<br>&quot;&quot;&quot;</pre><h4>5. Timestamps</h4><p>Query recognises dates and can compare them to strings. All strings inside a query quote must be quoted.</p><pre><em># Return rows where D_date is after Jan 2018<br></em>ex_5_loc = my_df.loc[my_df[<strong>&#39;D_date&#39;</strong>] &gt; <strong>&#39;Jan 2018&#39;</strong>, :]<br>ex_5_query = my_df.query(<strong>&quot;D_date &gt; &#39;Jan 2018&#39;&quot;</strong>)</pre><pre>&quot;&quot;&quot;<br>   A_int  B_float C_str     D_str     D_date<br>1      2      1.9  nine  May 2018 2018-05-01<br>&quot;&quot;&quot;</pre><h4>6. Column conversion prior to comparison</h4><p>You can perform a function on a given column prior to comparison.<br>Note that the output of the dataframe still contains the <em>C_str</em> column in its original format?</p><pre><em># First convert C_str to lowercase, than compare entries<br></em>ex_6_loc = my_df.loc[my_df[<strong>&#39;C_str&#39;</strong>].str.lower().isin(legit_entries),<br>                     :]<br>ex_6_query = my_df.query(<strong>&quot;C_str.str.lower() in @legit_entries&quot;</strong>)</pre><pre>&quot;&quot;&quot;<br>   A_int  B_float  C_str     D_str     D_date<br>0      1      7.5  eight  Mar 2017 2017-03-01<br>1      2      1.9   nine  May 2018 2018-05-01<br>2     -3      8.4    Ten  Jun 2016 2016-06-01<br>&quot;&quot;&quot;</pre><p><strong>7. Column names containing spaces<br></strong>Initially forbidden with pandas query, this has been resolved as of 0.25.2.<br>Quote the column with backticks. Other special characters in the column may not work.</p><pre><em># Return rows where &#39;E rogue column str&#39; column contains the word &#39;this&#39;<br></em>my_df[<strong>&#39;E rogue_column_str&#39;</strong>] = [<strong>&#39;this&#39;</strong>, <strong>&#39;and&#39;</strong>, <strong>&#39;that&#39;</strong>]</pre><pre>&quot;&quot;&quot;<br>&gt;&gt;&gt;my_df<br>   A_int  B_float  C_str     D_str     D_date E rogue_column_str<br>0      1      7.5  eight  Mar 2017 2017-03-01               this<br>1      2      1.9   nine  May 2018 2018-05-01                and<br>2     -3      8.4    Ten  Jun 2016 2016-06-01               that<br>&quot;&quot;&quot;</pre><pre>ex_7_loc = my_df.loc[my_df[<strong>&quot;E rogue_column_str&quot;</strong>] == <strong>&#39;this&#39;</strong>, :]<br>ex_7_query = my_df.query(<strong>&quot;`E rogue_column_str` == &#39;this&#39;&quot;</strong>))</pre><pre>&quot;&quot;&quot;<br>   A_int  B_float  C_str     D_str     D_date E rogue_column_str<br>0      1      7.5  eight  Mar 2017 2017-03-01               this<br>&quot;&quot;&quot;</pre><h3>Overcoming the ‘item’ deprecation</h3><p>In the latest release of pandas (0.25.3 at the time of writing), the <em>.item()</em> method was deprecated. Combined with the query function, <em>item</em> was a highly useful tool to obtain a single value from a given column when it was appropriate to assume that only one row would be returned. This would convert the column from a type <em>pd.Series </em>to that of the series’ datatype i.e int, str, float etc. If more than one row was returned, a ValueError is raised by the method.</p><p>We can use the squeeze method as an alternative with some small changes in the code. Like item, squeeze will convert a pandas series from series type to the datatype when the filtered series is only one row long. However, a ValueError is <strong>not </strong>raised if multiple values exist in the series, instead just the same series is returned. We can exploit this by checking if the returned value is still of a series type.</p><pre><em># Previous code<br></em><strong>try</strong>:<br>    single_value = ex_3_query[<strong>&#39;B_float&#39;</strong>].item()<br>    print(single_value)<br><strong>except </strong>ValueError:<br>    print(<strong>&quot;Error, expected to return only one value, got %d&quot; </strong>%<br>          len(ex_3_query[<strong>&#39;B_float&#39;</strong>]))</pre><pre><em># New code<br></em>single_value = ex_3_query[<strong>&#39;B_float&#39;</strong>].squeeze()<br><strong>if </strong>isinstance(single_value, pd.Series):<br>    print(<strong>&quot;Error, expected to return only one value, got %d&quot; </strong>%<br>          len(ex_3_query[<strong>&#39;B_float&#39;</strong>]))<br><strong>else</strong>:<br>    print(single_value)</pre><p>References:<br><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html">Pandas Query API</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9293d703b804" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/pandas-query-method-saves-double-handling-of-variables-9293d703b804">Pandas query method saves double handling of variables</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing  readable regexes]]></title>
            <link>https://medium.com/@awlucattini_60867/writing-readable-regexes-fa7433829b7f?source=rss-5b91b179ba57------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa7433829b7f</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[reproducibility]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[code-review]]></category>
            <dc:creator><![CDATA[Alexis Lucattini]]></dc:creator>
            <pubDate>Sun, 05 Jan 2020 03:34:22 GMT</pubDate>
            <atom:updated>2020-01-06T02:06:52.570Z</atom:updated>
            <content:encoded><![CDATA[<h3>Writing readable regexes</h3><p>Regexes (regular expressions) are essential for the flexibility of code to work over dynamic inputs. If it feels that writing regexes is hard, for those reading them it can feel impossible.</p><p>Before continuing I would highly recommend reading <a href="https://scotch.io/tutorials/an-introduction-to-regex-in-python">this tutorial</a> on regexes, their usage, and how to write them in python.</p><p>Now a very short questionnaire -<br><strong> Regexes are:</strong><br>A: Powerful<br>B: Confusing<br>C: I can only understand my own regexes!<br>D: All of the above.</p><p>For many of us, the answer is D. When I write a regex, it seems simple… but only to me. This is explained by -<br>1. I’m aware of all the possible different inputs we’re trying to mine on. <br>2. I’m familiar with the outputs that we need. <br>3. I’m probably very biased.</p><p>These tally up as to also why I cannot read anyone else’s regexes in code, for the same way they cannot read mine. There’s often little context for the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*kswRyZnAL6QipoElXKXQFA.jpeg" /><figcaption>Complicated regexes aren’t always readable — image src: <a href="https://www.complexsql.com/postgres-queries/">https://www.complexsql.com/postgres-queries/</a></figcaption></figure><p><strong>Commenting your regex<br></strong> Providing a logistical dialogue of how such a regex string in a doc string is not straight forward, particularly when you’re not sure on who will continue to maintain your code and their experience with regexes.</p><p>While personally, I try to comment almost every second line of code I write, creating a written lengthy essay for how one particular regex works, with working examples, seems tiresome to both me and the future maintainer that has to read it. How can I succinctly let them know I’ve thought of more than just one use case, or that all possible edge cases have been covered?</p><p>So this is my latest method - <a href="https://regex101.com/">https://regex101.com/</a></p><p>regex101 has been my favourite regex test site for a while. It has an amazing real-time explanation pane providing a detailed dialogue of why a regex matched or did not match. Most importantly, you can create permalink to unit tests and your testing area.</p><p>Which means we can copy this link into our code for future maintainers to see our thought processes.</p><p>Say I require a function that picks out a numerical value when provided with a single word followed by a dollar value. I can first test this on the regex101 site like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_sbFtUtYoRA22IfvC6AF2Q.png" /><figcaption>A regular expression is entered in the center console. Each line in the test string is highlighted if it matches the regex. An option to share as a permalink is provided on the left while the regex explanation is seen on right.</figcaption></figure><p>Then place this regex and the permalink into the code like so</p><pre>import re<br> <br>def get_money_from_input(input_string):<br>	&quot;&quot;&quot;<br>	Given a word and a dollar value, <br>        capture and return the <br>        numerical component of the dollar value <br>        if a match otherwise return none<br>        i.e ‘this $20.24’ -&gt; 20.24<br>        regex pattern testing can be found at <br>        https://regex101.com/r/4i6o2o/2<br>        Unit tests can be seen at<br>        https://regex101.com/r/4i6o2o/2/tests<br>        &quot;&quot;&quot;        <br>        # Create the pattern object<br>        pattern = re.compile(r&quot;^\S+\ \$(\d+\.\d{2})$&quot;)<br>        <br>        # Run the regex on the input string<br>        re_match_obj = re.match(pattern, input_string)<br>               <br>        # If we got a match return the first group as a float<br>        if re_match_obj is not None:<br>            return float(re_match_obj.group(1))<br>        # Otherwise, return a null value<br>        else:<br>            return None</pre><p>Now we’ve provided a link in the functions’ doc string to the regex testing area and unit tests I used for this regex. Here I can (and have) provided multiple working examples and non-working examples of the regex. In the event the regex must be modified, there already exists a list of unit tests that are still expected to pass — reducing the likelihood of introducing bugs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*LGjxS2Lqyw63aQDWLNPfcw.png" /><figcaption>The unit tests for a given regex, can inform a maintainer of edge cases that have been thought of.</figcaption></figure><p>We can also spell out the different components of the regex by placing each component on a different line. We must also place an additional argument to the function, re.VERBOSE, so that the regex is still interpreted correctly<br>Note the three quotes surrounding the regex in the new version</p><pre>### OLD ###</pre><pre># Create the pattern object<br>pattern = re.compile(r&quot;^\S+\ \$(\d+\.\d{2})$&quot;)</pre><pre>### NEW ###</pre><pre># Create the pattern object<br>pattern = re.compile(r&quot;&quot;&quot;<br>                      ^             # Start <br>                      \S+           # The single word<br>                      \             # The space<br>                      \$            # Dollar sign<br>                      (\d+\.\d{2})  # Many ints, period, two ints<br>                      $             # End<br>                      &quot;&quot;&quot;, re.VERBOSE)</pre><p>The verbose option also makes it easier to quickly count which captured component we need to grab in complicated regexes — counting down, rather than across. In this case, this is trivial with just one group in brackets.</p><p>You can read more about the regex101 project <a href="https://github.com/firasdib/Regex101/wiki/About">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa7433829b7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>