Mitja Felicijan's posts https://mitjafelicijan.com You do not learn by relaxing. You learn by violently assaulting your problem until it surrenders its mysteries to you. en-us Who knows what the world will look like tomorrow https://mitjafelicijan.com/who-knows-what-the-world-will-look-like-tomorrow.html Sat, 08 Jul 2023 18:49:07 +0200 https://mitjafelicijan.com/who-knows-what-the-world-will-look-like-tomorrow.html This site has gone through a lot of changes over the years. <p>This site has gone through a lot of changes over the years. From being written in Flask and Bottle to moving on to static site generators. I have used and tested probably 10s of them my now. From homebrew solutions to the biggest and the baddest. From Bash scripts to Node.js disasters. I've seen some things, no doubt. Not all bad.</p> <p>I'have been closely observing the web and where the trends are going, and I don't like what I see. Instead of internet being this weird place where experimentation is happening, it all became stale and formulized. Boring, actually. Really boring. And sad. Where is that old, revolutionary FU spirit I remember? It's still there, I know. But it's being drowned by the voices of mediocrity and formulaic boredom.</p> <p>It almost feels like that the internet stopped for 10 years and only now something has started happening. With all the insanity around the world. People hating people without actual reasons, just because it's fashionable to hate and crowd is saying so. Sad state of affairs.</p> <p>All this is contributing to this overall negativity masked as apathy. Everybody walking in lockstep. Instead of being creative are bold, we are just re-inventing the world and making the same mistakes. Maybe, just maybe, some things are good enough and there is no need to try to be too smart for our own good. After N-attempts, maybe something should click inside our heads to maybe say: &quot;This thing, opinion, etc. is actually really good, and even after several attempts it still holds.&quot;</p> <p>The older I get, the more careful I am of my own thoughts and why I think the way I think. More and more, I try to understand people with opposite opinions. Far from perfect, but closer to bearable. And then I see people hearing or reading a thing on internet and let's fucking goooooo! Strong opinions are a sign of a weak and uneducated mind. I am more and more sure of this.</p> <p>It's gotten to a point where you can with great certainty deduce a person's personality based on one or two opinions. How boring have we become. No wonder people can't talk to each other. These would be very quick conversations anyway.</p> <p>I just got remembered of a song, &quot;Hi Ren&quot;. The ending talks about being stiff and not being able to dance. Such an amazing metaphor. And we as people have gone so far, we can't even walk or even crawl normally anymore. We have forgotten that the most beautiful things in life have a great deal of uncertainty about them. We want instant gratification. Not only that, but we want absolute obedience. Complete control over others, because we have zero control of ourselves. And all the lies we could tell ourselves will not help us in this situation.</p> <p>It is funny how I catch myself from time to time being a complete idiot. It's like having an outer body experience. I can see myself being an idiot, and cannot stop myself. It serves as a learning lesson to stop before speaking. To think before saying. And to crawl before walking.</p> <p>So there is still time. We can dance once more. All we need to do is stop for a second. Me and you. Us two is a start. Let's not try to change the world, but rather nudge ourselves just a tiny bit. And if we only did that. Each of us nudged ourselves a small, tiny bit, the world would heal. If we would just put down the phones and ignored Internet for a day or two. Put visiting websites that feed on us on hold. Listened to just one sentence and try to understand it from a person who we completely disagree with. I truly believe that this is possible.</p> <p>Life is about suffering and joy. And instead of wishing suffering on others and excepting joy for yourselves, we should for a brief moment want suffering for ourselves and wish joy on others. Wouldn't that be an amazing sight to see?</p> <p>I caught myself hating on Rust. And I deeply thought about it afterward. Why did I do it? It is obviously not for me. So why the hell was I being so negative towards it? I think that I know the answer. I was negative because that is easy. Because it's much easier to hate on things than to say to yourself: &quot;Well, you know what? This is not for me. I will focus on creation and not destruction. This is who I want to be. This is what fills me with joy and purpose.&quot; Where joy is keeping me happy and purpose scares the shit out of me and keeps me honest. This is who I want to be. Admit to myself when I am wrong and accept the faults that I have without reservation and with courage march on.</p> <p>I just realized that this blog post is a sort of therapy for me. It's cathartic. Going thought the history of this site and remembering all the decisions and annoyances that came with it. When I was cursing at the tools. And time moved on, and the site is still here. It serves as a reminder that perseverance wins at the end. If we just let things go.</p> <p>This came with a decision that simplifying life and removing all the unnecessary negativity is key. Rather than worrying about what the internet is saying, what the world is trying to take from you, you are the only one who can say no. And create instead of destroy.</p> <p>I don't have an ending for this post, so I will say this. We live in the most amazing times in the recorded history, and we should be internally grateful for it. Create and study, this should be my mantra. Just create and let the world happen. And you feel yourself to be too certain, stop and check how deep in the shit you are already. Strong opinions are a sign of a weak and uneducated mind. Hate and disdain is for the weak.</p> Bringing all of my projects together under one umbrella https://mitjafelicijan.com/bringing-all-of-my-projects-together-under-one-umbrella.html Sat, 01 Jul 2023 18:49:07 +0200 https://mitjafelicijan.com/bringing-all-of-my-projects-together-under-one-umbrella.html What is the issue anyway? <h2 id="what-is-the-issue-anyway">What is the issue anyway?</h2> <p>Over the years, I have accumulated a bunch of virtual servers on my <a href="https://www.digitalocean.com/">DigitalOcean</a> account for small experimental projects I dabble in. And this has resulted in quite a bill. I mean, I wouldn't care if these projects were actually being used. But there were just being there unused and wasting resources. Which makes this an unnecessary burden for me.</p> <p>Most of them are just small HTML pages that have an endpoint or two to read data from or to, and for that reason I wrote servers left and right. To be honest, all of those things could have been done with <a href="https://en.wikipedia.org/wiki/Common_Gateway_Interface">CGI scripts</a> and that would have been more than enough.</p> <p>Recently, I decided to stop language hopping and focus on a simpler stack which includes C, Go and Lua. And I can accomplish all the things I am interested in.</p> <h2 id="finding-a-web-server-replacement">Finding a web server replacement</h2> <p>Usually I had <a href="https://nginx.org/en/">Nginx</a> in front of these small web servers and I had to manage SSL certificates and all that jazz. I am bored with these things. I don't want to manage any of this bullshit anymore.</p> <p>So the logical move forward was to find a solid alternative for this. I have ended up on <a href="https://caddyserver.com/">Caddy server</a>. I've used it in the past but kind of forgotten about it. What I really like about it is an ease of use and a bunch of out of the box functionalities that come with it.</p> <p>These are the <em>pitch</em> points from their website:</p> <ul> <li><strong>Secure by Default</strong>: Caddy is the only web server that uses HTTPS by default. A hardened TLS stack with modern protocols preserves privacy and exposes MITM attacks.</li> <li><strong>Config API</strong>: As its primary mode of configuration, Caddy's REST API makes it easy to automate and integrate with your apps.</li> <li><strong>No Dependencies</strong>: Because Caddy is written in Go, its binaries are entirely self-contained and run on every platform, including containers without libc.</li> <li><strong>Modular Stack</strong>: Take back control over your compute edge. Caddy can be extended with everything you need using plugins.</li> </ul> <p>I had just a few requirements:</p> <ul> <li>Automatic SSL</li> <li>Static file server</li> <li>Basic authentication</li> <li>CGI script support</li> </ul> <p>And the vanilla version does all of it, but CGI scripts. But that can easily be fixed with their modular approach. You can do this on their website and build a custom version of the server, or do it with Docker.</p> <p>This is a <code>Dockerfile</code> I used to build a custom server.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">FROM</span><span style="color:#a31515"> caddy:builder AS builder</span><span style=""> </span></span></span><span style="display:flex;"><span><span style=""> </span></span></span><span style="display:flex;"><span><span style=""></span><span style="color:#00f">RUN</span> xcaddy build <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> --with github.com/aksdb/caddy-cgi<span style=""> </span></span></span><span style="display:flex;"><span><span style=""> </span></span></span><span style="display:flex;"><span><span style=""></span><span style="color:#00f">FROM</span><span style="color:#a31515"> caddy:latest</span><span style=""> </span></span></span><span style="display:flex;"><span><span style=""></span><span style="color:#00f">RUN</span> apk add --no-cache nano<span style=""> </span></span></span><span style="display:flex;"><span><span style=""> </span></span></span><span style="display:flex;"><span><span style=""></span><span style="color:#00f">COPY</span> --from=builder /usr/bin/caddy /usr/bin/caddy<span style=""> </span></span></span></code></pre><h2 id="getting-rid-of-all-the-unnecessary-virtual-machines">Getting rid of all the unnecessary virtual machines</h2> <p>The next step was to get a handle on the number of virtual servers I have all over the place.</p> <p>I decided to move all the projects and services into two main VMs:</p> <ul> <li>personal server (still Nginx) <ul> <li>git server</li> <li>static file server</li> <li>personal blog</li> </ul> </li> <li>projects server (Caddy server) <ul> <li>personal experiments</li> <li>other projects</li> </ul> </li> </ul> <p>I will focus on projects' server in this post since it's more interesting.</p> <h2 id="testing-cgi-scripts">Testing CGI scripts</h2> <p>The first thing I tested was how CGI scripts work under Caddy. This is particularly import to me because almost all of my experiments and mini projects need this to work.</p> <p>To configure Caddy server, you must provide the server with a configuration file. By default, it's called <code>Caaddyfile</code>.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>{ </span></span><span style="display:flex;"><span> <span style="color:#00f">order</span> <span style="color:#a31515">cgi</span> before <span style="color:#a31515">respond</span> </span></span><span style="display:flex;"><span>} </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="font-weight:bold">examples.mitjafelicijan.com</span> { </span></span><span style="display:flex;"><span> <span style="color:#00f">cgi</span> /bash-test <span style="color:#a31515">/opt/projects/examples/bash-test.sh</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">cgi</span> /tcl-test <span style="color:#a31515">/opt/projects/examples/tcl-test.tcl</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">cgi</span> /lua-test <span style="color:#a31515">/opt/projects/examples/lua-test.lua</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">cgi</span> /python-test <span style="color:#a31515">/opt/projects/examples/python-test.py</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">root</span> * <span style="color:#a31515">/opt/projects/examples</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">file_server</span> </span></span><span style="display:flex;"><span>} </span></span></code></pre><ul> <li>The order is very important. Make sure that <code>order cgi before respond</code> is at the top of the configuration file.</li> <li>Also, when you run with Caddy v2, make sure you provide <code>adapter</code> argument like this <code>/usr/bin/caddy run --watch --environ --config /etc/caddy/Caddyfile --adapter caddyfile</code>. Otherwise, Caddy will try to use a different format for config file.</li> </ul> <p>I did a small batch of tests with <a href="https://www.gnu.org/software/bash/">Bash</a>, <a href="https://www.tcl-lang.org/">Tcl</a>, <a href="https://www.lua.org/">Lua</a> and <a href="https://www.python.org/">Python</a>. Here is a cheat sheet if you need it.</p> <p>Let's get Bash out of the way first.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">#!/usr/bin/bash </span></span></span><span style="display:flex;"><span><span style="color:#00f"></span> </span></span><span style="display:flex;"><span>printf <span style="color:#a31515">&#34;Content-type: text/plain\n\n&#34;</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>printf <span style="color:#a31515">&#34;Hello from Bash\n\n&#34;</span> </span></span><span style="display:flex;"><span>printf <span style="color:#a31515">&#34;PATH_INFO [%s]\n&#34;</span> $PATH_INFO </span></span><span style="display:flex;"><span>printf <span style="color:#a31515">&#34;QUERY_STRING [%s]\n&#34;</span> $QUERY_STRING </span></span><span style="display:flex;"><span>printf <span style="color:#a31515">&#34;\n&#34;</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">for</span> i in {0..9..1}; <span style="color:#00f">do</span> </span></span><span style="display:flex;"><span> printf <span style="color:#a31515">&#34;&gt; %s\n&#34;</span> $i </span></span><span style="display:flex;"><span><span style="color:#00f">done</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>exit 0 </span></span></code></pre><p>This one is for Tcl script.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000">#!/usr/bin/tclsh </span></span></span><span style="display:flex;"><span><span style="color:#008000"> </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span>puts <span style="color:#a31515">&#34;Content-type: text/plain\n&#34;</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>puts <span style="color:#a31515">&#34;Hello from Tcl\n&#34;</span> </span></span><span style="display:flex;"><span>puts <span style="color:#a31515">&#34;PATH_INFO \[$env(PATH_INFO)\]&#34;</span> </span></span><span style="display:flex;"><span>puts <span style="color:#a31515">&#34;QUERY_STRING \[$env(QUERY_STRING)\]&#34;</span> </span></span><span style="display:flex;"><span>puts <span style="color:#a31515">&#34;&#34;</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">for</span> <span style="color:#00f">{set</span> i 0<span style="color:#00f">}</span> <span style="color:#00f">{</span>$i &lt; 10<span style="color:#00f">}</span> <span style="color:#00f">{</span>incr i<span style="color:#00f">}</span> <span style="color:#00f">{</span> </span></span><span style="display:flex;"><span> puts <span style="color:#a31515">&#34;&gt; $i&#34;</span> </span></span><span style="display:flex;"><span><span style="color:#00f">}</span> </span></span></code></pre><p>And for all you Python enjoyers.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000">#!/usr/bin/python3</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> os </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>print(<span style="color:#a31515">&#34;Content-type: text/plain</span><span style="color:#a31515">\n</span><span style="color:#a31515">&#34;</span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>print(<span style="color:#a31515">&#34;Hello from Python</span><span style="color:#a31515">\n</span><span style="color:#a31515">&#34;</span>) </span></span><span style="display:flex;"><span>print(<span style="color:#a31515">&#34;PATH_INFO [</span><span style="color:#a31515">{}</span><span style="color:#a31515">]&#34;</span>.format(os.environ[<span style="color:#a31515">&#39;PATH_INFO&#39;</span>])) </span></span><span style="display:flex;"><span>print(<span style="color:#a31515">&#34;QUERY_STRING [</span><span style="color:#a31515">{}</span><span style="color:#a31515">]&#34;</span>.format(os.environ[<span style="color:#a31515">&#39;QUERY_STRING&#39;</span>])) </span></span><span style="display:flex;"><span>print(<span style="color:#a31515">&#34;&#34;</span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">for</span> i <span style="color:#00f">in</span> range(10): </span></span><span style="display:flex;"><span> print(<span style="color:#a31515">&#34;&gt; </span><span style="color:#a31515">{}</span><span style="color:#a31515">&#34;</span>.format(i)) </span></span></code></pre><p>And for the final example, Lua.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">#!/usr/bin/lua</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>print(<span style="color:#a31515">&#34;Content-type: text/plain</span><span style="color:#a31515">\n</span><span style="color:#a31515">&#34;</span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>print(<span style="color:#a31515">&#34;Hello from Lua</span><span style="color:#a31515">\n</span><span style="color:#a31515">&#34;</span>) </span></span><span style="display:flex;"><span>print(string.format(<span style="color:#a31515">&#34;PATH_INFO [%s]&#34;</span>, os.getenv(<span style="color:#a31515">&#34;PATH_INFO&#34;</span>))) </span></span><span style="display:flex;"><span>print(string.format(<span style="color:#a31515">&#34;QUERY_STRING [%s]&#34;</span>, os.getenv(<span style="color:#a31515">&#34;QUERY_STRING&#34;</span>))) </span></span><span style="display:flex;"><span>print() </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">for</span> i = 0, 9 <span style="color:#00f">do</span> </span></span><span style="display:flex;"><span> print(string.format(<span style="color:#a31515">&#34;&gt; %d&#34;</span>, i)) </span></span><span style="display:flex;"><span><span style="color:#00f">end</span> </span></span></code></pre><h2 id="basic-authentication">Basic authentication</h2> <p>One thing was also to have an option for some sort of authentication, and something like <a href="https://en.wikipedia.org/wiki/Basic_access_authentication">Basic access authentication</a> would be more than enough.</p> <p>Thankfully, Caddy supports this out of the box already. Below is an updated example.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>{ </span></span><span style="display:flex;"><span> <span style="color:#00f">order</span> <span style="color:#a31515">cgi</span> before <span style="color:#a31515">respond</span> </span></span><span style="display:flex;"><span>} </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="font-weight:bold">examples.mitjafelicijan.com</span> { </span></span><span style="display:flex;"><span> <span style="color:#00f">cgi</span> /bash-test <span style="color:#a31515">/opt/projects/examples/bash-test.sh</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">cgi</span> /tcl-test <span style="color:#a31515">/opt/projects/examples/tcl-test.tcl</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">cgi</span> /lua-test <span style="color:#a31515">/opt/projects/examples/lua-test.lua</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">cgi</span> /python-test <span style="color:#a31515">/opt/projects/examples/python-test.py</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">root</span> * <span style="color:#a31515">/opt/projects/examples</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">file_server</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">basicauth</span> * { </span></span><span style="display:flex;"><span> <span style="color:#00f">bob</span> <span style="">$</span><span style="color:#a31515">2a</span><span style="">$</span>14<span style="">$</span><span style="color:#a31515">/wCgaf9oMnmQa20txB76u.nI1AldGMBT/1J7fXCfgOiRShwz/JOkK</span> </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span>} </span></span></code></pre><p><code>basicauth *</code> matches everything under this domain/sub-domain and protects it with Basic Authentication.</p> <ul> <li><code>bob</code> is the username</li> <li><code>hash</code> is the password</li> </ul> <p>To generate these passwords, execute <code>caddy hash-password</code> and this will prompt you to insert a password twice and spit out a hashed password that you can put in your configuration file.</p> <p>Restart the server and you are ready to go.</p> <h2 id="making-caddy-a-service-with-systemd">Making Caddy a service with systemd</h2> <p>After the tests were successful, I copied <code>caddy</code> to <code>/usr/bin/caddy</code> and copied <code>Caddyfile</code> to <code>/etc/caddy/Caddyfile</code>.</p> <p>Now off to the systemd. Each systemd service requires you to create a service file.</p> <ul> <li>I created a <code>/etc/systemd/system/caddy.service</code> and put the following content in the file.</li> </ul> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">[Unit]</span> </span></span><span style="display:flex;"><span>Description=<span style="color:#a31515">Caddy</span> </span></span><span style="display:flex;"><span>Documentation=<span style="color:#a31515">https://caddyserver.com/docs/</span> </span></span><span style="display:flex;"><span>After=<span style="color:#a31515">network.target network-online.target</span> </span></span><span style="display:flex;"><span>Requires=<span style="color:#a31515">network-online.target</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">[Service]</span> </span></span><span style="display:flex;"><span>Type=<span style="color:#a31515">notify</span> </span></span><span style="display:flex;"><span>User=<span style="color:#a31515">root</span> </span></span><span style="display:flex;"><span>Group=<span style="color:#a31515">root</span> </span></span><span style="display:flex;"><span>ExecStart=<span style="color:#a31515">/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile --adapter caddyfile</span> </span></span><span style="display:flex;"><span>ExecReload=<span style="color:#a31515">/usr/bin/caddy reload --config /etc/caddy/Caddyfile --force --adapter caddyfile</span> </span></span><span style="display:flex;"><span>TimeoutStopSec=<span style="color:#a31515">5s</span> </span></span><span style="display:flex;"><span>LimitNOFILE=<span style="color:#a31515">1048576</span> </span></span><span style="display:flex;"><span>LimitNPROC=<span style="color:#a31515">512</span> </span></span><span style="display:flex;"><span>PrivateTmp=<span style="color:#a31515">true</span> </span></span><span style="display:flex;"><span>ProtectSystem=<span style="color:#a31515">full</span> </span></span><span style="display:flex;"><span>AmbientCapabilities=<span style="color:#a31515">CAP_NET_ADMIN CAP_NET_BIND_SERVICE</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">[Install]</span> </span></span><span style="display:flex;"><span>WantedBy=<span style="color:#a31515">multi-user.target</span> </span></span></code></pre><ul> <li>You might need to reload systemd with <code>systemctl daemon-reload</code>.</li> <li>Then I enabled the service with <code>systemctl enable caddy.service</code>.</li> <li>And then I started the service with <code>systemctl start caddy.service</code>.</li> </ul> <p>This was about all that I needed to do to get it running. Now I can easily add new subdomains and domains to the main configuration file and be done with it. No manual Let's Encrypt shenanigans needed.</p> Re-Inventing Task Runner That I Actually Used Daily https://mitjafelicijan.com/re-inventing-task-runner-that-i-actually-used-daily.html Wed, 31 May 2023 12:21:10 +0200 https://mitjafelicijan.com/re-inventing-task-runner-that-i-actually-used-daily.html Couple of months ago I had this brilliant idea of re-inventing the wheel bymaking an alternative for make. <p>Couple of months ago I had this brilliant idea of re-inventing the wheel by making an alternative for make. And so I went. Boldly into the battle. And to my big surprise my attempt resulted in not a completely useless piece of software.</p> <p>My initial requirements were quite simple but soon grow into something more ambitious. And looking back I should have stuck to the simple version. My laziness was on my side this time though. Because I haven’t implemented some of the features I now realise I really didn’t need them and they would bog the whole program and make it be something it was never meant to be.</p> <p>My basic requirements were following:</p> <ul> <li>Syntax should be a tiny bit inspired by Rake and Rakefiles.</li> <li>Should borrow the overall feel of a unit test experience.</li> <li>Using something like Python would be a bit of an overkill.</li> <li>The program must be statically compiled, so it can run on same architecture without libc, musl dependencies or things like that.</li> <li>Install ruby for rake is a bit overkill and can not be done with certain really lightweight distributions like Alpine Linux. This tool would be usable on such lightweight systems for remote debugging.</li> <li>I want to use it for more than just compiling things. I want to use it as an entry-point into a project, and I want this to help me indirectly document the project as well.</li> <li>It should be an abstraction over bash shell or the default system shell. <ul> <li>Each task essentially becomes its own shell instance.</li> </ul> </li> <li>Must work on Linux and macOS systems.</li> <li>By default, running <code>erd</code> list all the available tasks (when I use make, I usually put a disclaimer that you should check Makefile to see all available target).</li> <li>Should support passing arguments when you run it from a shell.</li> <li>Normal variable as the same as environmental variables. There is no distinction. Every variable is also essentially an environment variable and can be used by other programs.</li> <li>State between tasks is not shared, and this makes this “pure” shell instances.</li> <li>Should be single-threaded for the start and later expanded with <code>@spawn</code> command.</li> <li>Variables behave like macros and are preprocessed before evaluation.</li> <li>Should support something like <code>assure</code> that would check if programs like C compiler or Python (whatever the project requires) are installed on a machine.</li> </ul> <p>Quite a reasonable list of requirements. I do this things already in my Makefiles or/and Bash scripts. But I would like to avoid repeating myself every time I start working on something new.</p> <p>So I started with the following syntax.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>@env on </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># Override the default shell.</span> </span></span><span style="display:flex;"><span>@shell <span style="color:#a31515">/bin/</span>bash </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># Assure that program is installed.</span> </span></span><span style="display:flex;"><span>@assure docker-compose pip python3 </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># Load local dotenv files (these are then globally available).</span> </span></span><span style="display:flex;"><span>@dotenv .env </span></span><span style="display:flex;"><span>@dotenv .env.sample </span></span><span style="display:flex;"><span>@dotenv some_other_file </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># This are local variables but still accessible in tasks.</span> </span></span><span style="display:flex;"><span>@var HI = <span style="color:#a31515">&#34;hey&#34;</span> </span></span><span style="display:flex;"><span>@var TOKEN = <span style="color:#a31515">&#34;sometoken&#34;</span> </span></span><span style="display:flex;"><span>@var EMAIL = <span style="color:#a31515">&#34;m@m.com&#34;</span> </span></span><span style="display:flex;"><span>@var PASSWORD = <span style="color:#a31515">&#34;pass&#34;</span> </span></span><span style="display:flex;"><span>@var EDITOR = <span style="color:#a31515">&#34;vim&#34;</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>@task dev <span style="color:#a31515">&#34;Test chars .:&#39;}{]!//&#34;</span> does </span></span><span style="display:flex;"><span> echo <span style="color:#a31515">&#34;...&#34;</span> $HI </span></span><span style="display:flex;"><span><span style="color:#00f">end</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>@task clean <span style="color:#a31515">&#34;Cleans the obj files&#34;</span> does </span></span><span style="display:flex;"><span> rm .obj </span></span><span style="display:flex;"><span><span style="color:#00f">end</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>@task greet <span style="color:#a31515">&#34;Greets the user&#34;</span> does </span></span><span style="display:flex;"><span> echo <span style="color:#a31515">&#34;Hi user $TOKEN or $WINDOWID $EMAIL&#34;</span> </span></span><span style="display:flex;"><span><span style="color:#00f">end</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>@task stack <span style="color:#a31515">&#34;Starts Docker stack&#34;</span> does </span></span><span style="display:flex;"><span> docker-compose -f stack.yml up </span></span><span style="display:flex;"><span><span style="color:#00f">end</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>@task todo <span style="color:#a31515">&#34;Shows all todos in source files and count them&#34;</span> does </span></span><span style="display:flex;"><span> grep -ir <span style="color:#a31515">&#34;TODO|FIXME&#34;</span> . | wc -l </span></span><span style="display:flex;"><span><span style="color:#00f">end</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>@task test1 <span style="color:#a31515">&#34;For testing 1&#34;</span> does </span></span><span style="display:flex;"><span> unknown-command </span></span><span style="display:flex;"><span> echo <span style="color:#a31515">&#34;test1&#34;</span> </span></span><span style="display:flex;"><span> ls -lha </span></span><span style="display:flex;"><span><span style="color:#00f">end</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>@task test2 <span style="color:#a31515">&#34;For testing 2&#34;</span> does </span></span><span style="display:flex;"><span> echo <span style="color:#a31515">&#34;test1&#34;</span> </span></span><span style="display:flex;"><span> ls -lha </span></span><span style="display:flex;"><span> docker-compose -f samples/stack.yml up </span></span><span style="display:flex;"><span><span style="color:#00f">end</span> </span></span></code></pre><p>One thing that I really like about Errand. Yes, this is what it is called. And it is available at <a href="https://git.mitjafelicijan.com/errand.git/about/">https://git.mitjafelicijan.com/errand.git/about/</a>. Moving on. One thing that I really like is that a task is a persistent shell. By that I mean, that the whole task, even if it contains multiple command in one shell. In make each line in a target is that and you need to combine lines or add <code>\</code> at the end of the line.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># How you do this things in make.</span> </span></span><span style="display:flex;"><span>target: </span></span><span style="display:flex;"><span> source .venv/bin/activate <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> python script.py </span></span></code></pre><p>This solves this problem. Consider each task and what is being executed in that task a shell that will only close when all the tasks are completed.</p> <p>By self-documenting I mean that if you are in a directory with <code>Errandfile</code> in, if you only type <code>erd</code> and press enter it should by default display all the possible targets. In make i was doing this by having a first target be something like <code>default</code> that echos the message “Check Makefile for all available target.” Because all of the tasks in Errand require a message I use that to display let’s call it table of contents.</p> <p>Because I don’t use any external dependencies this whole thing can be statically compiled. So that also checked one of the boxes.</p> <p>It works on Linux and on a Mac so that’s also a bonus. I don’t believe this would work on Windows machines because of the way that I use shell instances. By you could use something like Windows Subsystem for Linux and run it in there. That is a valid option.</p> <p>To finish this essay off, how was it to use it in “real life”. I have to be honest. Some of the missing features still bother me. <code>@dotenv</code> directive is still missing and I need to implement this ASAP.</p> <p>Another thing that needs to happen is support for streaming output. Currently commands like <code>docker-compose</code> that runs in foreground mode is not compatible with Errand. So commands that stream output are an issue. I need to revisit how I initiate shell and how I read stdout and stderr. But that shouldn’t be a problem.</p> <p>I have been very satisfied with this thing. I am pleasantly surprised by how useful it is. I really wanted to test this in the wild before I commit to it. I have more abandoned project than Google and it’s bringing a massive shame to my family at this point. So I wanted to be sure that this is even useful. And it actually is. Quite surprised at myself.</p> <p>I really need to package this now and write proper docs. And maybe rewrite tokeniser. Its atrocious right now. Site to behold! But that is an issue for another time.</p> I think I was completely wrong about Git workflows https://mitjafelicijan.com/i-was-wrong-about-git-workflows.html Tue, 23 May 2023 12:00:00 +0200 https://mitjafelicijan.com/i-was-wrong-about-git-workflows.html I have been using some approximation of GitFlow for years now and never reallyquestioned it to be honest. <p>I have been using some approximation of <a href="https://jeffkreeftmeijer.com/git-flow/">Git Flow</a> for years now and never really questioned it to be honest. When I create a repo I create develop branch and set it as default one and then merge to master from there. Seems reasonable enough.</p> <p>One thing that I have learned is that long living branches are the devil. They always end up making a huge mess when they need to be merged eventually into master. So by that reason, what is the develop branch if not the longest living feature branch. And from my personal experience there was never a situation where I wasn’t sweating bullets when I had to merge develop back to master.</p> <p>This realisation started to give me pause. So why the hell am I doing this, and is there a better way. Well the solution was always there. And it comes in a form of <a href="https://git-scm.com/book/en/v2/Git-Basics-Tagging">git tags</a>.</p> <p>So what are git tags? Git tags are references to specific points in a Git repository's history. They are used to mark important milestones, such as releases or significant commits, making it easier to identify and access specific versions of a project.</p> <p>Somehow we have all hijacked the meaning of the master branch that it has to be the most releasable version of code. And this is also where the confusing about versioning the software kicks in. Because master branch implicitly says that we are dealing with the rolling release type of a software. And by having a develop branch we are hacking around this confusion. With a separation of develop and master we lock functionalities into place and forcing a stable vs development version of the software.</p> <p>But if that is true and the long living branches are the devil then why have develop at all. I think that most of this comes to how continuous integration is being done. There usually is no granular access to tags and CD software deploys what is present on a specific branch, may that be master for production and develop for staging. This is a gross simplification and by having this in place we have completely removed tagging as a viable option to create a fix point in software cycle that says, this is the production ready code.</p> <p>One cool thing about tags are that you can checkout a specific tag. So they behave very similarly as branches in that regard. And you don’t have the overhead of having two mainstream branches.</p> <p>So what is the solution? One approach is to use development workflow, where all changes are made on the smaller branches and continuously merged into master. Where the software is ready to be pushed to production you tag the master branch. This approach eliminates the need for long-lived branches and simplifies the development process. It also encourages developers to make small, incremental changes that can be tested and deployed quickly. However, this approach may not be suitable for all projects or teams that heavily rely on automated deployment based on branch names only.</p> <p>This also requires that developers always keep production in mind. No more living on an island of the develop branch. All your actions and code need to be ready to meet production standards on a much smaller timescale.</p> <p>I think that we have complicated the workflow in an honest attempt to make things more streamlined but in the process of doing this, we have inadvertently made our lives much more complicated.</p> <p>In conclusion, it's important to re-evaluate our workflows from time to time to see if they still make sense and if there are better alternatives available. Long-living branches can be problematic, and using tags to mark important milestones can simplify the development process.</p> Rekindling my love for programming and enjoying the act of creating https://mitjafelicijan.com/rekindling-my-love-for-programming.html Tue, 16 May 2023 12:00:00 +0200 https://mitjafelicijan.com/rekindling-my-love-for-programming.html Programming can be a challenging and rewarding experience, but sometimes it&#39;seasy to feel burnt out or disinterested. <p>Programming can be a challenging and rewarding experience, but sometimes it's easy to feel burnt out or disinterested. I have lost the passion for coding over the past couple of months and it looked like I will never enjoy the coding as much as I did.</p> <p>I was feeling burnt out with programming. I thought taking a break from it and focusing on other activities that I enjoy might be helpful. This way, I could come back to programming with a fresh perspective and renewed energy. I also thought about learning a new programming language or technology to keep things interesting and challenging.</p> <p>However, what I didn't realize was that learning a new language or technology wasn't going to solve the underlying issue. I needed to take a step back and re-evaluate why I had lost my passion for programming in the first place. This involved taking a deep look into what I was doing that resulted in this rut.</p> <p>Sometimes, it's easy to get caught up in the hype of new technologies or languages, and we can feel like we're missing out if we're not constantly learning and experimenting. However, it's important to remember that the latest and greatest isn't always the best fit for our projects or our interests. Instead of constantly chasing the next big thing, it can be helpful to focus on what truly interests us and what we're passionate about. This can help us stay motivated and engaged with our work, rather than feeling like we're just going through the motions.</p> <p>I expressed that I had lost my passion for coding over the past couple of months, and I realized that the reason behind it was my tendency to spread myself too thin and not focus on completing interesting projects. In order to regain my passion for coding, I need to focus on projects that truly interest me and give me a sense of purpose and motivation.</p> <p>Recently, I have been playing World of Warcraft more frequently and have become interested in developing addons for the game.</p> <p>This quickly resulted in me creating three addons that improve the quality of life, and I subsequently developed a more useful add-on that encapsulates all the others I made.</p> <p>I found it interesting that this action sparked a new interest in me. Additionally, I discovered the Lua language, which reminded me that coding should be fun rather than just a struggle with a language. It should be pure, unadulterated fun.</p> <p>I wasn't fighting the syntax, nor was I focused on finding the most optimal solution. I simply created things without the pressure of making them the best they could possibly be.</p> <p>This made me realize that I actually adore simple languages that get out of the way and let you express what you want to do. It forced me to rethink a lot about what I use and what I actually enjoy.</p> <p>I have decided to stick to the basics. For a scripting language, I will use Lua. For networking, I will use Golang. And for any special needs, I will rely on C. I do not require Rust, Nim, or Zig. This selection is more than sufficient for my needs. I have to stay true to this simplicity. There is something to the Occam's Razor.</p> <p>I've been struggling with a lack of creativity lately, but now I'm experiencing a real change. I realized I needed to take a step back and stop actively trying to address the issue. I needed to stop worrying and overthinking it. I simply needed some time. Looking back, I don't think I've taken any significant time off in the last 10 years.</p> <p>Suddenly, I find myself with the energy and passion to complete multiple small projects. It doesn't feel like a chore at all. Who knew I needed WoW to kickstart everything. Inspiration really does come from the strangest places.</p> Trying to build a New kind of terminal emulator for the modern age https://mitjafelicijan.com/trying-to-build-a-new-kind-of-terminal-emulator.html Thu, 26 Jan 2023 12:00:00 +0200 https://mitjafelicijan.com/trying-to-build-a-new-kind-of-terminal-emulator.html Over the past few weeks, I have been really thinking about terminal emulators,how we interact with computers, the separation of text-based programs and GUIones. <p>Over the past few weeks, I have been really thinking about terminal emulators, how we interact with computers, the separation of text-based programs and GUI ones. To be perfectly honest, I got pissed off one evening when I was cleaning up files on my computer. Normally, I go into console and do <code>ncdu</code> and check where the junk is. Then I start deleting stuff. Without any discrimination, usually. But when it comes to screenshots, I have learned that it's good to keep them somewhere near if I need to refer to something that I was doing. I am an avid screenshot taker. So at that point I checked Pictures folder and also did a basic search <code>find . -type f -name &quot;*.jpg&quot;</code> for all the JPEG files in my home directory and immediately got pissed off. Why can’t I see thumbnails in my terminal? I know why, but why in the year of 2022 this is still a problem. I am used to traversing my disk via terminal. I am faster, and I am more comfortable this way. But when it comes to visualization, I then need to revert to GUI applications and again find the same file to see it. I know that programs like <code>feh</code> and <code>sxiv</code> are available, but I would just like to see the preview. Like <a href="https://jupyter.org/">Jupyter notebook</a> or something similar. Just having it inline. Part of a result.</p> <p>It also didn’t help that I was spending some time with the <a href="https://plan9.io/plan9/">Plan 9</a> Operating system. More specifically <a href="http://9front.org/">9FRONT</a>. The way that <a href="http://acme.cat-v.org/">ACME editor</a> handles text editing is just wonderful. Different and fresh somehow, even though it’s super old.</p> <p>So, I went on a lookout for an interesting way of visualizing results of some query. I found these applications to be outstanding examples of how not to be a captive of a predetermined way of doing things.</p> <ul> <li><a href="https://www.wolfram.com/mathematica/">Wolfram Mathematica</a></li> <li><a href="https://jupyter.org/">Jupyter notebooks</a></li> <li><a href="http://www.9front.org">Plan 9 / 9FRONT</a></li> <li><a href="https://templeos.org/">Temple OS</a></li> <li><a href="https://www.gnu.org/software/emacs/">Emacs</a></li> </ul> <p>My idea is not as out there as ACME is, but it is a spin on the terminal emulators. I like the modes that Vi/Vim provides you with. I like the way the Emacs does its own <code>M-x</code> <code>M-c</code>. Furthermore, I really like how Mathematica and Jupyter present the data in a free flowing form. And I love how Temple OS is basically a C interpreter on some level.</p> <blockquote> <p><strong>Note:</strong> This is part 1 of the journey. Nowhere finished yet. I am just tinkering with this at the moment. This whole thing can easily spectacularly fail.</p> </blockquote> <p>So I started. I knew that I wanted to have the couple of modes, but I didn’t like the repetition of keystrokes, so the only option was to have some sort of toggle and indicate to the user that they are in a special mode. Like Vi does for Normal and Visual mode.</p> <p>These modes would for the first version be:</p> <ul> <li><em>Preview mode</em> (toggle with Ctrl + P) <ul> <li>When this mode would be enabled, the <code>ls</code> command would try to find images from the results and display thumbnails from them in the terminal itself. No ASCII art. Proper images. In a grid!</li> </ul> </li> <li><em>Detach mode</em> (toggle with Ctrl + D) <ul> <li>When this mode would be enabled, every command would open a new window and execute that command in it. This would be useful for starting <code>htop</code> in a separate window.</li> </ul> </li> </ul> <p>The reason for having these modes togglable is to not ask for previews every time. You enable a mode and until you disable it, it behaves that way. Purely out of ergonomic reasons.</p> <p>I would like to treat every terminal I open as a session mentally. When I start using the terminal, I start digging deeper into the issue I am trying to resolve. And while I am doing this, I would like to open detached windows etc. A lot of these things can be done easily with something like <a href="https://i3wm.org/">i3</a>, but also that pull you out of the context of what you were doing. I would like to orchestrate everything from one single point.</p> <p>In planning for this project, I knew that I would need to use a language like C and a library such as <a href="https://www.libsdl.org/">SDL2</a> in order to achieve the desired results. I had considered other options, but ultimately determined that <a href="https://www.libsdl.org/">SDL2</a> was the best fit based on its capabilities and reputation in the programming community.</p> <p>At first, I thought the idea of a hardware accelerated terminal was a bit of a joke. It seemed like such a niche and unnecessary feature, especially given the fact that terminal emulators have been around for decades and have always relied on software rendering. But to be fair, <a href="https://alacritty.org/">Alacritty</a> is doing the same thing. Well, they are doing a remarkable job at it.</p> <p>So, I embarked on a journey. Everything has to start somewhere. For me, it started with creating a window! It has to start somewhere. 🙂</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000">// Oh, Hi Mark! </span></span></span><span style="display:flex;"><span><span style="color:#008000">// Create the window, obviously. </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span>SDL_Window *window = SDL_CreateWindow( </span></span><span style="display:flex;"><span> WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, </span></span><span style="display:flex;"><span> WINDOW_WIDTH, WINDOW_HEIGHT, </span></span><span style="display:flex;"><span> SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); </span></span></code></pre><p>I continued like this to get some text displayed on the screen.</p> <p>I noted that <a href="https://wiki.libsdl.org/SDL_ttf/TTF_RenderText_Solid"><code>TTF_RenderText_Solid</code></a> rendered text really poorly. There were no antialiasing at all. In my wisdom, I never checked the documentation. Well, that was a fail. To uneducated like me: <code>TTF_RenderText_Solid</code> renders Latin1 text at fast quality to a new 8-bit surface. So, that's why the texts looked like shit. No wonder.</p> <p>Remarks on <code>TTF_RenderText_Solid</code>: This function will allocate a new 8-bit, palettized surface. The surface's 0 pixel will be the colorkey, giving a transparent background. The 1 pixel will be set to the text color.</p> <p>After I replaced it with <a href="https://wiki.libsdl.org/SDL_ttf/TTF_RenderText_LCD"><code>TTF_RenderText_LCD</code></a> which renders Latin1 text at LCD subpixel quality to a new ARGB surface, the text started looking good. Really make sure you read the documentation. It’s actually good. As a side note, you can find all the documentation regarding <a href="https://wiki.libsdl.org/">SDL2 on their Wiki</a>.</p> <p>After that was done, I started working on displaying other things like <code>Preview</code> and <code>Detach</code> modes. This wasn’t really that hard. In SDL2 you can check all the available events with <code>while (SDL_PollEvent(&amp;event) &gt; 0)</code> and have a bunch of switch statements to determine which key is currently being pressed. More about keys, <a href="https://documentation.help/SDL/sdlkey.html">SDLKey</a> and mroe about pooling the events on <a href="https://documentation.help/SDL/sdlpollevent.html">SDL_PollEvent</a>.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">while</span> (SDL_PollEvent(&amp;event) &gt; 0) </span></span><span style="display:flex;"><span>{ </span></span><span style="display:flex;"><span> <span style="color:#00f">switch</span> (event.type) </span></span><span style="display:flex;"><span> { </span></span><span style="display:flex;"><span> <span style="color:#00f">case</span> SDL_QUIT: </span></span><span style="display:flex;"><span> running = false; </span></span><span style="display:flex;"><span> <span style="color:#00f">break</span>; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">case</span> SDL_TEXTINPUT: </span></span><span style="display:flex;"><span> <span style="color:#00f">if</span> (!meta_key_pressed) </span></span><span style="display:flex;"><span> { </span></span><span style="display:flex;"><span> strncat(input_prompt_text, event.text.text, 1); </span></span><span style="display:flex;"><span> update_input_prompt = true; </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> <span style="color:#00f">break</span>; </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span>} </span></span></code></pre><p>After that was somewhat working correctly, I started creating a struct that would hold all the commands and results and I call them Cells. Yes, I stole that naming idea from Jupyter.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">typedef</span> <span style="color:#00f">struct</span> </span></span><span style="display:flex;"><span>{ </span></span><span style="display:flex;"><span> <span style="color:#2b91af">char</span> *command; </span></span><span style="display:flex;"><span> <span style="color:#2b91af">char</span> *result; </span></span><span style="display:flex;"><span> SDL_Surface *surface; </span></span><span style="display:flex;"><span> SDL_Texture *texture; </span></span><span style="display:flex;"><span> SDL_Rect rect; </span></span><span style="display:flex;"><span>} Cell; </span></span></code></pre><p>I am at a place now where I am starting to implement scrolling. This will for sure be fun to code. Memory management in C is super easy. 😂</p> <p>I have also added a simple <a href="https://en.wikipedia.org/wiki/INI_file">INI file like configuration</a> support. It is done in an <a href="https://github.com/nothings/stb/blob/master/docs/stb_howto.txt">STB style of header</a> and maps to specific options supported by the terminal. It is not universal, and the code below demonstrates how I will use it in the future.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">#ifndef CONFIG_H </span></span></span><span style="display:flex;"><span><span style="color:#00f">#define CONFIG_H </span></span></span><span style="display:flex;"><span><span style="color:#00f"></span> </span></span><span style="display:flex;"><span><span style="color:#008000">/* </span></span></span><span style="display:flex;"><span><span style="color:#008000"># This is a comment </span></span></span><span style="display:flex;"><span><span style="color:#008000"> </span></span></span><span style="display:flex;"><span><span style="color:#008000"># This is the first configuration option </span></span></span><span style="display:flex;"><span><span style="color:#008000">dettach=value11111 </span></span></span><span style="display:flex;"><span><span style="color:#008000"> </span></span></span><span style="display:flex;"><span><span style="color:#008000"># This is the second configuration option </span></span></span><span style="display:flex;"><span><span style="color:#008000">preview=value22222 </span></span></span><span style="display:flex;"><span><span style="color:#008000"> </span></span></span><span style="display:flex;"><span><span style="color:#008000"># This is the third configuration option </span></span></span><span style="display:flex;"><span><span style="color:#008000">debug=value33333 </span></span></span><span style="display:flex;"><span><span style="color:#008000">*/</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000">// Define a struct to hold the configuration options </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span><span style="color:#00f">typedef</span> <span style="color:#00f">struct</span> </span></span><span style="display:flex;"><span>{ </span></span><span style="display:flex;"><span> <span style="color:#2b91af">char</span> dettach[256]; </span></span><span style="display:flex;"><span> <span style="color:#2b91af">char</span> preview[256]; </span></span><span style="display:flex;"><span> <span style="color:#2b91af">char</span> debug[256]; </span></span><span style="display:flex;"><span>} Config; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000">// Read the configuration file and return the options as a struct </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span><span style="color:#00f">extern</span> Config read_config_file(<span style="color:#00f">const</span> <span style="color:#2b91af">char</span> *filename) </span></span><span style="display:flex;"><span>{ </span></span><span style="display:flex;"><span> <span style="color:#008000">// Create a struct to hold the configuration options </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> Config config = {0}; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">// Open the configuration file </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> FILE *file = fopen(filename, <span style="color:#a31515">&#34;r&#34;</span>); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">// Read each line from the file </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> <span style="color:#2b91af">char</span> line[256]; </span></span><span style="display:flex;"><span> <span style="color:#00f">while</span> (fgets(line, <span style="color:#00f">sizeof</span>(line), file)) </span></span><span style="display:flex;"><span> { </span></span><span style="display:flex;"><span> <span style="color:#008000">// Check if this line is a comment or empty </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> <span style="color:#00f">if</span> (line[0] == <span style="color:#a31515">&#39;#&#39;</span> || line[0] == <span style="color:#a31515">&#39;\n&#39;</span>) </span></span><span style="display:flex;"><span> <span style="color:#00f">continue</span>; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">// Parse the line to get the option and value </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> <span style="color:#2b91af">char</span> option[128], value[128]; </span></span><span style="display:flex;"><span> <span style="color:#00f">if</span> (sscanf(line, <span style="color:#a31515">&#34;%[^=]=%s&#34;</span>, option, value) != 2) </span></span><span style="display:flex;"><span> <span style="color:#00f">continue</span>; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">// Set the value of the appropriate option in the config struct </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> <span style="color:#00f">if</span> (strcmp(option, <span style="color:#a31515">&#34;dettach&#34;</span>) == 0) </span></span><span style="display:flex;"><span> { </span></span><span style="display:flex;"><span> strncpy(config.option1, value, <span style="color:#00f">sizeof</span>(config.option1)); </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> <span style="color:#00f">else</span> <span style="color:#00f">if</span> (strcmp(option, <span style="color:#a31515">&#34;preview&#34;</span>) == 0) </span></span><span style="display:flex;"><span> { </span></span><span style="display:flex;"><span> strncpy(config.option2, value, <span style="color:#00f">sizeof</span>(config.option2)); </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> <span style="color:#00f">else</span> <span style="color:#00f">if</span> (strcmp(option, <span style="color:#a31515">&#34;debug&#34;</span>) == 0) </span></span><span style="display:flex;"><span> { </span></span><span style="display:flex;"><span> strncpy(config.option3, value, <span style="color:#00f">sizeof</span>(config.option3)); </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">// Close the configuration file </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> fclose(file); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">// Return the configuration options </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> <span style="color:#00f">return</span> config; </span></span><span style="display:flex;"><span>} </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">#endif </span></span></span></code></pre><p>This is as far as I managed to get for now. I have a daily job and this prohibits me to work on these things full time. But I should probably get back and finish this. At least have a simple version working out, so I can start testing it on my machines. Fingers crossed. 🕵️‍♂️</p> Microsoundtrack — That sound that machine makes when struggling https://mitjafelicijan.com/that-sound-that-machine-makes-when-struggling.html Sun, 16 Oct 2022 12:00:00 +0200 https://mitjafelicijan.com/that-sound-that-machine-makes-when-struggling.html A couple of months ago, I got an idea about micro soundtracks. <p>A couple of months ago, I got an idea about micro soundtracks. In this concept, you are the observer, director, and audience in this tiny movies.</p> <p>What you do is to attempt to imagine what would be happening around you based on a title of the song and let the song help you fill the void in your story.</p> <p>I made these songs is Logic Pro X. Every year or so I do this kind of thing and make a couple of songs similar to this. But this is the first time I am posting about it.</p> <p>You can listen to the whole set on <a href="https://www.youtube.com/watch?v=_5oXBhSmF3c">Youtube</a> or scroll down the page and there are embedded players for each song.</p> <h2 id="a-bunch-of-inter-dimensional-people-with-loud-clocks">A bunch of inter-dimensional people with loud clocks</h2> <p>A group of inter-dimensional people are going up and down the elevator with you while having loud clocks around their necks. Each clock ticks on a different frequency. A lot of other sounds are getting drawn into your dimension, resulting in a strange merging of dimensions.</p> <iframe style="border: 0; width: 100%; height: 42px;" src="https://bandcamp.com/EmbeddedPlayer/album=3913808801/size=small/bgcol=ffffff/linkcol=0687f5/track=1349272965/transparent=true/" seamless title="Bandcamp"><a href="https://mitjafelicijan.bandcamp.com/album/that-sound-that-machine-makes-when-struggling">That sound that machine makes when struggling by Mitja Felicijan</a></iframe> <h2 id="two-black-holes-conversing-about-the-weather">Two black holes conversing about the weather</h2> <p>You are a traveler in a spaceship flying very close to two colliding black holes having a discussion about the weather while tearing each other apart. During all this your ship is getting pulled into the event horizon of both black holes, putting a lot of strain on your spaceship.</p> <iframe style="border: 0; width: 100%; height: 42px;" src="https://bandcamp.com/EmbeddedPlayer/album=3913808801/size=small/bgcol=ffffff/linkcol=0687f5/track=1756714200/transparent=true/" seamless title="Bandcamp"><a href="https://mitjafelicijan.bandcamp.com/album/that-sound-that-machine-makes-when-struggling">That sound that machine makes when struggling by Mitja Felicijan</a></iframe> <h2 id="a-planet-where-every-organism-is-a-plant">A planet where every organism is a plant</h2> <p>You land on a planet where every living organism is a plant and among those plants some of them are highly intelligent, and you were asked to make first contact with the native species. Your visit takes place in a giant cave where you are meeting these plants, and they are talking to you.</p> <iframe style="border: 0; width: 100%; height: 42px;" src="https://bandcamp.com/EmbeddedPlayer/album=3913808801/size=small/bgcol=ffffff/linkcol=0687f5/track=3710973979/transparent=true/" seamless title="Bandcamp"><a href="https://mitjafelicijan.bandcamp.com/album/that-sound-that-machine-makes-when-struggling">That sound that machine makes when struggling by Mitja Felicijan</a></iframe> <h2 id="bio-implants-having-a-fit-and-reprogramming-your-brain">Bio implants having a fit and reprogramming your brain</h2> <p>In a distant future where everybody has bio implants, you have just received your first one, which happens to be a brain implant. Something goes wrong, and your implant is starting to misbehave, and you are experiencing brain malfunctions. You are on the streets at night a couple of hours after your procedure. You can feel your sanity breaking down.</p> <iframe style="border: 0; width: 100%; height: 42px;" src="https://bandcamp.com/EmbeddedPlayer/album=3913808801/size=small/bgcol=ffffff/linkcol=0687f5/track=1157430581/transparent=true/" seamless title="Bandcamp"><a href="https://mitjafelicijan.bandcamp.com/album/that-sound-that-machine-makes-when-struggling">That sound that machine makes when struggling by Mitja Felicijan</a></iframe> <h2 id="cow-animation">Cow animation</h2> <p>I also made this little cow animation. Go into full screen to see the effects in more details.</p> <p><video src="/posts/microsoundtrack/cow.m4v" controls loop></video></p> State of Web Technologies and Web development in year 2022 https://mitjafelicijan.com/state-of-web-technologies-and-web-development-in-year-2022.html Thu, 06 Oct 2022 12:00:00 +0200 https://mitjafelicijan.com/state-of-web-technologies-and-web-development-in-year-2022.html Initial thoughtsThis post is a critique on the current state of web development. <h2 id="initial-thoughts">Initial thoughts</h2> <p><em>This post is a critique on the current state of web development. It is an opinionated post! I will learn more about this in the future, and probably slightly change my mind about some of the things I criticize.</em></p> <p>I have started working on a hobby project about two weeks ago, and I wanted to use that situation as a learning one. Trying new things, new technologies, new tools. I always considered myself to be an adventurous person when it comes to technology. I never shy away from trying new languages, new operating systems etc. Likewise, I find the whole experience satisfying, and it tickles that part of my brain that finds discovery the highest of the mountains to climb.</p> <p>What I always wanted to make was a coding game, that you would play in a browser (just to eliminate building binaries for each operating system) where you would level up your character and go into these scriptable battles. You know, RPG elements.</p> <p>So, the natural way to go would be some sort of SPA (single page application) with basic routing and some state management. Nothing crazy.</p> <blockquote> <p><strong>Before we move on</strong>, I have to be transparent. Take my views on this with a grain of salt. I have only scratched the surface with these technologies, and my knowledge is full of gaps. This is my experience using some of these products for the first time or in a limited capacity.</p> </blockquote> <p>Having this out of the way, I got myself a fresh pot of coffee and down the rabbit hole I went.</p> <h2 id="giving-react-js-a-spin">Giving React JS a spin</h2> <p>I first tried <a href="https://reactjs.org/">React JS</a>. I kind of like it. Furthermore, I have worked with libraries like this in the past and also wrote a couple of them (nothing compared to that level), but I had the basic understanding of what was going on. I rolled up a project quickly and had basic things done in a matter of two hours, which was impressive.</p> <p>I prefer using <a href="https://tailwindcss.com/">Tailwind CSS</a> for my styling pleasures, and integrating that was also a painless experience. It was actually nice to see that some things got better with time. In about 2 minutes I got Tailwind working, and I was able to use classes at my disposal. All that <code>postcss</code> stuff was taken care of by adding a couple of things in config files (all described really well in their documentation).</p> <p>It is not that different from Vue which I have had more encounters with in the past People will probably call me a lunatic for saying this. But you know, it is the truth. Same same, but different. I still believe that using libraries like this is beneficial. I am not a JavaScript purist. They all have their quirks, but at the end of the day, I truly believe it’s worth it.</p> <h2 id="bundlers-and-transpilers">Bundlers and Transpilers</h2> <p>I still reject calling <a href="https://www.typescriptlang.org/">Typescript</a> to <a href="https://www.javascript.com/">JavaScript</a> conversion a &quot;compilation process&quot;. I call them <a href="https://devopedia.org/transpiler">transpilers</a>, and I don’t care! 😈</p> <p>And if you want to fight this, take a look at this little chart and be mad at it!</p> <figure> <img src="/posts/state-of-web/compiling-vs-transpiling.png" alt="Compiling vs Transpiling" /> </figure> <p>The first one that I ever used was <a href="https://webpack.js.org/">webpack</a>, and it was an absolute horrific experience. Saying this, it is an absolutely fantastic tool. I felt more like a config editor than actually a programmer. To be fair, I am a huge fan of <a href="https://www.gnu.org/software/make/">make</a>, and you can do as you wish with this information. I like my build systems simple.</p> <p>Also, isn’t it interesting that we need something like <a href="https://babeljs.io/">Babel</a> to make JavaScript code work in a browser that has only one client side scripting available, which is by no accident also JavaScript. Why? I know why it’s needed, but seriously, why.</p> <p>I haven’t used Babel for years now. Or if I did, it was packaged together by some other bundler thingy. Which does not make things better, but at least I didn’t need to worry about it.</p> <p>I really don’t like complicated build systems. I really don’t like abstracting code and making things appear magical. The older I get, the more I appreciate clear and clean, expressive code. No one-liners, if possible.</p> <p>But I have to give props to <a href="https://vitejs.dev/">Vite</a>! This was one of the best developer experiences I have ever had. Granted, it still has magical properties. And yes, it still is a bundler and abstracts things to the nth degree. But at least it didn’t force me to configure 700 lines of JSON. And I know that this makes me a hypocrite. You can’t have it all. Nonetheless, my reasoning here is, if using bundlers is inevitable, then at least they should provide an excellent developer experience.</p> <p>I also noticed that now the catch-all phrase is “blazingly fast” and “lightning fast” and “next generation” and stuff like that. I mean, yeah, tools should get faster with time. But saying that starting a project now takes 2 seconds instead of 20 seconds is something that is a break it or make it kind of a deal is ridiculous. I don’t mind waiting a couple of seconds every couple of days. I also don’t create 700 projects every day, and also who does? This argument has no bite. All I want is a decent reload time (~100ms is more than good enough for me) and that is it.</p> <p>You don’t need to sell me benefits if I only get them when I start a fresh project, and then try to convince me that this is somehow changing the fate of the universe. First of all, it is not. And second, if this is your only argument for your tool, I would advise you to maybe re-focus your efforts to something else. Vite says that startup times are really fast. And if that would be the only thing differentiating it from other tools, I would ignore it. But it has some really compelling features like <a href="https://www.geeksforgeeks.org/reactjs-hot-module-replacement/">Hot Module Replacement</a> that really works well. It was a joy to use.</p> <p>So, I will be definitely using Vite in the future.</p> <h2 id="jam-stack-mach-stack-no-snack">Jam Stack, Mach Stack no snack</h2> <p>Let's get a couple of the acronyms out of the way, so we all know what we are talking about:</p> <ul> <li>Jam Stack - JavaScript, API and Markup</li> <li>Mach Stack - Microservices, API-first, Cloud-Native SaaS, Headless</li> </ul> <p>It is so hard to follow all these new trendy things happening around you, that it makes you have a massive <strong>FOMO</strong> all the time. But on the other hand, you also don’t want to be that old fart that doesn’t move with the times and still writes his trusty jQuery code while listening to Blink 182 All the small things on full blast. It’s a good song, don’t get me wrong, but there are other songs out there.</p> <p>I have to admit. <a href="https://vercel.com/">Vercel</a> is really cool! Love the simplicity of the service. You could compare it to <a href="https://www.netlify.com/">Netlify</a>. I haven’t tried Netlify extensively, but from a couple of experimental deployments I still prefer Vercel. It is much more streamlined, but maybe this is bias in me. I really like Vercel’s Analytics, which give you a <a href="https://web.dev/vitals/">Core Web Vitals report</a> in their admin console. Kind of cool, I’m not going to lie.</p> <p>This whole idea about frontend and backend merging into <a href="https://www.debugbear.com/blog/server-side-rendering">SSR (server-side rendering)</a> looks so good on paper. It almost doesn’t come with any major flaws.</p> <p>But when it comes to the actual implementation, there is much to be desired. I’m going to lump <a href="https://nextjs.org/">Next.js</a> and <a href="https://nuxtjs.org/">Nuxt.js</a> together because they are essentially the same thing, just a different library.</p> <p>Now comes the reality. Mixing backend and frontend in this manner creates this weird mental model where you kind of rely on magical properties of these libraries. You relinquish control over to them for better developer experience. But is that really true? Initially, I was so stoked about it. However, the more I used them, the more I felt uncomfortable. I felt dirty, actually. Maybe this is because I come from old ways of doing things where you control every step of request, and allowing something to hijack it feels like blasphemy.</p> <p>More than that, some pretty significant technical issues arose from this. How do you do JWT token authentication? You put it in <code>api</code> folder and then do some fetching and storing into local state management. But doing this also requires some tinkering with await/async stuff on the React/Vue side of things. And then you need to write middleware for it. And the more I look at it, the more I see that this whole thing was not meant to be used like this, and it all feels and looks like a huge hack.</p> <p>The issue I have with this is that they over-promise and under-deliver. They want to be an all-in-one replacement for everything, and they don’t deliver on this promise. And how could they?! We have to be fair. It is an impossible task.</p> <p>They sell you <a href="https://www.geeksforgeeks.org/overview-of-noops/">NoOps</a>, but when you need to accomplish something a little bit more out of the scope of Hello World, you have to make hacky decisions to make it work. And having a deployment strategy that relies on many moving parts is never a good idea. Abstracting too much is usually a sign of bad architecture.</p> <p>Lately, this has become a huge trend that will for sure bite us in the future. And let’s not get it twisted. By doing this, PaaS providers like <a href="https://aws.amazon.com/">AWS</a>, <a href="https://cloud.google.com/">GCS</a>, etc. obscure their billing, and you end up paying more than you really should. And even if that is not an issue, it comes down to the principle of things. AWS is known for having multiple “currencies“ inside their projects like write operations, read operations, etc. which add up, and it creates this impossible to track billing scheme. It all behaves suspiciously like a pay-to-win game you could find on mobile phones that scams you out of your money.</p> <p>And as far as I am concerned, the most important thing was me not coding the functionalities for the game I want to make. I was battling libraries and cloud providers. How to deploy, what settings are relevant. Bad documentation or multiple versions of achieving the same thing. You are getting bombarded by all this information, and you don’t really have any control over it. Production-ready code becomes a joke, essentially. Especially if you tend to work on that project for a prolonged period of time.</p> <p>All of these options end up creating a fatigue. What to choose, what not to choose. Unnecessary worrying about if the stack will still be deemed worthy in six months. There is elegance in simplicity.</p> <blockquote> <p>JavaScript UI frameworks and libraries work in cycles. Every six months or so, a new one pops up, claiming that it has revolutionized UI development. Thousands of developers adopt it into their new projects, blog posts are written, Stack Overflow questions are asked and answered, and then a newer (and even more revolutionary) framework pops up to usurp the throne. — Ian Allen</p> </blockquote> <figure> <img src="/posts/state-of-web/2008-vs-2020.png" alt="To many options" /> </figure> <p>And this jab at these libraries and cloud providers is not done out of malice. It is a real concern that I have about them. In my life, I have seen technologies come and go, but the basics always stick around. So surrendering all the power you have to a library or a cloud provider is in my opinion a stupid move.</p> <h2 id="tailwind-css-still-rocks">Tailwind CSS still rocks!</h2> <p>You know, many people say negative things about Tailwind. And after a lot of deliberation, I came to the conclusion that Tailwind is good for two types of developers. Tailwind is good for a complete noob or a senior developer. A complete noob doesn’t really care about inner workings of CSS, and a senior developer also doesn’t care about CSS. Well, at least, not anymore. And developers in between usually have the biggest issues with it. Not always of course, but in a lot of cases.</p> <p>I like the creature comforts of Tailwind. Being utility first would make me argue that it is actually more similar to <a href="https://sass-lang.com/">Sass</a> or <a href="https://lesscss.org/">Less</a> than something like Bootstrap. Not technically, but ideologically. After I started using it, I never looked back. I use it every time I need to do something web related.</p> <p>Writing CSS for general things feels like going several steps back. Instead of focusing on what you are actually trying to achieve, you focus on notations like <a href="https://en.bem.info/methodology/css/">BEM</a>, code structuring, optimizing HTML size. Just doing things that make 0.1% difference. You know that saying: Early optimization is the root of all evil. Exactly that.</p> <p>I am also not saying that Tailwind is the cure for everything. Sometimes custom CSS is necessary. But from what I found out in using it for almost two years in a production environment (on a site getting quite a lot of traffic and constantly being changed), I can say without any reservations that Tailwind saved our asses countless times. We would be rewriting CSS all the time without it. And I don’t really think writing CSS is the best way to spend my time.</p> <p>I have also noticed that people who criticize Tailwind the most never actually used it in a real project that has a long lifetime with plenty of changes that will happen in the future.</p> <p>But you know, whatever floats your boat!</p> <h2 id="code-maintainability">Code maintainability</h2> <p>Somehow, people also stopped talking about maintenance. If you constantly try to catch the latest and greatest train, you are by that logic always trying new things. Which is a good thing if you want to learn about technologies and try them. But for the production environment, you have to have a stable stack that doesn’t change every 6 months.</p> <p>You can lock dependencies for sure. Nevertheless, the hype train moves along anyway. And the mindset this breeds goes against locking the code. This bleeding-edge rolling release cycle is not helping. That is why enterprise solutions usually look down on these popular stacks and only do bare minimum to appear hip and cool.</p> <p>With that said, I still think that progress is good, but should be taken with a grain of salt. If your project is something that should be built once and then rarely updated, going with the latest stack is a possible way to go. But, if you are working on a project that lasts for years, you should probably approach it with some level of caution. Web development is often times too volatile.</p> <h2 id="web-development-has-a-marketing-issue">Web development has a marketing issue</h2> <p>I noticed that almost every project now has this marketing spin put on it. Everything is blazingly fast now. I get it, they are competing for your attention, but what happened to just being truthful and not inflating reality.</p> <p>And in order to appeal to mass market, they leave things out of their marketing materials. These open-source projects are now behaving more and more like companies do. Which is a scary thought on its self.</p> <p>And we are also seeing a rise in a concept of building a company in the open, which is a good thing, don't get me wrong. But when it is using open-source to lure people and then lock them in their ecosystem, there is where I have issues with it.</p> <p>This might be because I have been using GNU/Linux for 20 years now and have been so beholden for my success to open-source that I see issues when open-source is being used to trick people into a false sense of security that these projects are built in the spirit of open-source. Because there is a difference. They are NOT! They have a really specific goal in mind. And the open-source is being used as a delivery system. Which is in my opinion disgusting!</p> <h2 id="conclusion">Conclusion</h2> <p>I will end my post with this. Web development is running now in circles. People are discovering <a href="https://www.tutorialspoint.com/remote-procedure-call-rpc">RPC</a> now and this is the now the next big thing. <a href="https://graphql.org/">GraphQL</a> is so passé. And I am so tired of it all. Of blazingly fast libraries, of all these new technologies that are actually just a remake of old ones. Of just the general spirit of the web. I will just use what I already know. Which worked 10 years ago and will work 10 years after this. I will adopt a couple of little tools like Vite. But I will not waste my time on this anymore.</p> <p>It was a good exercise to get in touch with what’s new now. Nothing really changed that much. FOMO is now cured! Now I have to get my ass back to actually code and make the project that I wanted to make in the first place.</p> Aerial photography of algae spotted on river Sava https://mitjafelicijan.com/aerial-photography-of-algae-spotted-on-river-sava.html Sat, 13 Aug 2022 12:00:00 +0200 https://mitjafelicijan.com/aerial-photography-of-algae-spotted-on-river-sava.html This is a bit of a different post than I usually write, but quite interestingone to me. <p>This is a bit of a different post than I usually write, but quite interesting one to me. River Sava has plenty of hydropower plants located down the stream. This makes regulating the strength of a current easier than normally. Because of lower stream strength and high temperatures, algae has formed on the river. This is the first time I've seen something like this in my whole life.</p> <p>Below are some photographs taken from a DJI drone capturing the event.</p> <figure> <img src="/posts/algae-sava/dji-algae-0.jpg" alt="Algae on Sava" /> </figure> <figure> <img src="/posts/algae-sava/dji-algae-1.jpg" alt="Algae on Sava" /> </figure> <figure> <img src="/posts/algae-sava/dji-algae-2.jpg" alt="Algae on Sava" /> </figure> <figure> <img src="/posts/algae-sava/dji-algae-3.jpg" alt="Algae on Sava" /> </figure> <figure> <img src="/posts/algae-sava/dji-algae-4.jpg" alt="Algae on Sava" /> </figure> <figure> <img src="/posts/algae-sava/dji-algae-5.jpg" alt="Algae on Sava" /> </figure> <p>I will try to get more photos of this in the future days and if something intriguing shows up will post it again on the blog.</p> What would DNA sound if synthesized to an audio file https://mitjafelicijan.com/what-would-dna-sound-if-synthesized.html Tue, 05 Jul 2022 12:00:00 +0200 https://mitjafelicijan.com/what-would-dna-sound-if-synthesized.html IntroductionLately, I have been thinking a lot about the nature of life, what are thefoundation blocks of life and things like that. <h2 id="introduction">Introduction</h2> <p>Lately, I have been thinking a lot about the nature of life, what are the foundation blocks of life and things like that. It's remarkable how complex and on the other hand simple the creation is when you look at it. The miracle of life keeps us grounded when our imagination goes wild. If the DNA are the blocks of life, you could consider them to be an API nature provided us to better understand all of this chaos masquerading as order.</p> <p>I have been reading a lot about superintelligence and our somehow misguided path to create general artificial intelligence. What would the building blocks or our creation look like? Is the compression really the ultimate storage of information? Will our creation also ponder this questions when creating new worlds for themselves, or will we just disappear into the vastness of possibilities? It is a little offensive that we are playing God whilst being completely ignorant of our own reality. Who knows! Like many other breakthroughs, this one will also come at a cost not known to us when it finally happens.</p> <p>To keep things a bit lighter, I decided to convert some popular DNA sequences into an audio files for us to listen to. I am not the first one, nor I will be the last one to do this. But it is an interesting exercise in better understanding the relationship between art and science. Maybe listening to DNA instead of parsing it will find a way into better understanding, or at least enjoying the creation and cryptic nature of life.</p> <h2 id="dna-encoding-and-primer-example">DNA encoding and primer example</h2> <p>I have been exploring DNA in the past in my post from about 3 years ago in <a href="/encoding-binary-data-into-dna-sequence.html">Encoding binary data into DNA sequence</a> where I have been converting all sorts of data into DNA sequences.</p> <p>This will be a similar exercise but instead of converting to DNA, I will be generating tones from Nucleotides.</p> <table> <thead> <tr> <th>Nucleotides</th> <th>Note</th> <th>Frequency</th> </tr> </thead> <tbody> <tr> <td><strong>A</strong> (Adenine)</td> <td>A</td> <td>440 Hz</td> </tr> <tr> <td><strong>C</strong> (Cytosine)</td> <td>C</td> <td>783.99 Hz</td> </tr> <tr> <td><strong>G</strong> (Guanine)</td> <td>G</td> <td>523.25 Hz</td> </tr> <tr> <td><strong>T</strong> (Thymine)</td> <td>D</td> <td>587.33 Hz</td> </tr> </tbody> </table> <p>Since we do not have T in equal-tempered scale, I choose D to represent T note.</p> <p>You can check <a href="https://pages.mtu.edu/~suits/notefreqs.html">Frequencies for equal-tempered scale, A4 = 440 Hz</a>. For this tuning, we also choose <code>Speed of Sound = 345 m/s = 1130 ft/s = 770 miles/hr</code>.</p> <p>Now that we have this out of the way, we can also brush up on the DNA sequencing a bit. This is a famous quote I also used for the encoding tests, and it goes like this.</p> <blockquote> <p>How wonderful that we have met with a paradox. Now we have some hope of making progress. ― Niels Bohr</p> </blockquote> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>&gt;SEQ1 </span></span><span style="display:flex;"><span>GACAGCTTGTGTACAAGTGTGCTTGCTCGCGAGCGGGTACGCGCGTGGGCTAACAAGTGA </span></span><span style="display:flex;"><span>GCCAGCAGGTGAACAAGTGTGCGGACAAGCCAGCAGGTGCGCGGACAAGCTGGCGGGTGA </span></span><span style="display:flex;"><span>ACAAGTGTGCCGGTGAGCCAACAAGCAGACAAGTAAGCAGGTACGCAGGCGAGCTTGTCA </span></span><span style="display:flex;"><span>ACTCACAAGATCGCTTGTGTACAAGTGTGCGGACAAGCCAGCAGGTGCGCGGACAAGTAT </span></span><span style="display:flex;"><span>GCTTGCTGGCGGACAAGCCAGCTTGTAAGCGGACAAGCTTGCGCACAAGCTGGCAGGCCT </span></span><span style="display:flex;"><span>GCCGGCTCGCGTACAAATTCACAAGTAAGTACGCTTGCGTGTACGCGGGTATGTATACTC </span></span><span style="display:flex;"><span>AACCTCACCAAACGGGACAAGATCGCCGGCGGGCTAGTATACAAGAACGCTTGCCAGTAC </span></span><span style="display:flex;"><span>AACC </span></span></code></pre><p>This is what we gonna work with to get things rolling forward, when creating parser and waveform generator.</p> <h2 id="parsing-dna-data">Parsing DNA data</h2> <p>This step is rather simple one. All we need to do is parse input DNA sequence in <a href="https://en.wikipedia.org/wiki/FASTA_format">FASTA format</a> well known in <a href="https://en.wikipedia.org/wiki/Bioinformatics">Bioinformatics</a> to extract single Nucleotides that will be converted into separate tones based on equal-tempered scale explained above.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>nucleotide_tone_map = { </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;A&#39;</span>: 440, </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;C&#39;</span>: 523.25, </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;G&#39;</span>: 783.99, </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;T&#39;</span>: 587.33, <span style="color:#008000"># converted to D</span> </span></span><span style="display:flex;"><span>} </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">def</span> split(word): </span></span><span style="display:flex;"><span> <span style="color:#00f">return</span> [char <span style="color:#00f">for</span> char <span style="color:#00f">in</span> word] </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">def</span> generate_from_dna_sequence(sequence): </span></span><span style="display:flex;"><span> <span style="color:#00f">for</span> nucleotide <span style="color:#00f">in</span> split(sequence): </span></span><span style="display:flex;"><span> print(nucleotide, nucleotide_tone_map[nucleotide]) </span></span></code></pre><h2 id="generating-sine-wave">Generating sine wave</h2> <p>Because we are essentially creating a long stream of notes we will be appending sine notes to a global array we will later use for creating a WAV file out of it.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">import</span> math </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">def</span> append_sinewave(freq=440.0, duration_milliseconds=500, volume=1.0): </span></span><span style="display:flex;"><span> <span style="color:#00f">global</span> audio </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> num_samples = duration_milliseconds * (sample_rate / 1000.0) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">for</span> x <span style="color:#00f">in</span> range(int(num_samples)): </span></span><span style="display:flex;"><span> audio.append(volume * math.sin(2 * math.pi * freq * (x / sample_rate))) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">return</span> </span></span></code></pre><p>The sine wave generated here is the standard beep. If you want something more aggressive, you could try a square or saw tooth waveform.</p> <h2 id="generating-a-wav-file-from-accumulated-sine-waves">Generating a WAV file from accumulated sine waves</h2> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">import</span> wave </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> struct </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">def</span> save_wav(file_name): </span></span><span style="display:flex;"><span> wav_file = wave.open(file_name, <span style="color:#a31515">&#39;w&#39;</span>) </span></span><span style="display:flex;"><span> nchannels = 1 </span></span><span style="display:flex;"><span> sampwidth = 2 </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> nframes = len(audio) </span></span><span style="display:flex;"><span> comptype = <span style="color:#a31515">&#39;NONE&#39;</span> </span></span><span style="display:flex;"><span> compname = <span style="color:#a31515">&#39;not compressed&#39;</span> </span></span><span style="display:flex;"><span> wav_file.setparams((nchannels, sampwidth, sample_rate, nframes, comptype, compname)) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">for</span> sample <span style="color:#00f">in</span> audio: </span></span><span style="display:flex;"><span> wav_file.writeframes(struct.pack(<span style="color:#a31515">&#39;h&#39;</span>, int(sample * 32767.0))) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> wav_file.close() </span></span></code></pre><p>44100 is the industry standard sample rate - CD quality. If you need to save on file size, you can adjust it downwards. The standard for low quality is, 8000 or 8kHz.</p> <p>WAV files here are using short, 16 bit, signed integers for the sample size. So, we multiply the floating-point data we have by 32767, the maximum value for a short integer.</p> <blockquote> <p>It is theoretically possible to use the floating point -1.0 to 1.0 data directly in a WAV file, but not obvious how to do that using the wave module in Python.</p> </blockquote> <h2 id="generating-spectograms">Generating Spectograms</h2> <p>I have tried two methods of doing this and both were just fine. I however opted out to use the <a href="https://linux.die.net/man/1/sox">SoX - Sound eXchange, the Swiss Army knife of audio manipulation</a> one because it didn't require anything else.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>sox output.wav -n spectrogram -o spectrogram.png </span></span></code></pre><p>An example spectrogram of Ludwig van Beethoven Symphony No. 6 First movement.</p> <audio controls> <source src="/posts/dna-synthesized/symphony-no6-1st-movement.mp3" type="audio/mpeg"> </audio> <figure> <img src="/posts/dna-synthesized/symphony-no6-1st-movement.png" alt="Ludwig van Beethoven Symphony No. 6 First movement" /> </figure> <p>The other option could also be in combination with <a href="http://www.gnuplot.info/">gnuplot</a>. This would require an intermediary step, however.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>sox output.wav audio.dat </span></span><span style="display:flex;"><span>tail -n+3 audio.dat &gt; audio_only.dat </span></span><span style="display:flex;"><span>gnuplot audio.gpi </span></span></code></pre><p>And input file <code>audio.gpi</code> that would be passed to gnuplot looks something like this.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span># set output format and size </span></span><span style="display:flex;"><span>set term png size 1000,280 </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span># set output file </span></span><span style="display:flex;"><span>set output &#34;audio.png&#34; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span># set y range </span></span><span style="display:flex;"><span>set yr [-1:1] </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span># we want just the data </span></span><span style="display:flex;"><span>unset key </span></span><span style="display:flex;"><span>unset tics </span></span><span style="display:flex;"><span>unset border </span></span><span style="display:flex;"><span>set lmargin 0 </span></span><span style="display:flex;"><span>set rmargin 0 </span></span><span style="display:flex;"><span>set tmargin 0 </span></span><span style="display:flex;"><span>set bmargin 0 </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span># draw rectangle to change background color </span></span><span style="display:flex;"><span>set obj 1 rectangle behind from screen 0,0 to screen 1,1 </span></span><span style="display:flex;"><span>set obj 1 fillstyle solid 1.0 fillcolor rgbcolor &#34;#ffffff&#34; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span># draw data with foreground color </span></span><span style="display:flex;"><span>plot &#34;audio_only.dat&#34; with lines lt rgb &#39;red&#39; </span></span></code></pre><h2 id="pre-generated-sequences">Pre-generated sequences</h2> <p>What I did was take interesting parts from an animal's genome and feed it to a tone generator script. This then generated a WAV file and I converted those to MP3, so they can be played in a browser. The last step was creating a spectrogram based on a WAV file.</p> <h3 id="niels-bohr-quote">Niels Bohr quote</h3> <audio controls> <source src="/posts/dna-synthesized/quote/out.mp3" type="audio/mpeg"> </audio> <figure> <img src="/posts/dna-synthesized/quote/spectogram.png" alt="Spectogram" /> </figure> <h3 id="mouse">Mouse</h3> <p>This is part of a mouse genome <code>Mus_musculus.GRCm39.dna.nonchromosomal</code>. You can get <a href="http://ftp.ensembl.org/pub/release-106/fasta/mus_musculus/dna/">genom data here</a>.</p> <audio controls> <source src="/posts/dna-synthesized/mouse/out.mp3" type="audio/mpeg"> </audio> <figure> <img src="/posts/dna-synthesized/mouse/spectogram.png" alt="Spectogram" /> </figure> <h3 id="bison">Bison</h3> <p>This is part of a bison genome <code>Bison_bison_bison.Bison_UMD1.0.cdna</code>. You can get <a href="http://ftp.ensembl.org/pub/release-106/fasta/bison_bison_bison/cdna/">genom data here</a>.</p> <audio controls> <source src="/posts/dna-synthesized/bison/out.mp3" type="audio/mpeg"> </audio> <figure> <img src="/posts/dna-synthesized/bison/spectogram.png" alt="Spectogram" /> </figure> <h3 id="taurus">Taurus</h3> <p>This is part of a taurus genome <code>Bos_taurus.ARS-UCD1.2.cdna</code>. You can get <a href="http://ftp.ensembl.org/pub/release-106/fasta/bos_taurus/cdna/">genom data here</a>.</p> <audio controls> <source src="/posts/dna-synthesized/taurus/out.mp3" type="audio/mpeg"> </audio> <figure> <img src="/posts/dna-synthesized/taurus/spectogram.png" alt="Spectogram" /> </figure> <h2 id="making-a-drummer-out-of-a-dna-sequence">Making a drummer out of a DNA sequence</h2> <p>To make things even more interesting, I decided to send this data via MIDI to my <a href="https://www.elektron.se/en/model-samples">Elektron Model:Samples</a>. This is a really cool piece of equipment that supports MIDI in via USB and 3.5 mm audio jack.</p> <p>Elektron is connected to my MacBook via USB cable and audio out is patched to a Sony Bluetooth speaker I have that supports 3.5 mm audio in. Elektron doesn't have internal speakers.</p> <figure> <img src="/posts/dna-synthesized/elektron/IMG_0619.jpg" alt="" /> </figure> <figure> <img src="/posts/dna-synthesized/elektron/IMG_0620.jpg" alt="" /> </figure> <figure> <img src="/posts/dna-synthesized/elektron/IMG_0622.jpg" alt="" /> </figure> <p>For communicating with Elektron, I choose <code>pygame</code> Python module that has MIDI built in. With this, it was rather simple to send notes to the device. All I did was map MIDI notes to the actual Nucleotides.</p> <p>Before all of this I also checked Audio MIDI Setup app under MacOS and checked MIDI Studio by pressing ⌘-2.</p> <figure> <img src="/posts/dna-synthesized/elektron/midi-studio.jpg" alt="" /> </figure> <p>The whole script that parses and send notes to the Elektron looks like this.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">import</span> pygame.midi </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> time </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>pygame.midi.init() </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>print(pygame.midi.get_default_output_id()) </span></span><span style="display:flex;"><span>print(pygame.midi.get_device_info(0)) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>player = pygame.midi.Output(1) </span></span><span style="display:flex;"><span>player.set_instrument(2) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">def</span> send_note(note, velocity): </span></span><span style="display:flex;"><span> <span style="color:#00f">global</span> player </span></span><span style="display:flex;"><span> player.note_on(note, velocity) </span></span><span style="display:flex;"><span> time.sleep(0.3) </span></span><span style="display:flex;"><span> player.note_off(note, velocity) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>nucleotide_midi_map = { </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;A&#39;</span>: 60, </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;C&#39;</span>: 90, </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;G&#39;</span>: 160, </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;T&#39;</span>: 180, <span style="color:#008000"># is D</span> </span></span><span style="display:flex;"><span>} </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">with</span> open(<span style="color:#a31515">&#34;quote.fa&#34;</span>) <span style="color:#00f">as</span> f: </span></span><span style="display:flex;"><span> sequence = f.read().replace(<span style="color:#a31515">&#39;</span><span style="color:#a31515">\n</span><span style="color:#a31515">&#39;</span>, <span style="color:#a31515">&#39;&#39;</span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">for</span> nucleotide <span style="color:#00f">in</span> [char <span style="color:#00f">for</span> char <span style="color:#00f">in</span> sequence]: </span></span><span style="display:flex;"><span> print(<span style="color:#a31515">&#34;Playing nucleotide </span><span style="color:#a31515">{}</span><span style="color:#a31515"> with MIDI note </span><span style="color:#a31515">{}</span><span style="color:#a31515">&#34;</span>.format( </span></span><span style="display:flex;"><span> nucleotide, nucleotide_midi_map[nucleotide])) </span></span><span style="display:flex;"><span> send_note(nucleotide_midi_map[nucleotide], 127) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">del</span> player </span></span><span style="display:flex;"><span>pygame.midi.quit() </span></span></code></pre><p><video src="/posts/dna-synthesized/elektron/elektron.mp4" controls></video></p> <p>All of this could be made much more interesting if I choose different instruments for different Nucleotides, or doing more funky stuff with Elektron. But for now, this should be enough. It is just a proof of concept. Something to play around with.</p> <h2 id="going-even-further">Going even further</h2> <p>As you probably notice, the end results are quite similar to each other. This is to be expected because we are operating only with 4 notes essentially. What could make this more interesting is using something like <a href="https://supercollider.github.io/">Supercollider</a> to create more interesting sounds. By transposing notes or using effects based on repeated data in a sequence. Possibilities are endless.</p> <p>It is really astonishing what can be achieved with a little bit of code and an idea. I could see this becoming an interesting background soundscape instrument if done properly. It could replace random note generator with something more intriguing, biological, natural.</p> <p>I actually find the results fascinating. I took some time and listened to this music of nature. Even though it's quite the same, it's also quite different. The subtle differences on repeat kind of creates music on its own. Makes you wonder. It kind of puts Occam’s Razor in its place. Nature for sure loves to make things as energy efficient as possible.</p> Trying out Helix code editor as my main editor https://mitjafelicijan.com/tying-out-helix-code-editor.html Thu, 30 Jun 2022 12:00:00 +0200 https://mitjafelicijan.com/tying-out-helix-code-editor.html I have been searching for a lightweight code editor for quite some time. <p>I have been searching for a lightweight code editor for quite some time. One of the main reasons was that I wanted something that doesn't burn through CPU and RAM usage is not through the roof. I have been mostly using Visual Studio Code. It's been an outstanding editor. I have no quarrel with it at all. It's just time to spice life up with something new.</p> <p>I have been on this search for a couple of years. I have tried Vim, Neovim, Emacs, Doom Emacs, Micro and couple more. Among most of them, I liked Micro and Doom Emacs the most. Micro editor was a little too basic for me. And Doom Emacs was a bit too hardcore. This does not reflect on any of the editors. It's just my personal preference.</p> <blockquote> <p>I tried Helix Editor about a year ago. But I didn't pay attention to it. Tried it and saw it's similar to Vi and just said no. I was premature to dismiss it.</p> </blockquote> <p>One of the things I actually miss is line wrapping for certain files. When writing Markdown, line wrapping would be very helpful. Editing such a document is frustrating to say the least. Some of the Markdown to HTML converters don't take kindly of new lines between sentences. Not paragraphs, sentences. And I use Markdown to write this blog you are reading.</p> <p>But other than this, I have been extremely satisfied by it. It's been a pleasant surprise. There have been zero issues with the editor.</p> <p>One thing to do before you are able to use autocompletion and make use Language Server support is to install the language server with NPM.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>npm install -g typescript typescript-language-server </span></span></code></pre><p>I am still getting used to the keyboard shortcuts and getting better. What Helix does really well is packing in sane defaults and even though because currently there is no plugin support I haven't found any need for them. It has all that you would need. It goes to extreme measures to show a user what is going on with popups that show you what the keyboard shortcuts are.</p> <p>And it comes us packed with many <a href="https://github.com/helix-editor/helix/wiki/Themes">really good themes</a>.</p> <figure> <img src="/posts/helix-editor/editor.png" alt="Editor" /> </figure> <p>It's still young but has this mature feeling to it. It has sane defaults and mimics Vim (works a bit differently, but the overall idea is similar).</p> Wireless Application Protocol and the mobile web before the web https://mitjafelicijan.com/wap-mobile-web-before-the-web.html Thu, 30 Dec 2021 12:00:00 +0200 https://mitjafelicijan.com/wap-mobile-web-before-the-web.html A little stroll down the history laneAbout two weeks ago, I watched this outstanding documentary on YouTubeSpringboard: the secret history of the first realsmartphone about the history ofsmartphones and phones in general. <h2 id="a-little-stroll-down-the-history-lane">A little stroll down the history lane</h2> <p>About two weeks ago, I watched this outstanding documentary on YouTube <a href="https://www.youtube.com/watch?v=b9_Vh9h3Ohw">Springboard: the secret history of the first real smartphone</a> about the history of smartphones and phones in general. It brought back so many memories. I never had an actual smartphone before the Android. The closest to smartphone was <a href="https://www.gsmarena.com/sony_ericsson_p1-1982.php">Sony Ericsson P1</a>. A fantastic phone and I broke it in Prague after a party and that was one of those rare occasions where I was actually mad at myself. But nevertheless, after that phone, the next one was an Android one.</p> <p>Before that, I only owned normal phones from Nokia and Siemens etc. Nothing special, actually. These are the phones we are talking about. Before 2007. Apple and Android phones didn't exist yet.</p> <p>These phones were rocking:</p> <ul> <li>No selfie cameras.</li> <li>~2 inch displays.</li> <li>~120 MHz beast CPU's.</li> <li>144p main cameras.</li> <li>But they had a headphone jack.</li> </ul> <p>Let's take a look at these beauties.</p> <figure> <img src="/posts/wap/phones.gif" alt="Old phones" /> </figure> <h2 id="wap---wireless-application-protocol">WAP - Wireless Application Protocol</h2> <p>Not that one! We are talking about Wireless Application Protocol and not Cardi B's song 😃</p> <p>WAP stands for Wireless Application Protocol. It is a protocol designed for micro-browsers, and it enables the access of internet in the mobile devices. It uses the mark-up language WML (Wireless Markup Language and not HTML), WML is defined as XML 1.0 application. Furthermore, it enables creating web applications for mobile devices. In 1998, WAP Forum was founded by Ericson, Motorola, Nokia and Unwired Planet whose aim was to standardize the various wireless technologies via protocols. <a href="https://www.geeksforgeeks.org/wireless-application-protocol/">(source)</a></p> <p>WAP protocol was resulted by the joint efforts of the various members of WAP Forum. In 2002, WAP forum was merged with various other forums of the industry, resulting in the formation of Open Mobile Alliance (OMA). <a href="https://www.geeksforgeeks.org/wireless-application-protocol/">(source)</a></p> <p>These were some wild times. Devices had tiny screens and data transmission rates were abominable. But they were capable of rendering WML (Wireless Markup Language). This was very similar to HTML, actually. It is a markup language, after all.</p> <p>These pages could be served by <a href="https://apache.org/">Apache</a> and could be generated by CGI scripts on the backend. The only difference was the limited markup language.</p> <h2 id="wml---wireless-markup-language">WML - Wireless Markup Language</h2> <p>Just like web browsers use HTML for content structure, older mobile device browsers use WML - if you need to support really old mobile phones using WML browsers, you will need to know about it. WML is XML-based (an XML vocabulary just like XHTML and MathML, but not HTML) and does not use the same metaphor as HTML. HTML is a single document with some metadata packed away in the head, and a body encapsulating the visible page. With WML, the metaphor does not envisage a page, but rather a deck of cards. A WML file might have several pages or cards contained within it. <a href="https://www.w3.org/wiki/Introduction_to_mobile_web">(source)</a></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">&lt;?xml version=&#34;1.0&#34;?&gt;</span> </span></span><span style="display:flex;"><span><span style="color:#00f">&lt;!DOCTYPE wml PUBLIC &#34;-//WAPFORUM//DTD WML 1.1//EN&#34; &#34;http://www.wapforum.org/DTD/wml_1.1.xml&#34;&gt;</span> </span></span><span style="display:flex;"><span>&lt;wml&gt; </span></span><span style="display:flex;"><span> &lt;card id=<span style="color:#a31515">&#34;home&#34;</span> title=<span style="color:#a31515">&#34;Example Homepage&#34;</span>&gt; </span></span><span style="display:flex;"><span> &lt;p&gt;Welcome to the Example homepage&lt;/p&gt; </span></span><span style="display:flex;"><span> &lt;/card&gt; </span></span><span style="display:flex;"><span>&lt;/wml&gt; </span></span></code></pre><p>There is an amazing tutorial on <a href="https://www.tutorialspoint.com/wml/index.htm">Tutorialpoint about WML</a>.</p> <h2 id="converting-digg-to-wml">Converting Digg to WML</h2> <p>This task is completely useless and not really feasible nowadays, but I had to give it a try for old-time sake. Since the data is already there in a form of RSS feed, I could take this feed and parse it and create a WML version of the homepage.</p> <p>We will need:</p> <ul> <li>Python3 + Pip</li> <li>ImageMagick</li> <li>feedparser and mako templating</li> </ul> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># for fedora 35</span> </span></span><span style="display:flex;"><span>sudo dnf install ImageMagick python3-pip </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># tempalting engine for python</span> </span></span><span style="display:flex;"><span>pip install mako --user </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># for parsing rss feeds</span> </span></span><span style="display:flex;"><span>pip install feedparser --user </span></span></code></pre><p>Project folder structure should look like the following.</p> <pre><code>12:43:53 m@khan wap → tree -L 1 . ├── generate.py └── template.wml </code></pre> <p>After that, I created a small template for the homepage.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">&lt;?xml version=&#34;1.0&#34;?&gt;</span> </span></span><span style="display:flex;"><span><span style="color:#00f">&lt;!DOCTYPE wml PUBLIC &#34;-//WAPFORUM//DTD WML 1.2//EN&#34; &#34;http://www.wapforum.org/DTD/wml_1.2.xml&#34;&gt;</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>&lt;wml&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;card title=<span style="color:#a31515">&#34;Digg - What the Internet is talking about right now&#34;</span>&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> % for item in entries: </span></span><span style="display:flex;"><span> &lt;p&gt;&lt;img src=<span style="color:#a31515">&#34;/images/${item.id}.jpg&#34;</span> width=<span style="color:#a31515">&#34;175&#34;</span> height=<span style="color:#a31515">&#34;95&#34;</span> alt=<span style="color:#a31515">&#34;${item.title}&#34;</span> /&gt;&lt;/p&gt; </span></span><span style="display:flex;"><span> &lt;p&gt;&lt;small&gt;${item.kicker}&lt;/small&gt;&lt;/p&gt; </span></span><span style="display:flex;"><span> &lt;p&gt;&lt;big&gt;&lt;b&gt;${item.title}&lt;/b&gt;&lt;/big&gt;&lt;/p&gt; </span></span><span style="display:flex;"><span> &lt;p&gt;${item.description}&lt;/p&gt; </span></span><span style="display:flex;"><span> % endfor </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;/card&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>&lt;/wml&gt; </span></span></code></pre><p>And the parser that parses RSS feed looks like this.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">import</span> os </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> feedparser </span></span><span style="display:flex;"><span><span style="color:#00f">from</span> mako.template <span style="color:#00f">import</span> Template </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>os.system(<span style="color:#a31515">&#39;mkdir -p www/images&#39;</span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>template = Template(filename=<span style="color:#a31515">&#39;template.wml&#39;</span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>feed = feedparser.parse(<span style="color:#a31515">&#39;https://digg.com/rss/top.xml&#39;</span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>entries = feed.entries[:15] </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">for</span> entry <span style="color:#00f">in</span> entries: </span></span><span style="display:flex;"><span> print(<span style="color:#a31515">&#39;Processing image with id </span><span style="color:#a31515">{}</span><span style="color:#a31515">&#39;</span>.format(entry.id)) </span></span><span style="display:flex;"><span> os.system(<span style="color:#a31515">&#39;wget -q -O www/images/</span><span style="color:#a31515">{}</span><span style="color:#a31515">.jpg &#34;</span><span style="color:#a31515">{}</span><span style="color:#a31515">&#34;&#39;</span>.format(entry.id, entry.links[1].href)) </span></span><span style="display:flex;"><span> os.system(<span style="color:#a31515">&#39;convert www/images/</span><span style="color:#a31515">{}</span><span style="color:#a31515">.jpg -type Grayscale -resize 175x -depth 3 -quality 30 www/images/</span><span style="color:#a31515">{}</span><span style="color:#a31515">.jpg&#39;</span>.format(entry.id, entry.id)) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>html = template.render(entries = entries) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">with</span> open(<span style="color:#a31515">&#39;www/index.wml&#39;</span>, <span style="color:#a31515">&#39;w+&#39;</span>) <span style="color:#00f">as</span> fp: </span></span><span style="display:flex;"><span> fp.write(html) </span></span></code></pre><p>This script will create a folder <code>www</code> and in the folder <code>www/images</code> for storing resized images.</p> <blockquote> <p>Be sure you don't use SSL and use just normal HTTP for serving the content. These old phones will have problems with TLS 1.3 etc.</p> </blockquote> <p>If you look at the python file, I convert all the images into tiny B&amp;W images. They should be WBMP (Wireless BitMaP) but I choose JPEGs for this, and it seems to work properly.</p> <p>Because I currently don't have a phone old enough to test it on, I used an emulator. And it was really hard to find one. I found <a href="http://wap-proof.sharewarejunction.com/">WAP Proof</a> on shareware junction, and it did the job well enough. I will try to find and actual device to test it on.</p> <p><video src="/posts/wap/emulator.mp4" controls></video></p> <p>If you are using Nginx to serve the contents, add a directive to the hosts file that will automatically server <code>index.wml</code> file.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">server</span> { </span></span><span style="display:flex;"><span> <span style="color:#00f">index</span> <span style="color:#a31515">index.wml</span> <span style="color:#a31515">index.html</span> <span style="color:#a31515">index.htm</span> <span style="color:#a31515">index.nginx-debian.html</span>; </span></span><span style="display:flex;"><span>} </span></span></code></pre><h2 id="conclusion">Conclusion</h2> <p>Well, this was pointless, but very fun! I hope you enjoyed it as much as I did. I will try to find an old phone to test it on. If you have any questions, feel free to ask in the comments.</p> Running Golang application as PID 1 with Linux kernel https://mitjafelicijan.com/running-golang-application-as-pid1.html Sat, 25 Dec 2021 12:00:00 +0200 https://mitjafelicijan.com/running-golang-application-as-pid1.html Unikernels, kernels, and alikeI have been reading a lot aboutunikernernels lately and found themvery intriguing. <h2 id="unikernels-kernels-and-alike">Unikernels, kernels, and alike</h2> <p>I have been reading a lot about <a href="https://en.wikipedia.org/wiki/Unikernel">unikernernels</a> lately and found them very intriguing. When you push away all the marketing speak and look at the idea, it makes a lot of sense.</p> <blockquote> <p>A unikernel is a specialized, single address space machine image constructed by using library operating systems. (<a href="https://en.wikipedia.org/wiki/Unikernel">Wikipedia</a>)</p> </blockquote> <p>I really like the explanation from the article <a href="https://queue.acm.org/detail.cfm?id=2566628">Unikernels: Rise of the Virtual Library Operating System</a>. Really worth a read.</p> <p>If we compare a normal operating system to a unikernel side by side, they would look something like this.</p> <figure> <img src="/posts/pid1/unikernels.png" alt="Virtual machines vs Containers vs Unikernels" /> </figure> <p>From this image, we can see how the complexity significantly decreases with the use of Unikernels. This comes with a price, of course. Unikernels are hard to get running and require a lot of work since you don't have an actual proper kernel running in the background providing network access and drivers etc.</p> <p>So as a half step to make the stack simpler, I started looking into using Linux kernel as a base and going from there. I came across this <a href="https://www.youtube.com/watch?v=Sk9TatW9ino">Youtube video talking about Building the Simplest Possible Linux System</a> by <a href="https://landley.net">Rob Landley</a> and apart from statically compiling the application to be run as PID1 there was really no other obstacles.</p> <h2 id="what-is-pid-1">What is PID 1?</h2> <p>PID 1 is the first process that Linux kernel starts after the boot process. It also has a couple of unique properties that are unique to it.</p> <ul> <li>When the process with PID 1 dies for any reason, all other processes are killed with KILL signal.</li> <li>When any process having children dies for any reason, its children are re-parented to process with PID 1.</li> <li>Many signals which have default action of Term do not have one for PID 1.</li> <li>When the process with PID 1 dies for any reason, kernel panics, which result in system crash.</li> </ul> <p>PID 1 is considered as an Init application which takes care of running other and handling services like:</p> <ul> <li>sshd,</li> <li>nginx,</li> <li>pulseaudio,</li> <li>etc.</li> </ul> <p>If you are on a Linux machine, you can check what your process is with PID 1 by running the following.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>$ cat /proc/1/status </span></span><span style="display:flex;"><span>Name: systemd </span></span><span style="display:flex;"><span>Umask: 0000 </span></span><span style="display:flex;"><span>State: S (sleeping) </span></span><span style="display:flex;"><span>Tgid: 1 </span></span><span style="display:flex;"><span>Ngid: 0 </span></span><span style="display:flex;"><span>Pid: 1 </span></span><span style="display:flex;"><span>PPid: 0 </span></span><span style="display:flex;"><span>... </span></span></code></pre><p>As we can see on my machine the process with id of 1 is <a href="https://systemd.io/">systemd</a> which is a software suite that provides an array of system components for Linux operating systems. If you look closely you can also see that the <code>PPid</code> (process id of the parent process) is <code>0</code> which additionally confirms that this process doesn't have a parent.</p> <h2 id="so-why-even-run-application-as-pid-1-instead-of-just-using-a-container">So why even run application as PID 1 instead of just using a container?</h2> <p>Containers are wonderful, but they come with a lot of baggage. And because they are in their nature layered, the images require quite a lot of space and also a lot of additional software to handle them. They are not as lightweight as they seem, and many popular images require 500 MB plus disk space.</p> <p>The idea of running this as PID 1 would result in a significantly smaller footprint, as we will see later in the post.</p> <blockquote> <p>You could run a simple init system inside Docker container described more in this article <a href="https://blog.phusion.nl/2015/01/20/docker-and-the-pid-1-zombie-reaping-problem/">Docker and the PID 1 zombie reaping problem</a>.</p> </blockquote> <h2 id="the-master-plan">The master plan</h2> <ol> <li>Compile Linux kernel with the default definitions.</li> <li>Prepare a Hello World application in Golang that is statically compiled.</li> <li>Run it with <a href="https://www.qemu.org/">QEMU</a> and providing Golang application as init application / PID 1.</li> </ol> <p>For the sake of simplicity we will not be cross-compiling any of it and just use the 64bit version.</p> <h2 id="compiling-linux-kernel">Compiling Linux kernel</h2> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>$ wget https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.15.7.tar.xz </span></span><span style="display:flex;"><span>$ tar xf linux-5.15.7.tar.xz </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>$ cd linux-5.15.7 </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>$ make clean </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># read more about this https://stackoverflow.com/a/41886394</span> </span></span><span style="display:flex;"><span>$ make defconfig </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>$ time make -j <span style="color:#a31515">`</span>nproc<span style="color:#a31515">`</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>$ cd .. </span></span></code></pre><p>At this point we have kernel image that is located in <code>arch/x86_64/boot/bzImage</code>. We will use this in QEMU later.</p> <p>To make our lives a bit easier lets move the kernel image to another place. Lets create a folder <code>bin/</code> in the root of our project with <code>mkdir -p bin</code>.</p> <p>At this point we can copy <code>bzImage</code> to <code>bin/</code> folder with <code>cp linux-5.15.7/arch/x86_64/boot/bzImage bin/bzImage</code>.</p> <p>The folder structure of this experiment should look like this.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>pid1/ </span></span><span style="display:flex;"><span> bin/ </span></span><span style="display:flex;"><span> bzImage </span></span><span style="display:flex;"><span> linux-5.15.7/ </span></span><span style="display:flex;"><span> linux-5.15.7.tar.xz </span></span></code></pre><h2 id="preparing-pid-1-application-in-golang">Preparing PID 1 application in Golang</h2> <p>This step is relatively easy. The only thing we must have in mind that we will need to compile the binary as a static one.</p> <p>Let's create <code>init.go</code> file in the root of the project.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">package</span> main </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> ( </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#34;fmt&#34;</span> </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#34;time&#34;</span> </span></span><span style="display:flex;"><span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">func</span> main() { </span></span><span style="display:flex;"><span> <span style="color:#00f">for</span> { </span></span><span style="display:flex;"><span> fmt.Println(<span style="color:#a31515">&#34;Hello from Golang&#34;</span>) </span></span><span style="display:flex;"><span> time.Sleep(1 * time.Second) </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span>} </span></span></code></pre><p>If you notice, we have a forever loop in the main, with a simple sleep of 1 second to not overwhelm the CPU. This is because PID 1 should never complete and/or exit. That would result in a kernel panic. Which is BAD!</p> <p>There are two ways of compiling Golang application. Statically and dynamically.</p> <p>To statically compile the binary, use the following command.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>$ go build -ldflags=<span style="color:#a31515">&#34;-extldflags=-static&#34;</span> init.go </span></span></code></pre><p>We can also check if the binary is statically compiled with:</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>$ file init </span></span><span style="display:flex;"><span>init: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, Go BuildID=Ypu8Zw_4NBxm1Yxg2OYO/H5x721rQ9uTPiDVh-VqP/vZN7kXfGG1zhX_qdHMgH/9vBfmK81tFrygfOXDEOo, not stripped </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>$ ldd init </span></span><span style="display:flex;"><span>not a dynamic executable </span></span></code></pre><p>At this point, we need to create <a href="https://www.linuxfromscratch.org/blfs/view/svn/postlfs/initramfs.html">initramfs</a> (abbreviated from &quot;initial RAM file system&quot;, is the successor of initrd. It is a cpio archive of the initial file system that gets loaded into memory during the Linux startup process).</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>$ echo init | cpio -o --format=newc &gt; initramfs </span></span><span style="display:flex;"><span>$ mv initramfs bin/initramfs </span></span></code></pre><p>The projects at this stage should look like this.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>pid1/ </span></span><span style="display:flex;"><span> bin/ </span></span><span style="display:flex;"><span> bzImage </span></span><span style="display:flex;"><span> initramfs </span></span><span style="display:flex;"><span> linux-5.15.7/ </span></span><span style="display:flex;"><span> linux-5.15.7.tar.xz </span></span><span style="display:flex;"><span> init.go </span></span></code></pre><h2 id="running-all-of-it-with-qemu">Running all of it with QEMU</h2> <p><a href="https://www.qemu.org/">QEMU</a> is a free and open-source hypervisor. It emulates the machine's processor through dynamic binary translation and provides a set of different hardware and device models for the machine, enabling it to run a variety of guest operating systems.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>$ qemu-system-x86_64 -serial stdio -kernel bin/bzImage -initrd bin/initramfs -append <span style="color:#a31515">&#34;console=ttyS0&#34;</span> -m 128 </span></span></code></pre><pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>$ qemu-system-x86_64 -serial stdio -kernel bin/bzImage -initrd bin/initramfs -append <span style="color:#a31515">&#34;console=ttyS0&#34;</span> -m 128 </span></span><span style="display:flex;"><span>[ 0.000000] Linux version 5.15.7 (m@khan) (gcc (GCC) 11.2.1 20211203 (Red Hat 11.2.1-7), GNU ld version 2.37-10.fc35) <span style="color:#008000">#7 SMP Mon Dec 13 10:23:25 CET 2021</span> </span></span><span style="display:flex;"><span>[ 0.000000] Command line: console=ttyS0 </span></span><span style="display:flex;"><span>[ 0.000000] x86/fpu: x87 FPU will use FXSAVE </span></span><span style="display:flex;"><span>[ 0.000000] signal: max sigframe size: 1440 </span></span><span style="display:flex;"><span>[ 0.000000] BIOS-provided physical RAM map: </span></span><span style="display:flex;"><span>[ 0.000000] BIOS-e820: [mem 0x0000000000000000-0x000000000009fbff] usable </span></span><span style="display:flex;"><span>[ 0.000000] BIOS-e820: [mem 0x000000000009fc00-0x000000000009ffff] reserved </span></span><span style="display:flex;"><span>[ 0.000000] BIOS-e820: [mem 0x00000000000f0000-0x00000000000fffff] reserved </span></span><span style="display:flex;"><span>[ 0.000000] BIOS-e820: [mem 0x0000000000100000-0x0000000007fdffff] usable </span></span><span style="display:flex;"><span>[ 0.000000] BIOS-e820: [mem 0x0000000007fe0000-0x0000000007ffffff] reserved </span></span><span style="display:flex;"><span>[ 0.000000] BIOS-e820: [mem 0x00000000fffc0000-0x00000000ffffffff] reserved </span></span><span style="display:flex;"><span>[ 0.000000] NX (Execute Disable) protection: active </span></span><span style="display:flex;"><span>[ 0.000000] SMBIOS 2.8 present. </span></span><span style="display:flex;"><span>[ 0.000000] DMI: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-6.fc35 04/01/2014 </span></span><span style="display:flex;"><span>[ 0.000000] tsc: Fast TSC calibration failed </span></span><span style="display:flex;"><span>... </span></span><span style="display:flex;"><span>[ 2.016106] ALSA device list: </span></span><span style="display:flex;"><span>[ 2.016329] No soundcards found. </span></span><span style="display:flex;"><span>[ 2.053176] Freeing unused kernel image (initmem) memory: 1368K </span></span><span style="display:flex;"><span>[ 2.056095] Write protecting the kernel read-only data: 20480k </span></span><span style="display:flex;"><span>[ 2.058248] Freeing unused kernel image (text/rodata gap) memory: 2032K </span></span><span style="display:flex;"><span>[ 2.058811] Freeing unused kernel image (rodata/data gap) memory: 500K </span></span><span style="display:flex;"><span>[ 2.059164] Run /init as init process </span></span><span style="display:flex;"><span>Hello from Golang </span></span><span style="display:flex;"><span>[ 2.386879] tsc: Refined TSC clocksource calibration: 3192.032 MHz </span></span><span style="display:flex;"><span>[ 2.387114] clocksource: tsc: mask: 0xffffffffffffffff max_cycles: 0x2e02e31fa14, max_idle_ns: 440795264947 ns </span></span><span style="display:flex;"><span>[ 2.387380] clocksource: Switched to clocksource tsc </span></span><span style="display:flex;"><span>[ 2.587895] input: ImExPS/2 Generic Explorer Mouse as /devices/platform/i8042/serio1/input/input3 </span></span><span style="display:flex;"><span>Hello from Golang </span></span><span style="display:flex;"><span>Hello from Golang </span></span><span style="display:flex;"><span>Hello from Golang </span></span></code></pre><p>The whole <a href="/posts/pid1/qemu.log">log file here</a>.</p> <h2 id="size-comparison">Size comparison</h2> <p>The cool thing about this approach is that the Linux kernel and the application together only take around 12 MB, which is impressive as hell. And we need to also know that the size of bzImage (Linux kernel) could be greatly decreased by going into <code>make menuconfig</code> and removing a ton of features from the kernel, making the size even smaller. I managed to get kernel size down to 2 MB and still working properly.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>total 12M </span></span><span style="display:flex;"><span>-rw-r--r--. 1 m m 9.3M Dec 13 10:24 bzImage </span></span><span style="display:flex;"><span>-rw-r--r--. 1 m m 1.9M Dec 27 01:19 initramfs </span></span></code></pre><h2 id="creating-iso-image-and-running-it-with-gnome-boxes">Creating ISO image and running it with Gnome Boxes</h2> <p>First we need to create proper folder structure with <code>mkdir -p iso/boot/grub</code>.</p> <p>Then we need to download the <a href="https://github.com/littleosbook/littleosbook/raw/master/files/stage2_eltorito">grub binary</a>. You can read more about this program on <a href="https://github.com/littleosbook/littleosbook">https://github.com/littleosbook/littleosbook</a>.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>$ wget -O iso/boot/grub/stage2_eltorito https://github.com/littleosbook/littleosbook/raw/master/files/stage2_eltorito </span></span></code></pre><pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>$ tree iso/boot/ </span></span><span style="display:flex;"><span>iso/boot/ </span></span><span style="display:flex;"><span>├── bzImage </span></span><span style="display:flex;"><span>├── grub </span></span><span style="display:flex;"><span>│   ├── menu.lst </span></span><span style="display:flex;"><span>│   └── stage2_eltorito </span></span><span style="display:flex;"><span>└── initramfs </span></span></code></pre><p>Let's copy files into proper folders.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>$ cp stage2_eltorito iso/boot/grub/ </span></span><span style="display:flex;"><span>$ cp bin/bzImage iso/boot/ </span></span><span style="display:flex;"><span>$ cp bin/initramfs iso/boot/ </span></span></code></pre><p>Lets create a GRUB config file at <code>nano iso/boot/grub/menu.lst</code> with contents.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>default=<span style="color:#a31515">0</span> </span></span><span style="display:flex;"><span>timeout=<span style="color:#a31515">5</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>title GoAsPID1 </span></span><span style="display:flex;"><span>kernel /boot/bzImage </span></span><span style="display:flex;"><span>initrd /boot/initramfs </span></span></code></pre><p>Let's create iso file by using genisoimage:</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>genisoimage -R <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> -b boot/grub/stage2_eltorito <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> -no-emul-boot <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> -boot-load-size 4 <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> -A os <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> -input-charset utf8 <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> -quiet <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> -boot-info-table <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> -o GoAsPID1.iso <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> iso </span></span></code></pre><p>This will produce <code>GoAsPID1.iso</code> which you can use with <a href="https://www.virtualbox.org/">Virtualbox</a> or <a href="https://apps.gnome.org/app/org.gnome.Boxes/">Gnome Boxes</a>.</p> <p><video src="/posts/pid1/boxes.mp4" controls></video></p> <h2 id="is-running-applications-as-pid-1-even-worth-it">Is running applications as PID 1 even worth it?</h2> <p>Well, the answer to this is not as simple as one would think. Sometimes it is and sometimes it's not. For embedded systems and very specialized applications it is worth for sure. But in normal uses, I don't think so. It was an interesting exercise in compiling kernels and looking at the guts of the Linux kernel, but sticking to containers for most of the things is a better option in my opinion.</p> <p>An interesting experiment would be creating an image that supports networking and could be deployed to AWS as an EC2 instance and observing how it fares. But in that case, we would need to write some sort of supervisor that would run on a separate EC2 that would check if other EC2 instances are running properly. Remember that if your application fails, kernel panics and the whole machine is inoperable in this case.</p> Debian based riced up distribution for Developers and DevOps folks https://mitjafelicijan.com/debian-based-riced-up-distribution-for-developers-and-devops-folks.html Fri, 03 Dec 2021 12:00:00 +0200 https://mitjafelicijan.com/debian-based-riced-up-distribution-for-developers-and-devops-folks.html IntroductionI have been using Ubuntu for quite a longtime now. <h2 id="introduction">Introduction</h2> <p>I have been using <a href="https://ubuntu.com/">Ubuntu</a> for quite a longtime now. I have used <a href="https://www.debian.org/">Debian</a> in the past and <a href="https://manjaro.org/">Manjaro</a>. Also had <a href="https://archlinux.org/">Arch</a> for some time and even ran <a href="https://www.gentoo.org/">Gentoo</a> way back.</p> <p>What I learned from all this is that I prefer running a bit older versions and having them be stable than run bleeding edge rolling release. For that reason, I stuck with Ubuntu for a couple of years now. I am also at a point in my life where I just don't care what is cool or hip anymore. I just want a stable system that doesn't get in my way.</p> <p>During all this, I noticed that these distributions were getting very bloated and a lot of software got included that I usually uninstall on fresh installation. Maybe this is my OCD speaking, but why do I have to give fresh installation min 1 GB of ram out of the box just to have a blank screen in front of me? I get it, there are many things included in the distro to make my life easier. I understand. But at this point I have a feeling that modern Linux distributions are becoming similar to <a href="https://devhumor.com/content/uploads/images/August2017/node-modules.jpg">Node.js project with node_modules</a>. Just a crazy number of packages serving very little or no purpose, just supporting other software.</p> <p>I felt I needed a fresh start. To start over with something minimal and clean. Something that would put a little more joy into using a computer again.</p> <p>For the first version, I wanted to target the following machines I have at home that I want this thing to work on.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># My main stationary work machine</span> </span></span><span style="display:flex;"><span>Resolution: 3840x1080 (Super Ultrawide Monitor 32:9) </span></span><span style="display:flex;"><span>CPU: Intel i7-8700 (12) @ 4.600GHz </span></span><span style="display:flex;"><span>GPU: AMD ATI Radeon RX 470/480/570/570X/580/580X/590 </span></span><span style="display:flex;"><span>Memory: 32020MiB </span></span></code></pre><pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># Thinkpad x220 for testing things and goofing around</span> </span></span><span style="display:flex;"><span>Resolution: 1366x768 </span></span><span style="display:flex;"><span>CPU: Intel i5-2520M (4) @ 3.200GHz </span></span><span style="display:flex;"><span>GPU: Intel 2nd Generation Core Processor Family </span></span><span style="display:flex;"><span>Memory: 15891MiB </span></span></code></pre><h2 id="how-should-i-approach-this">How should I approach this?</h2> <p>I knew I wanted to use <a href="https://www.debian.org/CD/netinst/">minimal Debian netinst </a> for the base to give myself a head start. No reason to go through changing the installer and also testing all that behemoth of a thing. So, some sort of ricing was the only logical option to get this thing of the grounds somewhat quickly.</p> <blockquote> <p><strong>What is ricing anyway?</strong> The term “RICE” stands for Race Inspired Cosmetic Enhancement. A group of people (could be one, idk) decided to see if they could tweak their own distros like they/others did their cars. This gave rise to a community of Linux/Unix enthusiasts trying to make their distros look cooler and better than others... For more information, read this article <a href="https://pesos.github.io/2020/07/14/what-is-ricing.html">What in the world is ricing!?</a>.</p> </blockquote> <p>I didn't want this to just be a set of config files for theming purpose. I wanted this to include a set of pre-installed tools and services that are being used all the time by a modern developer. Theming is just a tiny part of it. Fonts being applied across the distro and things like that.</p> <p>First, I choose terminal installer and left it to load additional components. Avoid using graphical installer in this case.</p> <figure> <img src="/posts/dfd-rice/install-00.png" alt="" /> </figure> <p>After that I selected hostname and created a normal user and set password for that user and root user and choose guided mode for disk partitioning.</p> <figure> <img src="/posts/dfd-rice/install-01.png" alt="" /> </figure> <p>I left it run to install all the things required for the base system and opted out of scanning additional media for use by the package manager. Those will be downloaded from the internet during installation.</p> <figure> <img src="/posts/dfd-rice/install-02.png" alt="" /> </figure> <p>I opted out of the popularity contest, and <strong>now comes the important part</strong>. Uncheck all the boxes in Software selection and only leave 'standard system utilities'. I also left an SSH server, so I was able to log in to the machine from my main PC.</p> <figure> <img src="/posts/dfd-rice/install-03.png" alt="" /> </figure> <p>At this point, I installed GRUB bootloader on the disk where I installed the system.</p> <figure> <img src="/posts/dfd-rice/install-04.png" alt="" /> </figure> <p>That concluded the installation of base Debian and after restarting the computer I was prompted with the login screen.</p> <figure> <img src="/posts/dfd-rice/install-05.png" alt="" /> </figure> <p>Now that I had the base installation, it was time to choose what software do I want to include in this so-called distribution. I wanted out of the box developer experience, so I had plenty to choose.</p> <p>Let's not waste time and go through the list.</p> <h2 id="desktop-environments">Desktop environments</h2> <p>I have been using <a href="https://www.gnome.org/">Gnome</a> for my whole Linux life. From version 2 forward. It's been quite a ride. I hated version 3 when it came out and replaced version 2. But I got used to it. And now with version 40+ they also made couple of changes which I found both frustrating and presently surprised.</p> <p>The amount of vertical space you loose because of the beefy title bars on windows is ridiculous. And then in case of <a href="https://gnunn1.github.io/tilix-web/">Tilix</a> you also have tabs, and you are 100px deep. Vertical space is one of the most important things for a developer. The more real estate you have, the more code you can have in a viewport.</p> <p>But on the other hand, I still love how Gnome feels and looks. I gotta give them that. They really are trying to make Gnome feel unified and modern.</p> <p>Regardless of all the nice things Gnome has, I was looking at the tiling window managers for some time, but never had the nerve to actually go with it. But now was the ideal time to give it a go. No guts, no glory kind of a thing.</p> <p>One of the requirements for me was easy custom layouts because I use a really strange monitor with aspect ratio of 32:9. So relying on included layouts most of them have is a non-starter.</p> <p>What I was doing in Gnome was having windows in a layout like the diagram below. This is my common practice. And if you look at it you can clearly see I was replicating tiling window manager setup in Gnome.</p> <figure> <img src="/posts/dfd-rice/layout.png" alt="" /> </figure> <p>That made me look into a bunch of tiling window managers and then tested them out. Candidates I was looking at were:</p> <ul> <li><a href="https://i3wm.org/">i3</a></li> <li><a href="https://github.com/baskerville/bspwm">bspwm</a></li> <li><a href="https://awesomewm.org/index.html">awesome</a></li> <li><a href="https://xmonad.org/">XMonad</a></li> <li><a href="https://swaywm.org/">sway</a></li> <li><a href="http://www.qtile.org/">Qtile</a></li> <li><a href="https://dwm.suckless.org/">dwm</a></li> </ul> <p>You can also check article <a href="https://www.tecmint.com/best-tiling-window-managers-for-linux/">13 Best Tiling Window Managers for Linux</a> I was referencing while testing them out.</p> <p>While all of them provided what I needed, I liked i3 the most. What particular caught my eye was the ease to use and tree based layouts which allows flexible layouts. I know others can be set up also to have custom layouts other than<br /> spiral, dwindle etc. I think i3 is a good entry-level window manager for somebody like me.</p> <h2 id="batteries-included">Batteries included</h2> <p>The source for the whole thing is located on Github <a href="https://github.com/mitjafelicijan/dfd-rice">https://github.com/mitjafelicijan/dfd-rice</a>.</p> <p>Currenly included:</p> <ul> <li><code>non-free</code> (enables non-free packages in apt)</li> <li><code>sudo</code> (adds sudo and adds user to sudo group)</li> <li><code>essentials</code> (gcc, htop, zip, curl, etc...)</li> <li><code>wifi</code> (network manager nmtui)</li> <li><code>desktop</code> (i3, dmenu, fonts, configurations)</li> <li><code>pulseaudio</code> (pulseaudio with pavucontrol)</li> <li><code>code-editors</code> (vim, micro, vscode)</li> <li><code>ohmybash</code> (make bash pretty)</li> <li><code>file-managers</code> (mc)</li> <li><code>git-ui</code> (terminal git gui)</li> <li><code>meld</code> (diff tool)</li> <li><code>profiling</code> (kcachegrind, valgrind, strace, ltrace)</li> <li><code>browsers</code> (brave, firefox, chromium)</li> <li>programming languages: <ul> <li><code>python</code></li> <li><code>golang</code></li> <li><code>nodejs</code></li> <li><code>rust</code></li> <li><code>nim</code></li> <li><code>php</code></li> <li><code>ruby</code></li> </ul> </li> <li><code>docker</code> (with docker-compose)</li> <li><code>ansible</code></li> </ul> <p>Install script also allows you to install only specific packages (example for: essentials ohmybash docker rust).</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>su - root <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> bash -c <span style="color:#a31515">&#34;</span><span style="color:#00f">$(</span>wget -q https://raw.github.com/mitjafelicijan/dfd-rice/master/tools/install.sh -O -<span style="color:#00f">)</span><span style="color:#a31515">&#34;</span> -- <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> essentials ohmybash docker rust </span></span></code></pre><p>Currently, most of these recipes use what Debian and this is totally fine with me since I never use bleeding edge features of a package. But if something major would come to light, I will replace it with a possible compilation script or something similar.</p> <p>This is some of the output from the installation script.</p> <figure> <img src="/posts/dfd-rice/script.png" alt="" /> </figure> <p>Let's take a look at some examples in the installation script.</p> <h3 id="docker-recipe">Docker recipe</h3> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># docker</span> </span></span><span style="display:flex;"><span>print_header <span style="color:#a31515">&#34;Installing Docker&#34;</span> </span></span><span style="display:flex;"><span>curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --yes --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg </span></span><span style="display:flex;"><span>echo <span style="color:#a31515">&#34;deb [arch=</span><span style="color:#00f">$(</span>dpkg --print-architecture<span style="color:#00f">)</span><span style="color:#a31515"> signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian </span><span style="color:#00f">$(</span>lsb_release -cs<span style="color:#00f">)</span><span style="color:#a31515"> stable&#34;</span> | tee /etc/apt/sources.list.d/docker.list &gt; /dev/null </span></span><span style="display:flex;"><span>apt update </span></span><span style="display:flex;"><span>apt -y install docker-ce docker-ce-cli containerd.io docker-compose </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>systemctl start docker </span></span><span style="display:flex;"><span>systemctl enable docker </span></span><span style="display:flex;"><span>systemctl status docker --no-pager </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>/sbin/usermod -aG docker $USERNAME </span></span></code></pre><h3 id="making-bash-pretty">Making bash pretty</h3> <p>I really like <a href="https://ohmyz.sh/">Oh My Zsh</a>, but I don't like zsh shell. When I used it, I constantly needed to be aware of it and running bash scripts was a pain. So, I was really delighted when I found out that a version for bash existed called <a href="https://ohmybash.nntoan.com/">Oh My Bash</a>. Let's take a look at the recipe for installing it.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># ohmybash</span> </span></span><span style="display:flex;"><span>print_header <span style="color:#a31515">&#34;Enabling OhMyBash&#34;</span> </span></span><span style="display:flex;"><span>sudo -u $USERNAME sh -c <span style="color:#a31515">&#34;</span><span style="color:#00f">$(</span>curl -fsSL https://raw.github.com/ohmybash/oh-my-bash/master/tools/install.sh<span style="color:#00f">)</span><span style="color:#a31515">&#34;</span> &amp; </span></span><span style="display:flex;"><span>T1=<span style="color:#a31515">${</span>!<span style="color:#a31515">}</span> </span></span><span style="display:flex;"><span>wait <span style="color:#a31515">${</span>T1<span style="color:#a31515">}</span> </span></span></code></pre><p>Because OhMyBash does <code>exec bash</code> at the end, this traps our script inside another shell and our script cannot continue. For that reason, I executed this in background. But that presents a new problem. Because this is executed in background, we lose track of progress naturally. And that strange trick with <code>T1=${!}</code> and <code>wait ${T1}</code> waits for the background process to finish before continuing to another task in bash script.</p> <p>Check <a href="https://www.cloudsavvyit.com/12277/how-to-use-multi-threaded-processing-in-bash-scripts/">Multi-Threaded Processing in Bash Scripts</a> for more details.</p> <h2 id="conclusion">Conclusion</h2> <p>Take a look at <a href="https://github.com/mitjafelicijan/dfd-rice/blob/develop/tools/install.sh">https://github.com/mitjafelicijan/dfd-rice/blob/develop/tools/install.sh</a> script to get familiar with it. This is just a first iteration and I will continue to update it because I need this in my life.</p> <p>The current version boots in 4s to the login prompt, and after you log in, the desktop environment loads in 2s. So, its fast, very fast. And on clean boot, I measured ~230 MB of RAM usage.</p> <p>And this is how it looks with two terminals side by side. I really like the simplicity and clean interface. I will polish the colors and stuff like that, but I really do like the results.</p> <figure> <img src="/posts/dfd-rice/desktop.png" alt="" /> </figure> List of essential Linux commands for server management https://mitjafelicijan.com/linux-cheatsheet.html Sun, 01 Aug 2021 12:00:00 +0200 https://mitjafelicijan.com/linux-cheatsheet.html Generate SSH keyssh-keygen -t ed25519 -C &#34;your_email@example. <p><strong>Generate SSH key</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>ssh-keygen -t ed25519 -C <span style="color:#a31515">&#34;your_email@example.com&#34;</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># when no support for Ed25519 present</span> </span></span><span style="display:flex;"><span>ssh-keygen -t rsa -b 4096 -C <span style="color:#a31515">&#34;your_email@example.com&#34;</span> </span></span></code></pre><p>Note: By default SSH keys get stored to <code>/home/&lt;username&gt;/.ssh/</code> folder.</p> <p><strong>Login to host via SSH</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># connect to host as your local username</span> </span></span><span style="display:flex;"><span>ssh host </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># connect to host as user</span> </span></span><span style="display:flex;"><span>ssh &lt;user&gt;@&lt;host&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># connect to host using port</span> </span></span><span style="display:flex;"><span>ssh -p &lt;port&gt; &lt;user&gt;@&lt;host&gt; </span></span></code></pre><p><strong>Execute command on a server through SSH</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># execute one command</span> </span></span><span style="display:flex;"><span>ssh root@100.100.100.100 <span style="color:#a31515">&#34;ls /root&#34;</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># execute many commands</span> </span></span><span style="display:flex;"><span>ssh root@100.100.100.100 <span style="color:#a31515">&#34;cd /root;touch file.txt&#34;</span> </span></span></code></pre><p><strong>Displays currently logged in users in the system</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>w </span></span></code></pre><p><strong>Displays Linux system information</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>uname </span></span></code></pre><p><strong>Displays kernel release information</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>uname -r </span></span></code></pre><p><strong>Shows the system hostname</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>hostname </span></span></code></pre><p><strong>Shows system reboot history</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>last reboot </span></span></code></pre><p><strong>Displays information about the user</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>sudo apt install finger </span></span><span style="display:flex;"><span>finger &lt;username&gt; </span></span></code></pre><p><strong>Displays IP addresses and all the network interfaces</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>ip addr show </span></span></code></pre><p><strong>Downloads a file from an online source</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>wget https://example.com/example.tgz </span></span></code></pre><p>Note: If URL contains ?, &amp; enclose the URL in double quotes.</p> <p><strong>Compress a file with gzip</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># will not keep the original file</span> </span></span><span style="display:flex;"><span>gzip file.txt </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># will keep the original file</span> </span></span><span style="display:flex;"><span>gzip --keep file.txt </span></span></code></pre><p><strong>Interactive disk usage analyzer</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>sudo apt install ncdu </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>ncdu </span></span><span style="display:flex;"><span>ncdu &lt;path/to/directory&gt; </span></span></code></pre><p><strong>Install Node.js using the Node Version Manager</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash </span></span><span style="display:flex;"><span>source ~/.bashrc </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>nvm install v13 </span></span></code></pre><p><strong>Too long; didn't read</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>npm install -g tldr </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>tldr tar </span></span></code></pre><p><strong>Combine all Nginx access logs to one big log file</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>zcat -f /var/log/nginx/access.log* &gt; /var/log/nginx/access-all.log </span></span></code></pre><p><strong>Set up Redis server</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>sudo apt install redis-server redis-tools </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># check if server is running</span> </span></span><span style="display:flex;"><span>sudo service redis status </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># set and get a key value</span> </span></span><span style="display:flex;"><span>redis-cli set mykey myvalue </span></span><span style="display:flex;"><span>redis-cli get mykey </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># interactive shell</span> </span></span><span style="display:flex;"><span>redis-cli </span></span></code></pre><p><strong>Generate statistics of your webserver</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>sudo apt install goaccess </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># check if installed</span> </span></span><span style="display:flex;"><span>goaccess -v </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># combine logs</span> </span></span><span style="display:flex;"><span>zcat -f /var/log/nginx/access.log* &gt; /var/log/nginx/access-all.log </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># export to single html</span> </span></span><span style="display:flex;"><span>goaccess <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> --log-file=/var/log/nginx/access-all.log <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> --log-format=COMBINED <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> --exclude-ip=0.0.0.0 <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> --ignore-crawlers <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> --real-os <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> --output=/var/www/html/stats.html </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># cleanup afterwards</span> </span></span><span style="display:flex;"><span>rm /var/log/nginx/access-all.log </span></span></code></pre><p><strong>Search for a given pattern in files</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>grep -r ‘pattern’ files </span></span></code></pre><p><strong>Find proccess ID for a specific program</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>pgrep nginx </span></span></code></pre><p><strong>Print name of current/working directory</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>pwd </span></span></code></pre><p><strong>Creates a blank new file</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>touch newfile.txt </span></span></code></pre><p><strong>Displays first lines in a file</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># -n &lt;x&gt; presents the number of lines (10 by default)</span> </span></span><span style="display:flex;"><span>head -n 20 somefile.txt </span></span></code></pre><p><strong>Displays last lines in a file</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># -n &lt;x&gt; presents the number of lines (10 by default)</span> </span></span><span style="display:flex;"><span>tail -n 20 somefile.txt </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># -f follows the changes in file (doesn&#39;t closes)</span> </span></span><span style="display:flex;"><span>tail -f somefile.txt </span></span></code></pre><p><strong>Count lines in a file</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>wc -l somefile.txt </span></span></code></pre><p><strong>Find all instances of the file</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>sudo apt install mlocate </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>locate somefile.txt </span></span></code></pre><p><strong>Find file names that begin with ‘index’ in /home folder</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>find /home/ -name <span style="color:#a31515">&#34;index&#34;</span> </span></span></code></pre><p><strong>Find files larger than 100MB in the home folder</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>find /home -size +100M </span></span></code></pre><p><strong>Displays block devices related information</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>lsblk </span></span></code></pre><p><strong>Displays free space on mounted systems</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>df -h </span></span></code></pre><p><strong>Displays free and used memory in the system</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>free -h </span></span></code></pre><p><strong>Displays all active listening ports</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>sudo apt install net-tools </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>netstat -pnltu </span></span></code></pre><p><strong>Kill a process violently</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>kill -9 &lt;pid&gt; </span></span></code></pre><p><strong>List files opened by user</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>lsof -u &lt;user&gt; </span></span></code></pre><p><strong>Execute &quot;df -h&quot;, showing periodic updates</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># -n 1 means every second</span> </span></span><span style="display:flex;"><span>watch -n 1 df -h </span></span></code></pre> My journey from being an internet über consumer to being a full hominum again https://mitjafelicijan.com/from-internet-consumer-to-full-hominum-again.html Fri, 30 Jul 2021 12:00:00 +0200 https://mitjafelicijan.com/from-internet-consumer-to-full-hominum-again.html It&#39;s been almost a year since I started purging all my online accounts andgoing down this rabbit hole of being almost independent of the current internetmachine. <p>It's been almost a year since I started purging all my online accounts and going down this rabbit hole of being almost independent of the current internet machine. Even though I initially thought that I will have problems adapting, I was pleasantly surprised that the transition went so smoothly. Even better, it brought many benefits to my life. Such as increased focus, less stress about trivial things, etc.</p> <p>It all started with me doing small changes like unsubscribing from emails that I have either subscribed to by accepting terms and conditions. Or even some more malicious emails that I was getting because I was on a shared mailing list. And the later ones I hate the most of all. How the hell do they keep sharing my email and sending me unsolicited emails and get away with it? I have a suspicion that these marketing people share an Excel file between them and keep resubscribing me when they import lists into Mailchimp or similar software.</p> <p>It's fascinating to see how much crap you get subscribed to when you are not paying attention. It got so bad that my primary Gmail address is a full of junk and need constant monitoring and cleaning up. And because I want to have Inbox Zero, this presents an additional problem for me.</p> <p>The stress that email presented for me didn't occur to me for a long time. I was noticing that I was unable to go through one single hour without hysterically refreshing email. And if somebody wrote me something, I needed to see it right then, even though I didn't immediately reply to it. I can only describe this with FOMO (fear of missing out). I have no other explanation than that. It was crippling, and I was constantly context switching, which I will address further down this post in more details.</p> <p>This was one of the reasons why I spawned up my personal email server, and I am using it now as my primary and person email. I still have Gmail as my “junk” email that I use for throw away stuff. I log in to Gmail once a week and check if there are any important emails that I got, but apart from that, it's sitting dormant and collecting dust.</p> <p>The more I was watching the world loose it's self with allowing anti freedom things to happen to it, the more I started to realize that something has to change. I don't have the power to change the world. And I also don't have a grandiose opinion of myself to even think to try it. But what I can do is to not subscribe to this consumer way of thinking. I will not be complicit in this. My moral and ethical stances won't allow it. So, this brings us to the second part of my journey.</p> <p>I was using all these 3rd party services because I was either lazy or OK with the drawbacks of them. I watched these services and companies became more and privacy policies and everybody is OK with accepting them, and they pray on that more evil. It is evil if you sell your user's data in this manner. Nobody reads flaw in human nature. I really hate the hypocrisy they manage to muster. These companies prey on our laziness, and we are at fault here. Nobody else. And I truly understand the reasons why we rather accept and move on, and not object and have our lives a little more difficult. They have perfected this through years of small changes that make us a little more dependent on them. You could not convince a person to give away all his rights and data in one day. This was gradual and slow. And it caught us all in surprise. When I really stopped and thought about it, I felt repulsed. By really stopping and thinking about it, I really mean stopping and thinking about it. Thoroughly and in depth.</p> <p>Each step I took depleted my character a bit more. Like I was trading myself bit by bit without understanding what it all meant. What it meant to be a full person, not divided by all this bought attention they want from me. They don't just get your data, but they also take your attention away from you. They scatter your and go with the divide and conquer tactic from there. And a person divided is a person not fully there. Not at the moment. Not alive fully.</p> <p>I was unable to form long thoughts. Well, I thought I was. But now that I see what being a full person is again, I can see that I was not at my 100% back then.</p> <p>A revolt was inevitable. There was no other way of continuing my story without it. Without taking back my attention, my thoughts, my time, and my privacy, regardless of how too late it maybe is.</p> <p>This has nothing to do with conspiracy theories. Even less with changing the world. All I wanted was to get my life back in order and not waste the energy that could be spent in other, better places.</p> <p>I started reading more. I can focus now fully on things I work on. Furthermore, I have the mental acuity that I never had before. My mind feels sharp. I don't get angry so much. I can cherish the finer things in life now without the need to interpret them intellectually. Not only that, but I have a feeling of belonging again. Sense of purpose has returned with a vengeance. And I can now help people without depleting myself.</p> <p>The last step so far was to finish closing all the remaining online accounts that I still had. And when I was thinking what value they bring me, I wasn't surprised that the answer was none. I wasn't logging in them and using them. I stopped being afraid of FOMO. If somebody wants to get in contact me, they will find a way. I am one search away.</p> <p>We are not beholden to anybody. Our lives are our own. So dare yourself to delete Facebook, LinkedIn. To unsubscribe. Dare yourself to take your time and attention back. Use that time and energy to go for a walk without thinking about work. Read a book instead of reading comment on social media that you will forget in an hour. Enrich your life instead of wasting it. It only requires a small step. And you will feel the benefits immediately. Lose the weight of the world that is crushing you without your consent.</p> Simple world clock with eInk display and Raspberry Pi Zero https://mitjafelicijan.com/simple-world-clock-with-eiink-display-and-raspberry-pi-zero.html Sat, 26 Jun 2021 12:00:00 +0200 https://mitjafelicijan.com/simple-world-clock-with-eiink-display-and-raspberry-pi-zero.html Our team is spread across the world, from the USA all the way to Australia, sohaving some sort of world clock makes sense. <p>Our team is spread across the world, from the USA all the way to Australia, so having some sort of world clock makes sense.</p> <p>Currently, I am using an extension for Gnome called <a href="https://extensions.gnome.org/extension/2657/timezones-extension/">Timezone extension</a>, and it serves the purpose quite well.</p> <p>But I also have a bunch of electronics that I bought through the time, and I am not using any of them, and it's time to stop hording this stuff and use it in a project.</p> <p>A while ago I bought a small eInk display <a href="https://shop.pimoroni.com/products/inky-phat?variant=12549254217811">Inky pHAT</a> and I have a bunch of <a href="https://www.raspberrypi.org/products/raspberry-pi-zero/">Raspberry Pi's Zero</a> lying around that I really need to use.</p> <figure> <img src="/posts/world-clock/hardware.jpg" alt="Inky pHAT, Raspberry Pi Zero" /> </figure> <p>Since the Inky <a href="https://shop.pimoroni.com/products/inky-phat?variant=12549254217811">Inky pHAT</a> is essentially a HAT, it can easily be added on top of the <a href="https://www.raspberrypi.org/products/raspberry-pi-zero/">Raspberry Pi Zero</a>.</p> <p>First, I installed the necessary software on Raspberry Pi with <code>pip3 install inky</code>.</p> <p>And then I created a file <code>clock.py</code> in home directory <code>/home/pi</code>.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000">#!/usr/bin/env python</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># -*- coding: utf-8 -*-</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> sys </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> os </span></span><span style="display:flex;"><span><span style="color:#00f">from</span> inky.auto <span style="color:#00f">import</span> auto </span></span><span style="display:flex;"><span><span style="color:#00f">from</span> PIL <span style="color:#00f">import</span> Image, ImageFont, ImageDraw </span></span><span style="display:flex;"><span><span style="color:#00f">from</span> font_fredoka_one <span style="color:#00f">import</span> FredokaOne </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>clocks = [ </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;America/New_York&#39;</span>, </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;Europe/Ljubljana&#39;</span>, </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;Australia/Brisbane&#39;</span>, </span></span><span style="display:flex;"><span>] </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>board = auto() </span></span><span style="display:flex;"><span>board.set_border(board.WHITE) </span></span><span style="display:flex;"><span>board.rotation = 90 </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>img = Image.new(<span style="color:#a31515">&#39;P&#39;</span>, (board.WIDTH, board.HEIGHT)) </span></span><span style="display:flex;"><span>draw = ImageDraw.Draw(img) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>big_font = ImageFont.truetype(FredokaOne, 18) </span></span><span style="display:flex;"><span>small_font = ImageFont.truetype(FredokaOne, 13) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>x = board.WIDTH / 3 </span></span><span style="display:flex;"><span>y = board.HEIGHT / 3 </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>idx = 1 </span></span><span style="display:flex;"><span><span style="color:#00f">for</span> clock <span style="color:#00f">in</span> clocks: </span></span><span style="display:flex;"><span> ctime = os.popen(<span style="color:#a31515">&#39;TZ=&#34;</span><span style="color:#a31515">{}</span><span style="color:#a31515">&#34; date +&#34;</span><span style="color:#a31515">%a</span><span style="color:#a31515">,%H:%M&#34;&#39;</span>.format(clock)) </span></span><span style="display:flex;"><span> ctime = ctime.read().strip().split(<span style="color:#a31515">&#39;,&#39;</span>) </span></span><span style="display:flex;"><span> city = clock.split(<span style="color:#a31515">&#39;/&#39;</span>)[1].replace(<span style="color:#a31515">&#39;_&#39;</span>, <span style="color:#a31515">&#39; &#39;</span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> draw.text((15, (idx*y)-y+10), city, fill=board.BLACK, font=small_font) </span></span><span style="display:flex;"><span> draw.text((110, (idx*y)-y+7), str(ctime[0]), fill=board.BLACK, font=big_font) </span></span><span style="display:flex;"><span> draw.text((155, (idx*y)-y+7), str(ctime[1]), fill=board.BLACK, font=big_font) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> idx += 1 </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>board.set_image(img) </span></span><span style="display:flex;"><span>board.show() </span></span></code></pre><p>And because eInk displays are rather slow to refresh and the clock requires refreshing only once a minute, this can be done through cronjob.</p> <p>Before we add this job to cron we need to make <code>clock.py</code> executable with <code>chmod +x clock.py</code>.</p> <p>Then we add a cronjob with <code>crontab -e</code>.</p> <pre><code>* * * * * /home/pi/clock.py </code></pre> <p>So, we end up with a result like this.</p> <figure> <img src="/posts/world-clock/world-clock.jpg" alt="World Clock" /> </figure> <p>And for the enclosure that can be 3D printed, but I haven't yet something like this can be used.</p> <iframe id="vs_iframe" src="https://www.viewstl.com/?embedded&url=https%3A%2F%2Fmitjafelicijan.com%2Fposts%2Fworld-clock%2Fenclosure.stl&color=gray&bgcolor=white&edges=no&orientation=front&noborder=no" style="border:0;margin:0;width:100%;height:400px;"></iframe> <p>You can download my <a href="/posts/world-clock/enclosure.stl">STL file for the enclosure here</a>, but make sure that dimensions make sense and also opening for USB port should be added or just use a drill and some hot glue to make it stick in the enclosure.</p> Using GoAccess with Nginx to replace Google Analytics https://mitjafelicijan.com/using-goaccess-with-nginx-to-replace-google-analytics.html Mon, 25 Jan 2021 12:00:00 +0200 https://mitjafelicijan.com/using-goaccess-with-nginx-to-replace-google-analytics.html IntroductionI know! <h2 id="introduction">Introduction</h2> <p>I know! You cannot simply replace Google Analytics with parsing access logs and displaying a couple of charts. But to be honest, I actually never used Google Analytics to the fullest extent and was usually interested in seeing page hits and which pages were visited most often.</p> <p>I recently moved my blog from Firebase to a VPS and also decided to remove Google Analytics tracking code from the site since its quite malicious and tracks users across other pages also and is creating a profile of a user, and I've had it. But I also need some insight of what is happening on a server and which content is being read the most etc.</p> <p>I have looked at many existing solutions like:</p> <ul> <li><a href="https://umami.is/">Umami</a></li> <li><a href="https://github.com/sheshbabu/freshlytics">Freshlytics</a></li> <li><a href="https://matomo.org/">Matomo</a></li> </ul> <p>But the more I looked at them the more I noticed that I am replacing one evil with another one. Don't get me wrong. Some of these solutions are absolutely fantastic but would require installation of databases and something like PHP or Node. And I was not ready to put those things on my fresh server. Also having Docker installed is out of the question.</p> <h2 id="opting-for-log-parsing">Opting for log parsing</h2> <p>So, I defaulted to parsing already existing logs and generating HTML reports from this data.</p> <p>I found this amazing software <a href="https://goaccess.io/">GoAccess</a> which provides all the functionalities I need, and it's a single binary. Written in Go.</p> <p>GoAccess can be used in two different modes.</p> <figure> <img src="/posts/goaccess/goaccess-dash-term.png" alt="GoAccess Terminal" /> </figure> <center><i>Running in a terminal</i></center> <figure> <img src="/posts/goaccess/goaccess-dash-html.png" alt="GoAccess HTML" /> </figure> <center><i>Running in a browser</i></center> <p>I, however, need this to run in a browser. So, the second option is the way to go. The Idea is to periodically run cronjob and export this report into a folder that gets then server by Nginx behind a Basic authentication.</p> <h2 id="getting-nginx-ready">Getting Nginx ready</h2> <p>I choose Ubuntu on <a href="https://www.digitalocean.com/">DigitalOcean</a>. First I installed <a href="https://nginx.org/en/">Nginx</a>, and <a href="https://letsencrypt.org/getting-started/">Letsencrypt</a> certbot and all the necessary dependencies.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># log in as root user</span> </span></span><span style="display:flex;"><span>sudo su - </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># first let&#39;s update the system</span> </span></span><span style="display:flex;"><span>apt update &amp;&amp; apt upgrade -y </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># let&#39;s install</span> </span></span><span style="display:flex;"><span>apt install nginx certbot python3-certbot-nginx apache2-utils </span></span></code></pre><p>After all this is installed we can create a new configuration for a statistics. Stats will be available at <code>stats.domain.com</code>.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># creates directory where html will be hosted</span> </span></span><span style="display:flex;"><span>mkdir -p /var/www/html/stats.domain.com </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>cp /etc/nginx/sites-available/default /etc/nginx/sites-available/stats.domain.com </span></span><span style="display:flex;"><span>nano /etc/nginx/sites-available/stats.domain.com </span></span></code></pre><pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">server</span> { </span></span><span style="display:flex;"><span> <span style="color:#00f">root</span> <span style="color:#a31515">/var/www/html/stats.domain.com</span>; </span></span><span style="display:flex;"><span> <span style="color:#00f">server_name</span> <span style="color:#a31515">stats.domain.com</span>; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">index</span> <span style="color:#a31515">index.html</span>; </span></span><span style="display:flex;"><span> <span style="color:#00f">location</span> <span style="color:#a31515">/</span> { </span></span><span style="display:flex;"><span> <span style="color:#00f">try_files</span> $uri $uri/ =404; </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span>} </span></span></code></pre><p>Now we check if the configuration is ok. We can do this with <code>nginx -t</code>. If all is ok, we can restart Nginx with <code>service nginx restart</code>.</p> <p>After all that you should add A record for this domain that points to IP of a droplet.</p> <p>Before enabling SSL you should test if DNS records have propagated with <code>curl stats.domain.com</code>.</p> <p>Now, it's time to provision TLS certificate. To achieve this, you execute command <code>certbot --nginx</code>. Follow the wizard and when you are asked about redirection always choose 2 (always redirect to HTTPS).</p> <p>When this is done you can visit <a href="https://stats.domain.com">https://stats.domain.com</a> and you should get 404 not found error which is correct.</p> <h2 id="getting-goaccess-ready">Getting GoAccess ready</h2> <p>If you are using Debian like system GoAccess should be available in repository. Otherwise refer to the official website.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>apt install goaccess </span></span></code></pre><p>To enable Geo location we also need one additiona thing.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>cd /var/www/html/stats.stats.com </span></span><span style="display:flex;"><span>wget https://github.com/P3TERX/GeoLite.mmdb/raw/download/GeoLite2-City.mmdb </span></span></code></pre><p>Now we create a shell script that will be executed every 10 minutes.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>nano /var/www/html/stats.domain.com/generate-stats.sh </span></span></code></pre><p>Contents of this file should look like this.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">#!/bin/sh </span></span></span><span style="display:flex;"><span><span style="color:#00f"></span> </span></span><span style="display:flex;"><span>zcat -f /var/log/nginx/access.log* &gt; /var/log/nginx/access-all.log </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>goaccess <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> --log-file=/var/log/nginx/access-all.log <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> --log-format=COMBINED <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> --exclude-ip=0.0.0.0 <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> --geoip-database=/var/www/html/stats.domain.com/GeoLite2-City.mmdb <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> --ignore-crawlers <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> --real-os <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> --output=/var/www/html/stats.domain.com/index.html </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>rm /var/log/nginx/access-all.log </span></span></code></pre><p>Because after a while nginx creates multiple files with access logs we use <a href="https://linux.die.net/man/1/zcat"><code>zcat</code></a> to extract Gziped contents and create a file that has all the access logs. After this file is used we delete it.</p> <p>If you want to exclude your home IP's result look at the <code>--exclude-ip</code> option in script and instead of <code>0.0.0.0</code> add your own home IP address. You can find your home IP by executing <code>curl ifconfig.me</code> from your local machine and NOT from the droplet.</p> <p>Test the script by executing <code>sh /var/www/html/stats.domain.com/generate-stats.sh</code> and then checking <code>https://stats.domain.com</code>. If you can see stats instead of 404 than you are set.</p> <p>It's time to add this script to cron with <code>cron -e</code>.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>*/10 * * * * sh /<span style="color:#00f">var</span>/www/html/stats.domain.com/generate-stats.sh </span></span></code></pre><h2 id="securing-with-basic-authentication">Securing with Basic authentication</h2> <p>You probably don't want stats to be publicly available, so we should create a user and a password for Basic authentication.</p> <p>First we create a password for a user <code>stats</code> with <code>htpasswd -c /etc/nginx/.htpasswd stats</code>.</p> <p>Now we update config file with <code>nano /etc/nginx/sites-available/stats.domain.com</code>. You probably noticed that the file looks a bit different from before. This is because <code>certbot</code> added additional rules for SSL.</p> <p>Your location portion the config file should now look like. You should add <code>auth_basic</code> and <code>auth_basic_user_file</code> lines to the file.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">location</span> <span style="color:#a31515">/</span> { </span></span><span style="display:flex;"><span> <span style="color:#00f">try_files</span> $uri $uri/ =404; </span></span><span style="display:flex;"><span> <span style="color:#00f">auth_basic</span> <span style="color:#a31515">&#34;Private</span> <span style="color:#a31515">Property&#34;</span>; </span></span><span style="display:flex;"><span> <span style="color:#00f">auth_basic_user_file</span> <span style="color:#a31515">/etc/nginx/.htpasswd</span>; </span></span><span style="display:flex;"><span>} </span></span></code></pre><p>Test if config is still ok with <code>nginx -t</code> and if it is you can restart Nginx with <code>service nginx restart</code>.</p> <p>If you now visit <code>https://stats.domain.com</code> you should be prompted for username and password. If not, try reopening your browser.</p> <p>That is all. You now have analytics for your server that gets refreshed every 10 minutes.</p> Replacing Dropbox in favor of DigitalOcean spaces https://mitjafelicijan.com/replacing-dropbox-in-favor-of-digitalocean-spaces.html Sun, 24 Jan 2021 12:00:00 +0200 https://mitjafelicijan.com/replacing-dropbox-in-favor-of-digitalocean-spaces.html A few months ago I experimented with DigitalOcean spaces as my backup solutionthat could replace Dropboxeventually. <p>A few months ago I experimented with DigitalOcean spaces as my backup solution that could <a href="/digitalocean-spaces-to-sync-between-computers.html">replace Dropbox eventually</a>. That solution worked quite nicely, and I was amazed how smashing together a couple of existing solutions would work this fine.</p> <p>I have been running that solution in the background for a couple of months now and kind of forgot about it. But recent developments around deplatforming and having us people hostages of technology and big companies speed up my goals to become less dependent on <a href="https://edition.cnn.com/2020/12/17/tech/google-antitrust-lawsuit/index.html">Google</a>, <a href="https://www.pcworld.com/article/2048680/dropbox-takes-a-peek-at-files.html">Dropbox</a> etc and take back some control.</p> <p>I am not a conspiracy theory nut, but to be honest, what these companies are doing lately is out of control. It is a matter of principle at this point. I have almost completely degoogled my life all the way from ditching Gmail, YouTube and most of the services surrounding Google. And I must tell you, I feel so good. I haven't felt this way for a long time.</p> <p><strong>Anyways. Let's get to the meat of things.</strong></p> <p>Before you continue you should read my post about <a href="/digitalocean-spaces-to-sync-between-computers.html">syncing to Dropbox</a>.</p> <blockquote> <p>Also to note, I am using Linux on my machine with Gnome desktop environment. This should work on MacOS too. To use this on Windows I suggest using <a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10">Subsystem for Linux</a> or <a href="https://www.cygwin.com/">Cygwin</a>.</p> </blockquote> <h2 id="folder-structure">Folder structure</h2> <p>I liked structure from Dropbox. One folder where everything is located and synced. So, that's why adopted this also for my sync setup.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="">~</span>/Vault </span></span><span style="display:flex;"><span> <span style="">↳</span> backup </span></span><span style="display:flex;"><span> <span style="">↳</span> bin </span></span><span style="display:flex;"><span> <span style="">↳</span> documents </span></span><span style="display:flex;"><span> <span style="">↳</span> projects </span></span></code></pre><p>All of my code is located in <code>~/Vault/projects</code> folder. And most of the projects are Git repositories. I do not use this sync method for backup per see but in case I reinstall my machine I can easily recreate all the important folder structure with one quick command. No external drives needed that can fail etc.</p> <h2 id="sync-script">Sync script</h2> <p>My sync script is located in <code>~/Vault/bin/vault-backup.sh</code></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">#!/bin/bash </span></span></span><span style="display:flex;"><span><span style="color:#00f"></span> </span></span><span style="display:flex;"><span><span style="color:#008000"># dconf load /com/gexperts/Tilix/ &lt; tilix.dconf</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># 0 2 * * * sh ~/Vault/bin/vault-backup.sh</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>cd ~/Vault/backup/dotfiles </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>MACHINE=<span style="color:#00f">$(</span>whoami<span style="color:#00f">)</span>@<span style="color:#00f">$(</span>hostname<span style="color:#00f">)</span> </span></span><span style="display:flex;"><span>mkdir -p $MACHINE </span></span><span style="display:flex;"><span>cd $MACHINE </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>cp ~/.config/VSCodium/User/settings.json settings.json </span></span><span style="display:flex;"><span>cp ~/.s3cfg s3cfg </span></span><span style="display:flex;"><span>cp ~/.bash_extended bash_extended </span></span><span style="display:flex;"><span>cp ~/.ssh ssh -rf </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>codium --list-extensions &gt; vscode-extension.txt </span></span><span style="display:flex;"><span>dconf dump /com/gexperts/Tilix/ &gt; tilix.dconf </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>cd ~/Vault </span></span><span style="display:flex;"><span>s3cmd sync --delete-removed --exclude <span style="color:#a31515">&#39;node_modules/*&#39;</span> --exclude <span style="color:#a31515">&#39;.git/*&#39;</span> --exclude <span style="color:#a31515">&#39;.venv/*&#39;</span> ./ s3://bucket-name/backup/ </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>echo <span style="color:#a31515">`</span>date +<span style="color:#a31515">&#34;%D %T&#34;</span><span style="color:#a31515">`</span> &gt;&gt; ~/.vault.log </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>notify-send <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> -u normal <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> -i /usr/share/icons/Adwaita/96x96/status/security-medium-symbolic.symbolic.png <span style="color:#a31515">\ </span></span></span><span style="display:flex;"><span><span style="color:#a31515"></span> <span style="color:#a31515">&#34;Vault sync succeded at `date +&#34;</span>%D %T<span style="color:#a31515">&#34;`&#34;</span> </span></span></code></pre><p>This script also backups some of the dotfiles I use and sends notification to Gnome notification center. It is a straightforward solution. Nothing special going on.</p> <blockquote> <p>One obvious benefit of this is that I can omit syncing Node's <code>node_modules</code> or Python's <code>.venv</code> and <code>.git</code> folders.</p> </blockquote> <p>You can use this script in a combination with <a href="https://en.wikipedia.org/wiki/Cron">Cron</a>.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>0 2 * * * sh ~/Vault/bin/vault-backup.sh </span></span></code></pre><p>When you start syncing your local stuff with a remote server you can review your items on DigitalOcean.</p> <figure> <img src="/posts/dropbox-sync/dropbox-spaces.png" alt="Dropbox Spaces" /> </figure> <p>I have been using this script now for quite some time, and it's working flawlessly. I also uninstalled Dropbox and stopped using it completely.</p> <p>All I need to do is write a Bash script that does the reverse and downloads from remote server to local folder. This could be another post.</p> Using Digitalocean Spaces to sync between computers https://mitjafelicijan.com/digitalocean-spaces-to-sync-between-computers.html Wed, 09 Sep 2020 12:00:00 +0200 https://mitjafelicijan.com/digitalocean-spaces-to-sync-between-computers.html I&#39;ve been using Dropbox for probably 10+ yearsnow and I-ve became so used to it that it runs in the background that I don&#39;teven imagine a world without it. <p>I've been using <a href="https://www.dropbox.com/">Dropbox</a> for probably <strong>10+ years</strong> now and I-ve became so used to it that it runs in the background that I don't even imagine a world without it. But it's not without problems.</p> <p>At first I had problems with <code>.venv</code> environments for Python and the only solution for excluding synchronization for this folder was to manually exclude a specific folder which is not really scalable. FYI, my whole project folder is synced on <a href="https://www.dropbox.com/">Dropbox</a>. This of course introduced a lot of syncing of files and folders that are not needed or even break things on other machines. In the case of <strong>Python</strong>, I couldn't use that on my second machine. I needed to delete <code>.venv</code> folder and pip it again which synced files again to the main machine. This was very frustrating. <strong>Nodejs</strong> handles this much nicer and I can just run the scripts without deleting <code>node_modules</code> again and reinstalling. However, <code>node_modules</code> is a beast of its own. It creates so many files that OS has a problem counting them when you check the folder contents for size.</p> <p>I wanted something similar to Dropbox. I could without the instant syncing but it would need to be fast and had the option for me to exclude folders like <code>node_modules, .venv, .git</code> and folders like that.</p> <p>I went on a hunt for an alternative to <a href="https://www.dropbox.com/">Dropbox</a> and found:</p> <ul> <li><a href="https://tresorit.com/">Tresorit</a></li> <li><a href="https://sync.com">Sync.com</a></li> <li><a href="https://www.box.com/">Box</a></li> </ul> <p>You know, the usual list of suspects. I didn't include <a href="https://drive.google.com">Google drive</a> or <a href="https://onedrive.live.com/">One drive</a> since they are even more draconian than Dropbox.</p> <blockquote> <p>All this does not stem from me being paranoid but recently these companies have became more and more aggressive and they keep violating our privacy when they share our data with 3rd party services. It is getting out of control.</p> </blockquote> <p>So, my main problem was still there. No way of excluding a specific folder from syncing. And before we go into &quot;<em>But you have git, isn't that enough?</em>&quot;, I must say, that many of the files (PDFs, spreadsheets, etc) I have in a <code>git</code> repo don't get pushed upstream to Git and I still want to have them synced across my computers.</p> <p>I initially wanted to use <a href="https://linux.die.net/man/1/rsync">rsync</a> but I would need to then have a remote VPS or transfer between my computers directly. I wanted a solution where all my files could be accessible to me without my machine.</p> <blockquote> <p><strong>WARNING: This solution will cost you money!</strong> DigitalOcean Spaces are $5 per month and there are some bandwidth limitations and if you go beyond that you get billed additionally.</p> </blockquote> <p>Then I remembered that I could use something like <a href="https://en.wikipedia.org/wiki/Amazon_S3">S3</a> since it has versioning and is fully managed. I didn't want to go down the AWS rabbit hole with this so I choose <a href="https://www.digitalocean.com/products/spaces/">DigitalOcean Spaces</a>.</p> <p>Then I needed a command-line tool to sync between source and target. I found this nice tool <a href="https://s3tools.org/s3cmd">s3cmd</a> and it is in the Ubuntu repositories.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>sudo apt install s3cmd </span></span></code></pre><p>After installation will I create a new Space bucket on DigitalOcean. Remember the zone you will choose because you will need it when you will configure <code>s3cmd</code>.</p> <p>Then I visited <a href="https://cloud.digitalocean.com/account/api/tokens">Digitalocean Applications &amp; API</a> and generated <strong>Spaces access keys</strong>. Save both key and secret somewhere safe because when you will leave the page secret will not be available anymore to you and you will need to re-generate it.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># enter your key and secret and correct endpoint</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># my endpoint is ams3.digitaloceanspaces.com because</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># I created my bucket in Amsterdam regiin</span> </span></span><span style="display:flex;"><span>s3cmd --configure </span></span></code></pre><p>After that I played around with options for <code>s3cmd</code> and got to the following command.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># I executed this command from my projects folder</span> </span></span><span style="display:flex;"><span>cd projects </span></span><span style="display:flex;"><span>s3cmd sync --delete-removed --exclude <span style="color:#a31515">&#39;node_modules/*&#39;</span> --exclude <span style="color:#a31515">&#39;.git/*&#39;</span> --exclude <span style="color:#a31515">&#39;.venv/*&#39;</span> ./ s3://my-bucket-name/projects/ </span></span></code></pre><p>When syncing int he other direction you will need to change the order of the <code>SOURCE</code> and <code>TARGET</code> to <code>s3://my-bucket-name/projects/</code> and <code>./</code>.</p> <blockquote> <p>Be sure that all the paths have trailing slash so that sync knows that this are directories.</p> </blockquote> <p>I am planning to implement some sort of a <code>.ignore</code> file that will enable me to have a project-specific exclude options.</p> <p>I am currently running this every hour as a cronjob which is perfectly fine for now when I am testing how this whole thing works and how it all will turn out.</p> <p>I have also created a small Gnome extension which is still very unstable, but when/if this whole experiment pays of I will share on Github.</p> Fix bind warning in .profile on login in Ubuntu https://mitjafelicijan.com/bind-warning-on-login-in-ubuntu.html Tue, 08 Sep 2020 12:00:00 +0200 https://mitjafelicijan.com/bind-warning-on-login-in-ubuntu.html Recently I moved back to bash as mydefault shell. <p>Recently I moved back to <a href="https://www.gnu.org/software/bash/">bash</a> as my default shell. I was previously using <a href="https://fishshell.com/">fish</a> and got used to the cool features it has. But, regardless of that, I wanted to move to a more standard shell because I was hopping back and forth with exporting variables and stuff like that which got pretty annoying.</p> <p>So I embarked on a mission to make <a href="https://www.gnu.org/software/bash/">bash</a> more like <a href="https://fishshell.com/">fish</a> and in the process found that I really missed autosuggest with TAB on changing directories.</p> <p>I found a nice alternative that emulates <a href="http://zsh.sourceforge.net/">zsh</a> like autosuggestion and autocomplete so I added the following to my <code>.bashrc</code> file.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>bind <span style="color:#a31515">&#34;TAB:menu-complete&#34;</span> </span></span><span style="display:flex;"><span>bind <span style="color:#a31515">&#34;set show-all-if-ambiguous on&#34;</span> </span></span><span style="display:flex;"><span>bind <span style="color:#a31515">&#34;set completion-ignore-case on&#34;</span> </span></span><span style="display:flex;"><span>bind <span style="color:#a31515">&#34;set menu-complete-display-prefix on&#34;</span> </span></span><span style="display:flex;"><span>bind <span style="color:#a31515">&#39;&#34;\e[Z&#34;:menu-complete-backward&#39;</span> </span></span></code></pre><p>I haven't noticed anything wrong with this and all was working fine until I restarted my machine and then I got this error.</p> <figure> <img src="/posts/profile-bind-error/error.jpg" alt="Profile bind error" /> </figure> <p>When I pressed OK, I got into the <a href="https://wiki.gnome.org/Projects/GnomeShell">Gnome shell</a> and all was working fine, but the error was still bugging me. I started looking for the reason why this is happening and found a solution to this error on <a href="https://superuser.com/a/892682">Remote SSH Commands - bash bind warning: line editing not enabled</a>.</p> <p>So I added a simple <code>if [ -t 1 ]</code> around <code>bind</code> statements to avoid running commands that presume the session is interactive when it isn't.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">if</span> [ -t 1 ]; <span style="color:#00f">then</span> </span></span><span style="display:flex;"><span> bind <span style="color:#a31515">&#34;TAB:menu-complete&#34;</span> </span></span><span style="display:flex;"><span> bind <span style="color:#a31515">&#34;set show-all-if-ambiguous on&#34;</span> </span></span><span style="display:flex;"><span> bind <span style="color:#a31515">&#34;set completion-ignore-case on&#34;</span> </span></span><span style="display:flex;"><span> bind <span style="color:#a31515">&#34;set menu-complete-display-prefix on&#34;</span> </span></span><span style="display:flex;"><span> bind <span style="color:#a31515">&#39;&#34;\e[Z&#34;:menu-complete-backward&#39;</span> </span></span><span style="display:flex;"><span><span style="color:#00f">fi</span> </span></span></code></pre><p>After logging out and back in the problem was gone.</p> Getting started with MicroPython and ESP8266 https://mitjafelicijan.com/esp8266-and-micropython-guide.html Sun, 06 Sep 2020 12:00:00 +0200 https://mitjafelicijan.com/esp8266-and-micropython-guide.html IntroductionA while ago I bought someESP8266 andESP32 dev boards to playaround with and I finally found a project to try it out. <h2 id="introduction">Introduction</h2> <p>A while ago I bought some <a href="https://www.espressif.com/en/products/socs/esp8266">ESP8266</a> and <a href="https://www.espressif.com/en/products/socs/esp32">ESP32</a> dev boards to play around with and I finally found a project to try it out.</p> <p>For my project, I used <a href="https://www.espressif.com/en/products/socs/esp32">ESP32</a> but I could easily choose <a href="https://www.espressif.com/en/products/socs/esp8266">ESP8266</a>. This guide contains which tools I use and how I prepared my workspace to code for <a href="https://www.espressif.com/en/products/socs/esp8266">ESP8266</a>.</p> <figure> <img src="/posts/esp8366-micropython/boards.jpg" alt="ESP8266 and ESP32 boards" /> </figure> <p>This guide covers:</p> <ul> <li>flashing SOC</li> <li>install proper tooling</li> <li>deploying a simple script</li> </ul> <blockquote> <p>Make sure that you are using <strong>a good USB cable</strong>. I had some problems with mine and once I replaced it everything started to work.</p> </blockquote> <h2 id="flashing-the-soc">Flashing the SOC</h2> <p>Plug your ESP8266 to USB port and check if the device was recognized with executing <code>dmesg | grep ch341-uart</code>.</p> <p>Then check if the device is available under <code>/dev/</code> by running <code>ls /dev/ttyUSB*</code>.</p> <blockquote> <p><strong>Linux users</strong>: if a device is not available be sure you are in <code>dialout</code> group. You can check this by executing <code>groups $USER</code>. You can add a user to <code>dialout</code> group with <code>sudo adduser $USER dialout</code>.</p> </blockquote> <p>After these conditions are meet go to the navigate to <a href="https://micropython.org/download/esp8266/">https://micropython.org/download/esp8266/</a> and download <code>esp8266-20200902-v1.13.bin</code>.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>mkdir esp8266-test </span></span><span style="display:flex;"><span>cd esp8266-test </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>wget https://micropython.org/resources/firmware/esp8266-20200902-v1.13.bin </span></span></code></pre><p>After obtaining firmware we will need some tooling to flash the firmware to the board.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>sudo pip3 install esptool </span></span></code></pre><p>You can read more about <code>esptool</code> at <a href="https://github.com/espressif/esptool/">https://github.com/espressif/esptool/</a>.</p> <p>Before flashing the firmware we need to erase the flash on device. Substitute <code>USB0</code> with the device listed in output of <code>ls /dev/ttyUSB*</code>.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>esptool.py --port /dev/ttyUSB0 erase_flash </span></span></code></pre><p>If flash was successfully erased it is now time to flash the new firmware to it.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect 0 esp8266-20200902-v1.13.bin </span></span></code></pre><p>If everything went ok you can try accessing MicroPython REPL with <code> screen /dev/ttyUSB0 115200</code> or <code>picocom /dev/ttyUSB0 -b115200</code>.</p> <blockquote> <p>Sometimes you will need to press <code>ENTER</code> in <code>screen</code> or <code>picocom</code> to access REPL.</p> </blockquote> <p>When you are in REPL you can test if all is working properly following steps.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>&gt; <span style="color:#00f">import</span> machine </span></span><span style="display:flex;"><span>&gt; machine.freq() </span></span></code></pre><p>This should output a number representing a frequency of the CPU (mine was <code>80000000</code>).</p> <p>When you are in <code>screen</code> or <code>picocom</code> these can help you a bit.</p> <table> <thead> <tr> <th>Key</th> <th>Command</th> </tr> </thead> <tbody> <tr> <td>CTRL+d</td> <td>preforms soft reboot</td> </tr> <tr> <td>CTRL+a x</td> <td>exits picocom</td> </tr> <tr> <td>CTRL+a \</td> <td>exits screen</td> </tr> </tbody> </table> <h2 id="install-better-tooling">Install better tooling</h2> <p>Now, to make our lives a little bit easier there are couple of additional tools that will make this whole experience a little more bearable.</p> <p>There are twq cool ways of uploading local files to SOC flash.</p> <ul> <li>ampy → <a href="https://github.com/scientifichackers/ampy">https://github.com/scientifichackers/ampy</a></li> <li>rshell → <a href="https://github.com/dhylands/rshell">https://github.com/dhylands/rshell</a></li> </ul> <h3 id="ampy">ampy</h3> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># installing ampy</span> </span></span><span style="display:flex;"><span>sudo pip3 install adafruit-ampy </span></span></code></pre><p>Listed below are some common commands I used.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># uploads file to flash</span> </span></span><span style="display:flex;"><span>ampy --delay 2 --port /dev/ttyUSB0 put boot.py </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># lists file on flash</span> </span></span><span style="display:flex;"><span>ampy --delay 2 --port /dev/ttyUSB0 ls </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># outputs contents of file on flash</span> </span></span><span style="display:flex;"><span>ampy --delay 2 --port /dev/ttyUSB0 cat boot.py </span></span></code></pre><blockquote> <p>I added <code>delay</code> of 2 seconds because I had problems with executing commands.</p> </blockquote> <h3 id="rshell">rshell</h3> <p>Even though <code>ampy</code> is a cool tool I opted with <code>rshell</code> in the end since it's much more polished and feature rich.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># installing ampy</span> </span></span><span style="display:flex;"><span>sudo pip3 install rshell </span></span></code></pre><p>Now that <code>rshell</code> is installed we can connect to the board.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>rshell --buffer-size=30 -p /dev/ttyUSB0 -a </span></span></code></pre><p>This will open a shell inside bash and from here you can execute multiple commands. You can check what is supported with <code>help</code> once you are inside of a shell.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>m@turing ~/Junk/esp8266-test </span></span><span style="display:flex;"><span>$ rshell --buffer-size=30 -p /dev/ttyUSB0 -a </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>Using buffer-size of 30 </span></span><span style="display:flex;"><span>Connecting to /dev/ttyUSB0 (buffer-size 30)... </span></span><span style="display:flex;"><span>Trying to connect to REPL connected </span></span><span style="display:flex;"><span>Testing <span style="color:#00f">if</span> ubinascii.unhexlify exists ... Y </span></span><span style="display:flex;"><span>Retrieving root directories ... /boot.py/ </span></span><span style="display:flex;"><span>Setting time ... Sep 06, 2020 23:54:28 </span></span><span style="display:flex;"><span>Evaluating board_name ... pyboard </span></span><span style="display:flex;"><span>Retrieving time epoch ... Jan 01, 2000 </span></span><span style="display:flex;"><span>Welcome to rshell. Use Control-D (or the exit command) to exit rshell. </span></span><span style="display:flex;"><span>/home/m/Junk/esp8266-test&gt; help </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>Documented commands (type help &lt;topic&gt;): </span></span><span style="display:flex;"><span>======================================== </span></span><span style="display:flex;"><span>args cat connect date edit filesize help mkdir rm shell </span></span><span style="display:flex;"><span>boards cd cp echo exit filetype ls repl rsync </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>Use Control-D (or the exit command) to exit rshell. </span></span></code></pre><blockquote> <p>Inside a shell <code>ls</code> will display list of files on your machine. To get list of files on flash folder <code>/pyboard</code> is remapped inside the shell. To list files on flash you must perform <code>ls /pyboard</code>.</p> </blockquote> <h4 id="moving-files-to-flash">Moving files to flash</h4> <p>To avoid copying files all the time I used <code>rsync</code> function from the inside of <code>rshell</code>.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>rsync . /pyboard </span></span></code></pre><h4 id="executing-scripts">Executing scripts</h4> <p>It is a pain to continuously reboot the device to trigger <code>/pyboard/boot.py</code> and there is a better way of testing local scripts on remote device.</p> <p>Lets assume we have <code>src/freq.py</code> file that displays CPU frequency of a remote device.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># src/freq.py</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> machine </span></span><span style="display:flex;"><span>print(machine.freq()) </span></span></code></pre><p>Now lets upload this and execute it.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># syncs files to remove device</span> </span></span><span style="display:flex;"><span>rsync ./src /pyboard </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># goes into REPL</span> </span></span><span style="display:flex;"><span>repl </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># we import file by importing it without .py extension and this will run the script</span> </span></span><span style="display:flex;"><span>&gt; import freq </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># CTRL+x will exit REPL</span> </span></span></code></pre><h2 id="additional-resources">Additional resources</h2> <ul> <li><a href="https://randomnerdtutorials.com/getting-started-micropython-esp32-esp8266/">https://randomnerdtutorials.com/getting-started-micropython-esp32-esp8266/</a></li> <li><a href="http://docs.micropython.org/en/latest/esp8266/quickref.html">http://docs.micropython.org/en/latest/esp8266/quickref.html</a></li> </ul> Disable mouse wake from suspend with systemd service https://mitjafelicijan.com/disable-mouse-wake-from-suspend-with-systemd-service.html Sat, 15 Aug 2020 12:00:00 +0200 https://mitjafelicijan.com/disable-mouse-wake-from-suspend-with-systemd-service.html I recently bought ThinkPadX220 just as ajoke on eBay to test Linux distributions and play around with things and notdestroy my main machine. <p>I recently bought <a href="https://www.laptopmag.com/reviews/laptops/lenovo-thinkpad-x220">ThinkPad X220</a> just as a joke on eBay to test Linux distributions and play around with things and not destroy my main machine. Little to my knowledge I felt in love with it. Man, they really made awesome machines back then.</p> <p>After changing disk that came with it to SSD and installing Ubuntu to test if  everything works I noticed that even after a single touch of my external mouse the system would wake up from sleep even though the lid was shut down.</p> <p>I wouldn't even noticed it if laptop didn't have <a href="https://support.lenovo.com/lk/en/solutions/~/media/Images/ContentImages/p/pd025386_x1_status_03.ashx?w=426&amp;h=262">LED sleep indicator</a>. I already had a bad experience with Linux and it's power management. I had a <a href="https://www.pcmag.com/reviews/dell-inspiron-15-7537">Dell Inspiron 7537</a> laptop with a touchscreen and while traveling it decided to wake up and started cooking in my backpack to the point that the digitizer responsible for touch actually glue off and the whole screen got wrecked. So, I am a bit touchy about this.</p> <p>I went on solution hunting and to my surprise there is no easy way to disable specific devices to perform wake up. Why is this not under the power management  tab in setting is really strange.</p> <p>After googling for a solution I found <a href="https://codetrips.com/2020/03/18/ubuntu-disable-mouse-wake-from-suspend/">this nice article describing the solution</a> that worked for me. The only problem with this solution was that he added his solution to <code>.bashrc</code> and this triggers <code>sudo</code> that asks for a password each time new terminal is opened, which get annoying quickly since I open a lot of terminals all the time.</p> <p>I followed his instructions and got to solution <code>sudo sh -c &quot;echo 'disabled' &gt; /sys/bus/usb/devices/2-1.1/power/wakeup&quot;</code>.</p> <p>I created a system service file <code>sudo nano /etc/systemd/system/disable-mouse-wakeup.service</code> and removed <code>sudo</code> and replaced <code>sh</code> with <code>/usr/bin/sh</code> and pasted all that in <code>ExecStart</code>.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">[Unit]</span> </span></span><span style="display:flex;"><span>Description=<span style="color:#a31515">Disables wakeup on mouse event</span> </span></span><span style="display:flex;"><span>After=<span style="color:#a31515">network.target</span> </span></span><span style="display:flex;"><span>StartLimitIntervalSec=<span style="color:#a31515">0</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">[Service]</span> </span></span><span style="display:flex;"><span>Type=<span style="color:#a31515">simple</span> </span></span><span style="display:flex;"><span>Restart=<span style="color:#a31515">always</span> </span></span><span style="display:flex;"><span>RestartSec=<span style="color:#a31515">1</span> </span></span><span style="display:flex;"><span>User=<span style="color:#a31515">root</span> </span></span><span style="display:flex;"><span>ExecStart=<span style="color:#a31515">/usr/bin/sh -c &#34;echo &#39;disabled&#39; &gt; /sys/bus/usb/devices/2-1.1/power/wakeup&#34;</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">[Install]</span> </span></span><span style="display:flex;"><span>WantedBy=<span style="color:#a31515">multi-user.target</span> </span></span></code></pre><p>After that I enabled, started and checked status of service.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>sudo systemctl enable disable-mouse-wakeup.service </span></span><span style="display:flex;"><span>sudo systemctl start disable-mouse-wakeup.service </span></span><span style="display:flex;"><span>sudo systemctl status disable-mouse-wakeup.service </span></span></code></pre><p>This will permanently disable that device from wakeing up you computer on boot. If you have many devices you would like to surpress from waking up your machine I would create a shell script and call that instead of direclty doing it in service file.</p> Remote work and how it affects the daily lives of people https://mitjafelicijan.com/remote-work.html Tue, 05 May 2020 12:00:00 +0200 https://mitjafelicijan.com/remote-work.html I have been working remotely for the past 5 years. <p>I have been working remotely for the past 5 years. I love it. Love the freedom and make your schedule thingy.</p> <h2 id="you-work-more-not-less">You work more not less</h2> <p>I've heard from people things like: &quot;Oh, you are so lucky, working from home, having all the free time you want&quot;. It was obvious they had no clue what means working remotely. They had this romantic idea of remote work. You can watch TV whenever you like, you can go outside for a picnic if you want and stuff like that.</p> <p>This may be true if you work a day or two in a week from home. But if you go completely remote all these changes completely. I take some time to acclimate but then you start feeling the consequences of going fully remote. And it's not all rainbows and unicorns. Rather the opposite.</p> <h2 id="feeling-lost">Feeling lost</h2> <p>At first, I remembered I felt lost. I was not used to this kind of environment. It felt disoriented and a part of you that is used to procrastinate turns on. You start thinking of a workday as a whole day. And soon this idea of &quot;I can do this later&quot; starts creeping in. Well, I have the whole day ahead of me. I can do this a bit later.</p> <h2 id="hyper-performance">Hyper-performance</h2> <p>As a direct result, you become more focused on your work since you don't have all the interruptions common in the workplace. And you can quickly get used to this hyper-performance. But this mode requires also a lot of peace and quiet.</p> <p>And here we come to the ugly parts of all this. <strong>People rarely have the self-control</strong> to not waste other people's time. It is paralyzing when people start calling you, sending you chat messages, etc. The thing is, that when I achieve this hyper-performance mode I am completely embroiled in the problem I am solving and this kind of interruptions mess with your head. I need an hour at least to get back in the zone. Sometimes not achieving the same focus the whole day.</p> <p>I know that life is not how you want it to be and takes its route but from what I've learned this kind of interruptions can be avoided in 90% of the case easily just by closing any chat programs and putting your phone in a drawer.</p> <h2 id="suggestion-to-all-the-new-remote-workers">Suggestion to all the new remote workers</h2> <ul> <li>Stop wasting other people's time. You don't bother people at their desks in the office either.</li> <li>Do not replace daily chats in the hallways with instant messaging software. It will only interrupt people. Nothing good will come of it.</li> <li>Set your working hours and try to not allow it to bleed outside these boundaries and maintain your routine.</li> <li>Be prepared that hours will be longer regardless of your good intentions and your well thought of routine.</li> <li>Try to be hyper-focused and do only one thing at the time. Multitasking is the enemy of progress.</li> <li>Avoid long meetings and if possible eliminate them. Rather take time to write them out and allow others to respond in their own time. Meetings are usually a large waste of time and most of the people attending them are there just because the manager said so.</li> <li>The software will not solve your problems. And throwing money at problems neither.</li> <li>If you are in a managerial position don't supervise any single minute of workers. They are probably giving you more hours anyways. Track progress weekly not daily. You hired them and give them the benefit of the doubt that they will deliver what you agreed upon.</li> </ul> My love and hate relationship with Node.js https://mitjafelicijan.com/my-love-and-hate-relationship-with-nodejs.html Mon, 30 Mar 2020 12:00:00 +0200 https://mitjafelicijan.com/my-love-and-hate-relationship-with-nodejs.html Previous project I was working on was being coded inGolang. <p>Previous project I was working on was being coded in <a href="https://golang.org/">Golang</a>. Also was my first project using it. And damn, that was an awesome experience. The whole thing is just superb. From how errors are handled. The C-like way you handle compiling. The way the language is structured making it incredibly versatile and easy to learn.</p> <p>It may cause some pain for somebody that is not used of using interfaces to map JSON and doing the recompilation all the time. But we have tools like <a href="http://eradman.com/entrproject/">entr</a> and <a href="https://www.gnu.org/software/make/">make</a> to fix that.</p> <p>But we are not here to talk about my undying love for <strong>Golang</strong>. Only in some way we probably should. It is an excellent example of how modern language should be designed. And because I have used it extensively in the last couple of years this probably taints my views of other languages. And is doing me a great disservice. Nevertheless, here we are.</p> <p>About two years ago I started flirting with <a href="https://nodejs.org/en/">Node.js</a> for a project I started working on. What I wanted was to have things written in a language that is widely used, and we could get additional developers for. As much as <strong>Golang</strong> is amazing it's really hard to get developers for it. Even now. And after playing around with it for a week I felt in love with the speed of iteration and massive package ecosystem. Do you want SSO? You got it! Do you want some esoteric library for something? There is a strong chance somebody wrote it. It is so extensive that you find yourself evaluating packages based on <strong>GitHub stars</strong> and number of contributors. You get swallowed by the vanity metrics and that potentially will become the downfall of Node.js.</p> <p>Because of the sheer amount of choice I often got anxiety when choosing libraries. Will I choose the correct one? Is this library something that will be supported for a foreseeable future or not? I am used of using libraries that are being in development for 10 years plus (Python, C) and that gave me some sort of comfort. And it is probably unfair to Node.js and community to expect same dedication.</p> <p>Moving forward ... Work started and things were great. <strong>Speed of iteration was insane</strong>. For some feature that I would need a day in Golang only took me hour or two. I became lazy! Using packages all over the place. Falling into the same trap as others. Packages on top of packages. And <a href="https://www.npmjs.com/">npm</a> didn't help at all. The way that the package manager works is just horrendous. And not allowing to have node_modules outside the project is also the stupidest idea ever.</p> <p>So at that point I started feeling the technical debt that comes with Node.js and the whole ecosystem. What nobody tells you is that <strong>structuring large Node.js apps</strong> is more problematic than one would think. And going microservice for every single thing is also a bad idea. The amount of networking you introduce with that approach always ends up being a pain in the ass. And I don't even want to go into system administration here. The overhead is insane. Package-lock.json made many days feel like living hell for me. And I would eat the cost of all this if it meant for better development experience. Well, it didn't.</p> <p>The <strong>lack of Typescript</strong> support in the interpreter is still mind boggling to me. Why haven't they added native support yet for this is beyond me?! That would have solved so many problems. Lack of type safety became a problem somewhere in the middle of the project where the codebase was sufficiently large enough to present problems. We started adding arguments to functions and there was <strong>no way to implicitly define argument types</strong>. And because at that point there were a lot of functions, it became impossible to know what each one accepts, development became more and more trial and error based.</p> <p>I tried <strong>implementing Typescript</strong>, but that would present a large refactor that we were not willing to do at that point. The benefits were not enough. I also tried <a href="https://flow.org/">Flow - static type checker</a> but implementation was also horrible. What Typescript and Flow forces you is to have src folder and then <strong>transpile</strong> your code into dist folder and run it with node. WTH is that all about. Why can't this be done in memory or some virtual file system? Why? I see no reason why this couldn't be done like this. But it is what it is. I abandoned all hope for static type checking.</p> <p>One of the problems that resulted from not having interfaces or types was inability to model out our data from <strong>Elasticsearch</strong>. I could have done a <strong>pedestrian implementation</strong> of it, but there must be a better way of doing this without resorting to some hack basically. Or maybe I haven't found a solution, which is also a possibility. I have looked, though. No juice!</p> <p><strong>Error handling?</strong> Is that a joke?</p> <p>Thank god for <strong>await/async</strong>. Without it, I would have probably just abandoned the whole thing and went with something else like Python. That's all I am going to say about this :)</p> <p>I started asking myself a question if Node.js is actually ready to be used in a <strong>large scale applications</strong>? And this was a totally wrong question. What I should have been asking myself was, how to use Node.js in large scale application. And you don't get this in <strong>marketing material</strong> for Express or Koa etc. They never tell you this. Making Node.js scale on infrastructure or in codebase is really <strong>more of an art than a science</strong>. And just like with the whole JavaScript ecosystem:</p> <ul> <li>impossible to master,</li> <li>half of your time you work on your tooling,</li> <li>just accept transpilers that convert one code into another (holly smokes),</li> <li>error handling is a joke,</li> <li>standards? What standards?</li> </ul> <p>But on the other hand. As I did, you will also learn to love it. Learn to use it quickly and do impossible things in crazy limited time.</p> <p>I hate to admit it. But I love Node.js. Dammit, I love it :)</p> <p>2023 Update: I hate Node.js!</p> The strange case of Elasticsearch allocation failure https://mitjafelicijan.com/the-strange-case-of-elasticsearch-allocation-failure.html Sun, 29 Mar 2020 12:00:00 +0200 https://mitjafelicijan.com/the-strange-case-of-elasticsearch-allocation-failure.html I&#39;ve been using Elasticsearch in production for 5 years now and never had asingle problem with it. <p>I've been using Elasticsearch in production for 5 years now and never had a single problem with it. Hell, never even known there could be a problem. Just worked. All this time. The first node that I deployed is still being used in production, never updated, upgraded, touched in anyway.</p> <p>All this bliss came to an abrupt end this Friday when I got notification that Elasticsearch cluster went warm. Well, warm is not that bad right? Wrong! Quickly after that I got another email which sent chills down my spine. Cluster is now red. RED! Now, shit really hit the fan!</p> <p>I tried googling what could be the problem and after executing allocation function noticed that some shards were unassigned and 5 attempts were already made (which is BTW to my luck the maximum) and that meant I am basically fucked. They also applied that one should wait for cluster to re-balance itself. So, I waited. One hour, two hours, several hours. Nothing, still RED.</p> <p>The strangest thing about it all was, that queries were still being fulfilled. Data was coming out. On the outside it looked like nothing was wrong but everybody that would look at the cluster would know immediately that something was very very wrong and we were living on borrowed time here.</p> <blockquote> <p><strong>Please, DO NOT do what I did.</strong> Seriously! Please ask someone on official forums or if you know an expert please consult him. There could be million of reasons and these solution fit my problem. Maybe in your case it would disastrous. I had all the data backed up and even if I would fail spectacularly I would be able to restore the data. It would be a huge pain and I would loose couple of days but I had a plan B.</p> </blockquote> <p>Executing allocation and told me what the problem was but no clear solution yet.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>GET /_cat/allocation?format=json </span></span></code></pre><p>I got a message that <code>ALLOCATION_FAILED</code> with additional info <code>failed to create shard, failure ioexception[failed to obtain in-memory shard lock]</code>. Well splendid! I must also say that our cluster is capable more than enough to handle the traffic. Also JVM memory pressure never was an issue. So what happened really then?</p> <p>I tried also re-routing failed ones with no success due to AWS restrictions on having managed Elasticsearch cluster (they lock some of the functions).</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>POST /_cluster/reroute?retry_failed=true </span></span></code></pre><p>I got a message that significantly reduced my options.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>{ </span></span><span style="display:flex;"><span> &#34;Message&#34;: <span style="color:#a31515">&#34;Your request: &#39;/_cluster/reroute&#39; is not allowed.&#34;</span> </span></span><span style="display:flex;"><span>} </span></span></code></pre><p>After that I went on a hunt again. I won't bother you with all the details because hours/days went by until I was finally able to re-index the problematic index and hoped for the best. Until that moment even re-indexing was giving me errors.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>POST _reindex </span></span><span style="display:flex;"><span>{ </span></span><span style="display:flex;"><span> &#34;source&#34;: { </span></span><span style="display:flex;"><span> &#34;index&#34;: <span style="color:#a31515">&#34;myindex&#34;</span> </span></span><span style="display:flex;"><span> }, </span></span><span style="display:flex;"><span> &#34;dest&#34;: { </span></span><span style="display:flex;"><span> &#34;index&#34;: <span style="color:#a31515">&#34;myindex-new&#34;</span> </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span>} </span></span></code></pre><p>I needed to do this multiple times to get all the documents re-indexed. Then I dropped the original one with the following command.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>DELETE /myindex </span></span></code></pre><p>And re-indexed again new one in the original one (well by name only).</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>POST _reindex </span></span><span style="display:flex;"><span>{ </span></span><span style="display:flex;"><span> &#34;source&#34;: { </span></span><span style="display:flex;"><span> &#34;index&#34;: <span style="color:#a31515">&#34;myindex-new&#34;</span> </span></span><span style="display:flex;"><span> }, </span></span><span style="display:flex;"><span> &#34;dest&#34;: { </span></span><span style="display:flex;"><span> &#34;index&#34;: <span style="color:#a31515">&#34;myindex&#34;</span> </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span>} </span></span></code></pre><p>On the surface it looks like all is working but I have a long road in front of me to get all the things working again. Cluster now shows that it is in Green mode but I am also getting a notification that the cluster has processing status which could mean million of things.</p> <p>Godspeed!</p> Create placeholder images with sharp Node.js image processing library https://mitjafelicijan.com/create-placeholder-images-with-sharp.html Fri, 27 Mar 2020 12:00:00 +0200 https://mitjafelicijan.com/create-placeholder-images-with-sharp.html I have been searching for a solution to pre-generate some placeholder images forimage server I needed to develop that resizes images on S3. <p>I have been searching for a solution to pre-generate some placeholder images for image server I needed to develop that resizes images on S3. I though this would be a 15min job and quickly found out how very mistaken I was.</p> <p>Even though Node.js is not really the best way to do this kind of things (surely something written in C or Rust or even Golang would be the correct way to do this but we didn't need the speed in our case) I found an excellent library <a href="https://github.com/lovell/sharp">sharp - High performance Node.js image processing</a>.</p> <p>Getting things running was a breeze.</p> <h2 id="fetch-image-from-s3-and-save-resized">Fetch image from S3 and save resized</h2> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">const</span> sharp = require(<span style="color:#a31515">&#39;sharp&#39;</span>); </span></span><span style="display:flex;"><span><span style="color:#00f">const</span> aws = require(<span style="color:#a31515">&#39;aws-sdk&#39;</span>); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">const</span> x,y = 100; </span></span><span style="display:flex;"><span><span style="color:#00f">const</span> s3 = <span style="color:#00f">new</span> aws.S3({}); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>aws.config.update({ </span></span><span style="display:flex;"><span> secretAccessKey: <span style="color:#a31515">&#39;secretAccessKey&#39;</span>, </span></span><span style="display:flex;"><span> accessKeyId: <span style="color:#a31515">&#39;accessKeyId&#39;</span>, </span></span><span style="display:flex;"><span> region: <span style="color:#a31515">&#39;region&#39;</span> </span></span><span style="display:flex;"><span>}); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">const</span> originalImage = <span style="color:#00f">await</span> s3.getObject({ </span></span><span style="display:flex;"><span> Bucket: <span style="color:#a31515">&#39;some-bucket-name&#39;</span>, </span></span><span style="display:flex;"><span> Key: <span style="color:#a31515">&#39;image.jpg&#39;</span>, </span></span><span style="display:flex;"><span>}).promise(); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">const</span> resizedImage = <span style="color:#00f">await</span> sharp(originalImage.Body) </span></span><span style="display:flex;"><span> .resize(x, y) </span></span><span style="display:flex;"><span> .jpeg({ progressive: <span style="color:#00f">true</span> }) </span></span><span style="display:flex;"><span> .toBuffer(); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>s3.putObject({ </span></span><span style="display:flex;"><span> Bucket: <span style="color:#a31515">&#39;some-bucket-name&#39;</span>, </span></span><span style="display:flex;"><span> Key: <span style="color:#a31515">`optimized/</span><span style="color:#a31515">${</span>x<span style="color:#a31515">}</span><span style="color:#a31515">x</span><span style="color:#a31515">${</span>y<span style="color:#a31515">}</span><span style="color:#a31515">/image.jpg`</span>, </span></span><span style="display:flex;"><span> Body: resizedImage, </span></span><span style="display:flex;"><span> ContentType: <span style="color:#a31515">&#39;image/jpeg&#39;</span>, </span></span><span style="display:flex;"><span> ACL: <span style="color:#a31515">&#39;public-read&#39;</span> </span></span><span style="display:flex;"><span>}).promise(); </span></span></code></pre><p>All this code was wrapped inside a web service with some additional security checks and defensive coding to detect if key is missing on S3.</p> <p>And at that point I needed to return placeholder images as a response in case key is missing or x,y are not allowed by the server etc. I could have created PNG in Gimp and just serve them but I wanted to respect aspect ratio and I didn't want to return some mangled images.</p> <blockquote> <p>Main problem with finding a clean solution I could copy and paste and change a bit was a task. API is changing constantly and there weren't clear examples or I was unable to find them.</p> </blockquote> <h2 id="generating-placeholder-images-using-svg">Generating placeholder images using SVG</h2> <p>What I ended up was using SVG to generate text and created image with sharp and used composition to combine both layers. Response returned by this function is a buffer you can use to either upload to S3 or save to local file.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">const</span> generatePlaceholderImageWithText = <span style="color:#00f">async</span> (width, height, message) =&gt; { </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> overlay = <span style="color:#a31515">`&lt;svg width=&#34;</span><span style="color:#a31515">${</span>width - 20<span style="color:#a31515">}</span><span style="color:#a31515">&#34; height=&#34;</span><span style="color:#a31515">${</span>height - 20<span style="color:#a31515">}</span><span style="color:#a31515">&#34;&gt; </span></span></span><span style="display:flex;"><span><span style="color:#a31515"> &lt;text x=&#34;50%&#34; y=&#34;50%&#34; font-family=&#34;sans-serif&#34; font-size=&#34;16&#34; text-anchor=&#34;middle&#34;&gt;</span><span style="color:#a31515">${</span>message<span style="color:#a31515">}</span><span style="color:#a31515">&lt;/text&gt; </span></span></span><span style="display:flex;"><span><span style="color:#a31515"> &lt;/svg&gt;`</span>; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">return</span> <span style="color:#00f">await</span> sharp({ </span></span><span style="display:flex;"><span> create: { </span></span><span style="display:flex;"><span> width: width, </span></span><span style="display:flex;"><span> height: height, </span></span><span style="display:flex;"><span> channels: 4, </span></span><span style="display:flex;"><span> background: { r: 230, g: 230, b: 230, alpha: 1 } </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> }) </span></span><span style="display:flex;"><span> .composite([{ </span></span><span style="display:flex;"><span> input: Buffer.from(overlay), </span></span><span style="display:flex;"><span> gravity: <span style="color:#a31515">&#39;center&#39;</span>, </span></span><span style="display:flex;"><span> }]) </span></span><span style="display:flex;"><span> .jpeg() </span></span><span style="display:flex;"><span> .toBuffer(); </span></span><span style="display:flex;"><span>} </span></span></code></pre><p>That is about it. Nothing more to it. You can change the color of the image by changing <code>background</code> and if you want to change text styling you can adapt SVG to your needs.</p> <blockquote> <p>Also be careful about the length of the text. This function positions text at the center and adds <code>20px</code> padding on all sides. If text is longer than the image it will get cut.</p> </blockquote> Simple Server-Sent Events based PubSub Server https://mitjafelicijan.com/simple-server-sent-events-based-pubsub-server.html Sun, 22 Mar 2020 12:00:00 +0200 https://mitjafelicijan.com/simple-server-sent-events-based-pubsub-server.html Before we continue . <h2 id="before-we-continue-">Before we continue ...</h2> <p>Publisher Subscriber model is nothing new and there are many amazing solutions out there, so writing a new one would be a waste of time if other solutions wouldn't have quite complex install procedures and weren't so hard to maintain. But to be fair, comparing this simple server with something like <a href="https://kafka.apache.org/">Kafka</a> or <a href="https://www.rabbitmq.com/">RabbitMQ</a> is laughable at the least. Those solutions are enterprise grade and have many mechanisms there to ensure messages aren't lost and much more. Regardless of these drawbacks, this method has been tested on a large website and worked until now without any problems. So now, that we got that cleared up, let's continue.</p> <p><em><strong>Wiki definition:</strong> Publish/subscribe messaging, or pub/sub messaging, is a form of asynchronous service-to-service communication used in serverless and microservices architectures. In a pub/sub model, any message published to a topic is immediately received by all the subscribers to the topic.</em></p> <h2 id="general-goals">General goals</h2> <ul> <li>provide a simple server that relays messages to all the connected clients,</li> <li>messages can be posted on specific topics,</li> <li>messages get sent via <a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events">Server-Sent Events</a> to all the subscribers.</li> </ul> <h2 id="how-exactly-does-the-pubsub-model-work">How exactly does the pub/sub model work?</h2> <p>The easiest way to explain this is with diagram bellow. Basic function is simple. We have subscribers that receive messages, and we have publishers that create and post messages. Similar model is also well know pattern that works on a premise of consumers and producers, and they take similar roles.</p> <figure> <img src="/posts/simple-pubsub-server/pubsub-overview.png" alt="How PubSub works" /> </figure> <p><strong>These are some naive characteristics we want to achieve:</strong></p> <ul> <li>producer is publishing messages to subscribe topic,</li> <li>consumer is receiving messages from subscribed topic,</li> <li>servers is also known as Broker,</li> <li>broker does not store messages or tracks success,</li> <li>broker uses <a href="https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics)">FIFO</a> method for delivering messages,</li> <li>if consumer wants to receive messages from a topic, producer and consumer topics must match,</li> <li>consumer can subscribe to multiple topics,</li> <li>producer can publish to multiple topics,</li> <li>each message has a messageId.</li> </ul> <p><strong>Known drawbacks:</strong></p> <ul> <li>messages will not be stored in a persistent queue or unreceived messages like <a href="https://en.wikipedia.org/wiki/Dead_letter_queue">DeadLetterQueue</a> so old messages could be lost on server restart,</li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events">Server-Sent Events</a> opens a long-running connection between the client and the server so make sure if your setup is load balanced that the load balancer in this case can have long opened connection,</li> <li>no system moderation due to the dynamic nature of creating queues.</li> </ul> <h2 id="server-sent-events">Server-Sent Events</h2> <p>Read more about it on <a href="https://html.spec.whatwg.org/multipage/server-sent-events.html">official specification page</a>.</p> <h3 id="current-browser-support">Current browser support</h3> <figure> <img src="/posts/simple-pubsub-server/caniuse.png" alt="Browser support" /> </figure> <p>Check <a href="https://caniuse.com/#feat=eventsource">https://caniuse.com/#feat=eventsource</a> for latest information about browser support.</p> <h3 id="known-issues">Known issues</h3> <ul> <li>Firefox 52 and below do not support EventSource in web/shared workers</li> <li>In Firefox prior to version 36 server-sent events do not reconnect automatically in case of a connection interrupt (bug)</li> <li>Reportedly, CORS in EventSource is currently supported in Firefox 10+, Opera 12+, Chrome 26+, Safari 7.0+.</li> <li>Antivirus software may block the event streaming data chunks.</li> </ul> <p>Source: <a href="https://caniuse.com/#feat=eventsource">https://caniuse.com/#feat=eventsource</a></p> <h3 id="message-format">Message format</h3> <p>The simplest message that can be sent is only with data attribute:</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>data: this is a simple message </span></span><span style="display:flex;"><span>&lt;blank line&gt; </span></span></code></pre><p>You can send message IDs to be used if the connection is dropped:</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>id: 33 </span></span><span style="display:flex;"><span>data: this is line one </span></span><span style="display:flex;"><span>data: this is line two </span></span><span style="display:flex;"><span>&lt;blank line&gt; </span></span></code></pre><p>And you can specify your own event types (the above messages will all trigger the message event):</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>id: 36 </span></span><span style="display:flex;"><span>event: price </span></span><span style="display:flex;"><span>data: 103.34 </span></span><span style="display:flex;"><span>&lt;blank line&gt; </span></span></code></pre><h3 id="server-requirements">Server requirements</h3> <p>The important thing is how you send headers and which headers are sent by the server that triggers browser to threat response as a EventStream.</p> <p>Headers responsible for this are:</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>Content-Type: text/event-stream </span></span><span style="display:flex;"><span>Cache-Control: no-cache </span></span><span style="display:flex;"><span>Connection: keep-alive </span></span></code></pre><h3 id="debugging-with-google-chrome">Debugging with Google Chrome</h3> <p>Google Chrome provides build-in debugging and exploration tool for <a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events">Server-Sent Events</a> which is quite nice and available from Developer Tools under Network tab.</p> <blockquote> <p>You can debug only client side events that get received and not the server ones. For debugging server events add <code>console.log</code> to <code>server.js</code> code and print out events.</p> </blockquote> <figure> <img src="/posts/simple-pubsub-server/chrome-debugging.png" alt="Google Chrome Developer Tools EventStream" /> </figure> <h2 id="server-implementation">Server implementation</h2> <p>For the sake of this example we will use <a href="https://nodejs.org/en/">Node.js</a> with <a href="https://expressjs.com">Express</a> as our router since this is the easiest way to get started and we will use already written SSE library for node <a href="https://www.npmjs.com/package/sse-pubsub">sse-pubsub</a> so we don't reinvent the wheel.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>npm init --yes </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>npm install express </span></span><span style="display:flex;"><span>npm install body-parser </span></span><span style="display:flex;"><span>npm install sse-pubsub </span></span></code></pre><p>Basic implementation of a server (<code>server.js</code>):</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">const</span> express = require(<span style="color:#a31515">&#39;express&#39;</span>); </span></span><span style="display:flex;"><span><span style="color:#00f">const</span> bodyParser = require(<span style="color:#a31515">&#39;body-parser&#39;</span>); </span></span><span style="display:flex;"><span><span style="color:#00f">const</span> SSETopic = require(<span style="color:#a31515">&#39;sse-pubsub&#39;</span>); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">const</span> app = express(); </span></span><span style="display:flex;"><span><span style="color:#00f">const</span> port = process.env.PORT || 4000; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000">// topics container </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span><span style="color:#00f">const</span> sseTopics = {}; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>app.use(bodyParser.json()); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000">// open for all cors </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span>app.all(<span style="color:#a31515">&#39;*&#39;</span>, (req, res, next) =&gt; { </span></span><span style="display:flex;"><span> res.header(<span style="color:#a31515">&#39;Access-Control-Allow-Origin&#39;</span>, <span style="color:#a31515">&#39;*&#39;</span>); </span></span><span style="display:flex;"><span> res.header(<span style="color:#a31515">&#39;Access-Control-Allow-Headers&#39;</span>, <span style="color:#a31515">&#39;X-Requested-With, Content-Type&#39;</span>); </span></span><span style="display:flex;"><span> next(); </span></span><span style="display:flex;"><span>}); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000">// preflight request error fix </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span>app.options(<span style="color:#a31515">&#39;*&#39;</span>, <span style="color:#00f">async</span> (req, res) =&gt; { </span></span><span style="display:flex;"><span> res.header(<span style="color:#a31515">&#39;Access-Control-Allow-Origin&#39;</span>, <span style="color:#a31515">&#39;*&#39;</span>); </span></span><span style="display:flex;"><span> res.header(<span style="color:#a31515">&#39;Access-Control-Allow-Headers&#39;</span>, <span style="color:#a31515">&#39;X-Requested-With, Content-Type&#39;</span>); </span></span><span style="display:flex;"><span> res.send(<span style="color:#a31515">&#39;OK&#39;</span>); </span></span><span style="display:flex;"><span>}); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000">// serve the event streams </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span>app.get(<span style="color:#a31515">&#39;/stream/:topic&#39;</span>, <span style="color:#00f">async</span> (req, res, next) =&gt; { </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> topic = req.params.topic; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">if</span> (!(topic <span style="color:#00f">in</span> sseTopics)) { </span></span><span style="display:flex;"><span> sseTopics[topic] = <span style="color:#00f">new</span> SSETopic({ </span></span><span style="display:flex;"><span> pingInterval: 0, </span></span><span style="display:flex;"><span> maxStreamDuration: 15000, </span></span><span style="display:flex;"><span> }); </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">// subscribing client to topic </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> sseTopics[topic].subscribe(req, res); </span></span><span style="display:flex;"><span>}); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000">// accepts new messages into topic </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span>app.post(<span style="color:#a31515">&#39;/publish&#39;</span>, <span style="color:#00f">async</span> (req, res) =&gt; { </span></span><span style="display:flex;"><span> <span style="color:#00f">let</span> body = req.body; </span></span><span style="display:flex;"><span> <span style="color:#00f">let</span> status = 200; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> console.log(<span style="color:#a31515">&#39;Incoming message:&#39;</span>, req.body); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">if</span> ( </span></span><span style="display:flex;"><span> body.hasOwnProperty(<span style="color:#a31515">&#39;topic&#39;</span>) &amp;&amp; </span></span><span style="display:flex;"><span> body.hasOwnProperty(<span style="color:#a31515">&#39;event&#39;</span>) &amp;&amp; </span></span><span style="display:flex;"><span> body.hasOwnProperty(<span style="color:#a31515">&#39;message&#39;</span>) </span></span><span style="display:flex;"><span> ) { </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> topic = req.body.topic; </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> event = req.body.event; </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> message = req.body.message; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">if</span> (topic <span style="color:#00f">in</span> sseTopics) { </span></span><span style="display:flex;"><span> <span style="color:#008000">// sends message to all the subscribers </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> sseTopics[topic].publish(message, event); </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> } <span style="color:#00f">else</span> { </span></span><span style="display:flex;"><span> status = 400; </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> res.status(status).send({ </span></span><span style="display:flex;"><span> status, </span></span><span style="display:flex;"><span> }); </span></span><span style="display:flex;"><span>}); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000">// returns JSON object of all opened topics </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span>app.get(<span style="color:#a31515">&#39;/status&#39;</span>, <span style="color:#00f">async</span> (req, res) =&gt; { </span></span><span style="display:flex;"><span> res.send(sseTopics); </span></span><span style="display:flex;"><span>}); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000">// health-check endpoint </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span>app.get(<span style="color:#a31515">&#39;/&#39;</span>, <span style="color:#00f">async</span> (req, res) =&gt; { </span></span><span style="display:flex;"><span> res.send(<span style="color:#a31515">&#39;OK&#39;</span>); </span></span><span style="display:flex;"><span>}); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000">// return a 404 if no routes match </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span>app.use((req, res, next) =&gt; { </span></span><span style="display:flex;"><span> res.set(<span style="color:#a31515">&#39;Cache-Control&#39;</span>, <span style="color:#a31515">&#39;private, no-store&#39;</span>); </span></span><span style="display:flex;"><span> res.status(404).end(<span style="color:#a31515">&#39;Not found&#39;</span>); </span></span><span style="display:flex;"><span>}); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000">// starts the server </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span>app.listen(port, () =&gt; { </span></span><span style="display:flex;"><span> console.log(<span style="color:#a31515">`PubSub server running on http://localhost:</span><span style="color:#a31515">${</span>port<span style="color:#a31515">}</span><span style="color:#a31515">`</span>); </span></span><span style="display:flex;"><span>}); </span></span></code></pre><h3 id="our-custom-message-format">Our custom message format</h3> <p>Each message posted on a server must be in a specific format that out server accepts. Having structure like this allows us to have multiple separated type of events on each topic.</p> <p>With this we can separate streams and only receive events that belong to the topic.</p> <p>One example would be, that we have index page and we want to receive messages about new upvotes or new subscribers but we don't want to follow events for other pages. This reduces clutter and overall network. And structure is much nicer and maintanable.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>{ </span></span><span style="display:flex;"><span> &#34;topic&#34;: <span style="color:#a31515">&#34;sample-topic&#34;</span>, </span></span><span style="display:flex;"><span> &#34;event&#34;: <span style="color:#a31515">&#34;sample-event&#34;</span>, </span></span><span style="display:flex;"><span> &#34;message&#34;: { &#34;name&#34;: <span style="color:#a31515">&#34;John&#34;</span> } </span></span><span style="display:flex;"><span>} </span></span></code></pre><h2 id="publisher-and-subscriber-clients">Publisher and subscriber clients</h2> <h3 id="publisher-and-subscriber-in-action">Publisher and subscriber in action</h3> <p><video src="/posts/simple-pubsub-server/clients.m4v" controls></video></p> <p>You can download <a href="../simple-pubsub-server/sse-pubsub-server.zip">the code</a> and follow along.</p> <h3 id="publisher">Publisher</h3> <p>As talked about above publisher is the one that send messages to the broker/server. Message inside the payload can be whatever you want (string, object, array). I would however personally avoid send large chunks of data like blobs and such.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">&lt;!DOCTYPE html&gt;</span> </span></span><span style="display:flex;"><span>&lt;html lang=<span style="color:#a31515">&#34;en&#34;</span>&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;head&gt; </span></span><span style="display:flex;"><span> &lt;meta charset=<span style="color:#a31515">&#34;UTF-8&#34;</span>&gt; </span></span><span style="display:flex;"><span> &lt;meta name=<span style="color:#a31515">&#34;viewport&#34;</span> content=<span style="color:#a31515">&#34;width=device-width, initial-scale=1.0&#34;</span>&gt; </span></span><span style="display:flex;"><span> &lt;title&gt;Publisher&lt;/title&gt; </span></span><span style="display:flex;"><span> &lt;/head&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;body&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;h1&gt;Publisher&lt;/h1&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;fieldset&gt; </span></span><span style="display:flex;"><span> &lt;p&gt; </span></span><span style="display:flex;"><span> &lt;label&gt;Server:&lt;/label&gt; </span></span><span style="display:flex;"><span> &lt;input type=<span style="color:#a31515">&#34;text&#34;</span> id=<span style="color:#a31515">&#34;server&#34;</span> value=<span style="color:#a31515">&#34;http://localhost:4000&#34;</span>&gt; </span></span><span style="display:flex;"><span> &lt;/p&gt; </span></span><span style="display:flex;"><span> &lt;p&gt; </span></span><span style="display:flex;"><span> &lt;label&gt;Topic:&lt;/label&gt; </span></span><span style="display:flex;"><span> &lt;input type=<span style="color:#a31515">&#34;text&#34;</span> id=<span style="color:#a31515">&#34;topic&#34;</span> value=<span style="color:#a31515">&#34;sample-topic&#34;</span>&gt; </span></span><span style="display:flex;"><span> &lt;/p&gt; </span></span><span style="display:flex;"><span> &lt;p&gt; </span></span><span style="display:flex;"><span> &lt;label&gt;Event:&lt;/label&gt; </span></span><span style="display:flex;"><span> &lt;input type=<span style="color:#a31515">&#34;text&#34;</span> id=<span style="color:#a31515">&#34;event&#34;</span> value=<span style="color:#a31515">&#34;sample-event&#34;</span>&gt; </span></span><span style="display:flex;"><span> &lt;/p&gt; </span></span><span style="display:flex;"><span> &lt;p&gt; </span></span><span style="display:flex;"><span> &lt;label&gt;Message:&lt;/label&gt; </span></span><span style="display:flex;"><span> &lt;input type=<span style="color:#a31515">&#34;text&#34;</span> id=<span style="color:#a31515">&#34;message&#34;</span> value=<span style="color:#a31515">&#39;{&#34;name&#34;: &#34;John&#34;}&#39;</span>&gt; </span></span><span style="display:flex;"><span> &lt;/p&gt; </span></span><span style="display:flex;"><span> &lt;p&gt; </span></span><span style="display:flex;"><span> &lt;button type=<span style="color:#a31515">&#34;button&#34;</span> id=<span style="color:#a31515">&#34;button&#34;</span>&gt;Publish message to topic&lt;/button&gt; </span></span><span style="display:flex;"><span> &lt;/p&gt; </span></span><span style="display:flex;"><span> &lt;/fieldset&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;script&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> button = document.querySelector(<span style="color:#a31515">&#39;#button&#39;</span>); </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> server = document.querySelector(<span style="color:#a31515">&#39;#server&#39;</span>); </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> topic = document.querySelector(<span style="color:#a31515">&#39;#topic&#39;</span>); </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> event = document.querySelector(<span style="color:#a31515">&#39;#event&#39;</span>); </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> message = document.querySelector(<span style="color:#a31515">&#39;#message&#39;</span>); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> button.addEventListener(<span style="color:#a31515">&#39;click&#39;</span>, <span style="color:#00f">async</span> (evt) =&gt; { </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> req = <span style="color:#00f">await</span> fetch(<span style="color:#a31515">`</span><span style="color:#a31515">${</span>server.value<span style="color:#a31515">}</span><span style="color:#a31515">/publish`</span>, { </span></span><span style="display:flex;"><span> method: <span style="color:#a31515">&#39;post&#39;</span>, </span></span><span style="display:flex;"><span> headers: { </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;Accept&#39;</span>: <span style="color:#a31515">&#39;application/json&#39;</span>, </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;Content-Type&#39;</span>: <span style="color:#a31515">&#39;application/json&#39;</span>, </span></span><span style="display:flex;"><span> }, </span></span><span style="display:flex;"><span> body: JSON.stringify({ </span></span><span style="display:flex;"><span> topic: topic.value, </span></span><span style="display:flex;"><span> event: event.value, </span></span><span style="display:flex;"><span> message: JSON.parse(message.value), </span></span><span style="display:flex;"><span> }), </span></span><span style="display:flex;"><span> }); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> res = <span style="color:#00f">await</span> req.json(); </span></span><span style="display:flex;"><span> console.log(res); </span></span><span style="display:flex;"><span> }); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;/script&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;/body&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>&lt;/html&gt; </span></span></code></pre><h3 id="subscriber">Subscriber</h3> <p>Subscriber is responsible for receiving new messages that come from server via publisher. The code bellow is very rudimentary but works and follows the implementation guidelines for EventSource.</p> <p>You can use either Developer Tools Console to see incoming messages or you can defer to Debugging with Google Chrome section above to see all EventStream messages.</p> <blockquote> <p>Don't be alarmed if the subscriber gets disconnected from the server every so often. The code we have here resets connection every 15s but it automatically get reconnected and fetches all messages up to last received message id. This setting can be adjusted in <code>server.js</code> file; search for the <code>maxStreamDuration</code> variable.</p> </blockquote> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">&lt;!DOCTYPE html&gt;</span> </span></span><span style="display:flex;"><span>&lt;html lang=<span style="color:#a31515">&#34;en&#34;</span>&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;head&gt; </span></span><span style="display:flex;"><span> &lt;meta charset=<span style="color:#a31515">&#34;UTF-8&#34;</span>&gt; </span></span><span style="display:flex;"><span> &lt;meta name=<span style="color:#a31515">&#34;viewport&#34;</span> content=<span style="color:#a31515">&#34;width=device-width, initial-scale=1.0&#34;</span>&gt; </span></span><span style="display:flex;"><span> &lt;title&gt;Subscriber&lt;/title&gt; </span></span><span style="display:flex;"><span> &lt;link rel=<span style="color:#a31515">&#34;stylesheet&#34;</span> href=<span style="color:#a31515">&#34;style.css&#34;</span>&gt; </span></span><span style="display:flex;"><span> &lt;/head&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;body&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;h1&gt;Subscriber&lt;/h1&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;fieldset&gt; </span></span><span style="display:flex;"><span> &lt;p&gt; </span></span><span style="display:flex;"><span> &lt;label&gt;Server:&lt;/label&gt; </span></span><span style="display:flex;"><span> &lt;input type=<span style="color:#a31515">&#34;text&#34;</span> id=<span style="color:#a31515">&#34;server&#34;</span> value=<span style="color:#a31515">&#34;http://localhost:4000&#34;</span>&gt; </span></span><span style="display:flex;"><span> &lt;/p&gt; </span></span><span style="display:flex;"><span> &lt;p&gt; </span></span><span style="display:flex;"><span> &lt;label&gt;Topic:&lt;/label&gt; </span></span><span style="display:flex;"><span> &lt;input type=<span style="color:#a31515">&#34;text&#34;</span> id=<span style="color:#a31515">&#34;topic&#34;</span> value=<span style="color:#a31515">&#34;sample-topic&#34;</span>&gt; </span></span><span style="display:flex;"><span> &lt;/p&gt; </span></span><span style="display:flex;"><span> &lt;p&gt; </span></span><span style="display:flex;"><span> &lt;label&gt;Event:&lt;/label&gt; </span></span><span style="display:flex;"><span> &lt;input type=<span style="color:#a31515">&#34;text&#34;</span> id=<span style="color:#a31515">&#34;event&#34;</span> value=<span style="color:#a31515">&#34;sample-event&#34;</span>&gt; </span></span><span style="display:flex;"><span> &lt;/p&gt; </span></span><span style="display:flex;"><span> &lt;p&gt; </span></span><span style="display:flex;"><span> &lt;button type=<span style="color:#a31515">&#34;button&#34;</span> id=<span style="color:#a31515">&#34;button&#34;</span>&gt;Subscribe to topic&lt;/button&gt; </span></span><span style="display:flex;"><span> &lt;/p&gt; </span></span><span style="display:flex;"><span> &lt;/fieldset&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;script&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> button = document.querySelector(<span style="color:#a31515">&#39;#button&#39;</span>); </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> server = document.querySelector(<span style="color:#a31515">&#39;#server&#39;</span>); </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> topic = document.querySelector(<span style="color:#a31515">&#39;#topic&#39;</span>); </span></span><span style="display:flex;"><span> <span style="color:#00f">const</span> event = document.querySelector(<span style="color:#a31515">&#39;#event&#39;</span>); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> button.addEventListener(<span style="color:#a31515">&#39;click&#39;</span>, <span style="color:#00f">async</span> (evt) =&gt; { </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">let</span> es = <span style="color:#00f">new</span> EventSource(<span style="color:#a31515">`</span><span style="color:#a31515">${</span>server.value<span style="color:#a31515">}</span><span style="color:#a31515">/stream/</span><span style="color:#a31515">${</span>topic.value<span style="color:#a31515">}</span><span style="color:#a31515">`</span>); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> es.addEventListener(event.value, <span style="color:#00f">function</span> (evt) { </span></span><span style="display:flex;"><span> console.log(<span style="color:#a31515">`incoming message`</span>, JSON.parse(evt.data)); </span></span><span style="display:flex;"><span> }); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> es.addEventListener(<span style="color:#a31515">&#39;open&#39;</span>, <span style="color:#00f">function</span> (evt) { </span></span><span style="display:flex;"><span> console.log(<span style="color:#a31515">&#39;connected&#39;</span>, evt); </span></span><span style="display:flex;"><span> }); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> es.addEventListener(<span style="color:#a31515">&#39;error&#39;</span>, <span style="color:#00f">function</span> (evt) { </span></span><span style="display:flex;"><span> console.log(<span style="color:#a31515">&#39;error&#39;</span>, evt); </span></span><span style="display:flex;"><span> }); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> }); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;/script&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;/body&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>&lt;/html&gt; </span></span></code></pre><h2 id="reading-further">Reading further</h2> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events">Using server-sent events</a></li> <li><a href="https://www.smashingmagazine.com/2018/02/sse-websockets-data-flow-http2/">Using SSE Instead Of WebSockets For Unidirectional Data Flow Over HTTP/2</a></li> <li><a href="https://apifriends.com/api-streaming/server-sent-events/">What is Server-Sent Events?</a></li> <li><a href="https://tools.ietf.org/id/draft-xie-bidirectional-messaging-01.html">An HTTP/2 extension for bidirectional messaging communication</a></li> <li><a href="https://developers.google.com/web/fundamentals/performance/http2">Introduction to HTTP/2</a></li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">The WebSocket API (WebSockets)</a></li> </ul> Using sentiment analysis for clickbait detection in RSS feeds https://mitjafelicijan.com/using-sentiment-analysis-for-clickbait-detection-in-rss-feeds.html Sat, 19 Oct 2019 12:00:00 +0200 https://mitjafelicijan.com/using-sentiment-analysis-for-clickbait-detection-in-rss-feeds.html Initial thoughtsOne of the things that interested me for a while now is if major wellestablished news sites use click bait titles to drive additional traffic totheir sites and generate additional impressions. <h2 id="initial-thoughts">Initial thoughts</h2> <p>One of the things that interested me for a while now is if major well established news sites use click bait titles to drive additional traffic to their sites and generate additional impressions.</p> <p>Goal is to see how article titles and actual content of article differ from each other and see if titles are clickbaited.</p> <h2 id="preparing-and-cleaning-data">Preparing and cleaning data</h2> <p>For this example I opted to just use RSS feed from a new website and decided to go with <a href="https://www.theguardian.com">The Guardian</a> World news. While this gets us limited data (~40) articles and also description (actual content) is trimmed this really doesn't reflect the actual article contents.</p> <p>To get better content I could use web scraping and use RSS as link list and fetch contents directly from website, but for this simple example this will suffice.</p> <p>There are couple of requirements we need to install before we continue:</p> <ul> <li><code>pip3 install feedparser</code> (parses RSS feed from url)</li> <li><code>pip3 install vaderSentiment</code> (does sentiment polarity analysis)</li> <li><code>pip3 install matplotlib</code> (plots chart of results)</li> </ul> <p>So first we need to fetch RSS data and sanitize HTML content from description.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">import</span> re </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> feedparser </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>feed_url = <span style="color:#a31515">&#34;https://www.theguardian.com/world/rss&#34;</span> </span></span><span style="display:flex;"><span>feed = feedparser.parse(feed_url) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># sanitize html</span> </span></span><span style="display:flex;"><span><span style="color:#00f">for</span> item <span style="color:#00f">in</span> feed.entries: </span></span><span style="display:flex;"><span> item.description = re.sub(<span style="color:#a31515">&#39;&lt;[^&lt;]+?&gt;&#39;</span>, <span style="color:#a31515">&#39;&#39;</span>, item.description) </span></span></code></pre><h2 id="perform-sentiment-analysis">Perform sentiment analysis</h2> <p>Since we now have cleaned up data in our <code>feed.entries</code> object we can start with performing sentiment analysis.</p> <p>There are many sentiment analysis libraries available that range from rule-based sentiment analysis up to machine learning supported analysis. To keep things simple I decided to use rule-based analysis library <a href="https://github.com/cjhutto/vaderSentiment">vaderSentiment</a> from <a href="https://github.com/cjhutto">C.J. Hutto</a>. Really nice library and quite easy to use.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">from</span> vaderSentiment.vaderSentiment <span style="color:#00f">import</span> SentimentIntensityAnalyzer </span></span><span style="display:flex;"><span>analyser = SentimentIntensityAnalyzer() </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>sentiment_results = [] </span></span><span style="display:flex;"><span><span style="color:#00f">for</span> item <span style="color:#00f">in</span> feed.entries: </span></span><span style="display:flex;"><span> sentiment_title = analyser.polarity_scores(item.title) </span></span><span style="display:flex;"><span> sentiment_description = analyser.polarity_scores(item.description) </span></span><span style="display:flex;"><span> sentiment_results.append([sentiment_title[<span style="color:#a31515">&#39;compound&#39;</span>], sentiment_description[<span style="color:#a31515">&#39;compound&#39;</span>]]) </span></span></code></pre><p>Now that we have this data in a shape that is compatible with matplotlib we can plot results to see the difference between title and description sentiment of an article.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">import</span> matplotlib.pyplot <span style="color:#00f">as</span> plt </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>plt.rcParams[<span style="color:#a31515">&#39;figure.figsize&#39;</span>] = (15, 3) </span></span><span style="display:flex;"><span>plt.plot(sentiment_results, drawstyle=<span style="color:#a31515">&#39;steps&#39;</span>) </span></span><span style="display:flex;"><span>plt.title(<span style="color:#a31515">&#39;Sentiment analysis relationship between title and description (Guardian World News)&#39;</span>) </span></span><span style="display:flex;"><span>plt.legend([<span style="color:#a31515">&#39;title&#39;</span>, <span style="color:#a31515">&#39;description&#39;</span>]) </span></span><span style="display:flex;"><span>plt.show() </span></span></code></pre><h2 id="results-and-assets">Results and assets</h2> <ol> <li>Because of the small sample size further conclusions are impossible to make.</li> <li>Rule-based approach may not be the best way of doing this. By using deep learning we would be able to get better insights.</li> <li><strong>Next step would be to</strong> periodically fetch RSS items and store them over a longer period of time and then perform analysis again and use either machine learning or deep learning on top of it.</li> </ol> <figure> <img src="/posts/sentiment-analysis/guardian-sa-title-desc-relationship.png" alt="Relationship between title and description" /> </figure> <p>Figure above displays difference between title and description sentiment for specific RSS feed item. 1 means positive and -1 means negative sentiment.</p> <p><a href="/posts/sentiment-analysis/sentiment-analysis.ipynb">» Download Jupyter Notebook</a></p> <h2 id="going-further">Going further</h2> <ul> <li><a href="https://github.com/bswiss/news_mood">Twitter Sentiment Analysis by Bryan Schwierzke</a></li> <li><a href="https://github.com/thisandagain/sentiment">AFINN-based sentiment analysis for Node.js by Andrew Sliwinski</a></li> <li><a href="https://github.com/adeshpande3/LSTM-Sentiment-Analysis">Sentiment Analysis with LSTMs in Tensorflow by Adit Deshpande</a></li> <li><a href="https://github.com/abdulfatir/twitter-sentiment-analysis">Sentiment analysis on tweets using Naive Bayes, SVM, CNN, LSTM, etc. by Abdul Fatir</a></li> </ul> Simplifying and reducing clutter in my life and work https://mitjafelicijan.com/simplifying-and-reducing-clutter.html Mon, 14 Oct 2019 12:00:00 +0200 https://mitjafelicijan.com/simplifying-and-reducing-clutter.html I recently moved my main working machine back from Hachintosh to Linux. <p>I recently moved my main working machine back from Hachintosh to Linux. Well the experiment was interesting and I have done some great work on macOS but it was time to move back.</p> <p>I actually really missed Linux. The simplicity of <code>apt-get</code> or just the amount of software that exists for Linux should be a no-brainer. I spent most of my time on macOS finding solutions to make things work. Using <a href="https://brew.sh/">Brew</a> was just a horrible experience and far from package managers of Linux. At least they managed to get that <code>sudo</code> debacle sorted.</p> <p>Not all was bad. macOS in general was a perfectly good environment. Things like Docker and tooling like this worked without any hiccups. My normal tools like coding IDE worked flawlessly and the whole look and feel is just superb. I have been using MacBook Air for couple of years so I was used to the system but never as a daily driver.</p> <p>One of the things I did after I installed Linux back on my machine was cleaning up my Dropbox folder. I have everything on Dropbox. Even projects folder. I write code for living so my whole life revolves around couple of megs of code (with assets). So it's not like I have huge files on my machine. I don't have movies or music or pictures on my PC. All of that stuff is in cloud. I use Google music and I have Netflix account which is more than enough for me.</p> <p>I also went and deleted some of the repositories on my Github account. I have deleted more code than deployed. People find this strange but for me deleting something feels so cathartic and also forces me to write better code next time around when I am faced with similar problem. That was a huge relief if I am being totally honest.</p> <p>Next step was to do something with my webpage. I have been using some scripts I wrote a while ago to generate static pages from markdown source posts. I kept on adding and adding stuff on top of it and it became a source of a frustration. And this is just a simple blog and I was using gulp and npm. Anyways after couple of hours of searching and testing static generators I found an interesting one <a href="https://github.com/piranha/gostatic">https://github.com/piranha/gostatic</a> and I just decided to use this one. It was the only one that had a simple templating engine, not that I really need one. But others had this convoluted way of trying to solve everything and at the end just required quite bigger learning curve I was ready to go with. So I deleted couple of old posts, simplified HTML, trashed most of the CSS and went with <a href="https://motherfuckingwebsite.com/">https://motherfuckingwebsite.com/</a> aesthetics. Yeah, the previous site was more visually stimulating but all I really care is the content at this point. And Times New Roman font is kind of awesome.</p> <p>I stopped working on most of the projects in the past couple of months because the overhead was just too insane. There comes a point when you stretch yourself too much and then you stop progressing and with that comes dissatisfaction.</p> <p>So that's about it. Moving forward minimal style.</p> Encoding binary data into DNA sequence https://mitjafelicijan.com/encoding-binary-data-into-dna-sequence.html Thu, 03 Jan 2019 12:00:00 +0200 https://mitjafelicijan.com/encoding-binary-data-into-dna-sequence.html Initial thoughtsImagine a world where you could go outside and take a leaf from a tree and putit through your personal DNA sequencer and get data like music, videos orcomputer programs from it. <h2 id="initial-thoughts">Initial thoughts</h2> <p>Imagine a world where you could go outside and take a leaf from a tree and put it through your personal DNA sequencer and get data like music, videos or computer programs from it. Well, this is all possible now. It was not done on a large scale because it is quite expensive to create DNA strands but it's possible.</p> <p>Encoding data into DNA sequence is relatively simple process once you understand the relationship between binary data and nucleotides and scientists have been making large leaps in this field in order to provide viable long-term storage solution for our data that would potentially survive our specie if case of global disaster. We could imprint all the world's knowledge into plants and ensure the survival of our knowledge.</p> <p>More optimistic usage for this technology would be easier storage of ever growing data we produce every day. Once machines for sequencing DNA become fast enough and cheaper this could mean the next evolution of storing data and abandoning classical hard and solid state drives in data warehouses.</p> <p>As we currently stand this is still not viable but it is quite an amazing and cool technology.</p> <p>My interests in this field are purely in encoding processes and experimental testing mainly because I don't have the access to this expensive machines. My initial goal was to create a toolkit that can be used by everybody to encode their data into a proper DNA sequence.</p> <h2 id="glossary">Glossary</h2> <p><strong>deoxyribose</strong> A five-carbon sugar molecule with a hydrogen atom rather than a hydroxyl group in the 2′ position; the sugar component of DNA nucleotides.</p> <p><strong>double helix</strong> The molecular shape of DNA in which two strands of nucleotides wind around each other in a spiral shape.</p> <p><strong>nitrogenous base</strong> A nitrogen-containing molecule that acts as a base; often referring to one of the purine or pyrimidine components of nucleic acids.</p> <p><strong>phosphate group</strong> A molecular group consisting of a central phosphorus atom bound to four oxygen atoms.</p> <p><strong>RGB</strong> The RGB color model is an additive color model in which red, green and blue light are added together in various ways to reproduce a broad array of colors.</p> <p><strong>GCC</strong> The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages.</p> <h2 id="data-encoding">Data encoding</h2> <p><strong>TL;DR:</strong> Encoding involves the use of a code to change original data into a form that can be used by an external process.</p> <p>Encoding is the process of converting data into a format required for a number of information processing needs, including:</p> <ul> <li>Program compiling and execution</li> <li>Data transmission, storage and compression/decompression</li> <li>Application data processing, such as file conversion</li> </ul> <p>Encoding can have two meanings:</p> <ul> <li>In computer technology, encoding is the process of applying a specific code, such as letters, symbols and numbers, to data for conversion into an equivalent cipher.</li> <li>In electronics, encoding refers to analog to digital conversion.</li> </ul> <h2 id="quick-history-of-dna">Quick history of DNA</h2> <ul> <li><strong>1869</strong> - Friedrich Miescher identifies &quot;nuclein&quot;.</li> <li><strong>1900s</strong> - The Eugenics Movement.</li> <li><strong>1900</strong> – Mendel's theories are rediscovered by researchers.</li> <li><strong>1944</strong> - Oswald Avery identifies DNA as the 'transforming principle'.</li> <li><strong>1952</strong> - Rosalind Franklin photographs crystallized DNA fibres.</li> <li><strong>1953</strong> - James Watson and Francis Crick discover the double helix structure of DNA.</li> <li><strong>1965</strong> - Marshall Nirenberg is the first person to sequence the bases in each codon.</li> <li><strong>1983</strong> - Huntington's disease is the first mapped genetic disease.</li> <li><strong>1990</strong> - The Human Genome Project begins.</li> <li><strong>1995</strong> - Haemophilus Influenzae is the first bacterium genome sequenced.</li> <li><strong>1996</strong> - Dolly the sheep is cloned.</li> <li><strong>1999</strong> - First human chromosome is decoded.</li> <li><strong>2000</strong> – Genetic code of the fruit fly is decoded.</li> <li><strong>2002</strong> – Mouse is the first mammal to have its genome decoded.</li> <li><strong>2003</strong> – The Human Genome Project is completed.</li> <li><strong>2013</strong> – DNA Worldwide and Eurofins Forensic discover identical twins have differences in their genetic makeup.</li> </ul> <h2 id="what-is-dna">What is DNA?</h2> <p>Deoxyribonucleic acid, a self-replicating material which is <strong>present in nearly all living organisms</strong> as the main constituent of chromosomes. It is the <strong>carrier of genetic information</strong>.</p> <blockquote> <p>The nitrogen in our DNA, the calcium in our teeth, the iron in our blood, the carbon in our apple pies were made in the interiors of collapsing stars. We are made of starstuff. <strong>-- Carl Sagan, Cosmos</strong></p> </blockquote> <p>The nucleotide in DNA consists of a sugar (deoxyribose), one of four bases (cytosine (C), thymine (T), adenine (A), guanine (G)), and a phosphate. Cytosine and thymine are pyrimidine bases, while adenine and guanine are purine bases. The sugar and the base together are called a nucleoside.</p> <figure> <img src="/posts/dna-sequence/dna-basics.jpg" alt="DNA" /> <figcaption><p><em>DNA (a) forms a double stranded helix, and (b) adenine pairs with thymine and cytosine pairs with guanine. (credit a: modification of work by Jerome Walker, Dennis Myts)</em></p></figcaption> </figure> <h2 id="encode-binary-data-into-dna-sequence">Encode binary data into DNA sequence</h2> <p>As an input file you can use any file you want:</p> <ul> <li>ASCII files,</li> <li>Compiled programs,</li> <li>Multimedia files (MP3, MP4, MVK, etc),</li> <li>Images,</li> <li>Database files,</li> <li>etc.</li> </ul> <p>Note: If you would copy all the bytes from RAM to file or pipe data to file you could encode also this data as long as you provide file pointer to the encoder.</p> <h3 id="basic-encoding">Basic Encoding</h3> <p>As already mentioned, the Basic Encoding is based on a simple mapping. Since DNA is composed of 4 nucleotides (Adenine, Cytosine, Guanine, Thymine; usually referred using the first letter). Using this technique we can encode</p> <p><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 -907.9672135000189 11313.37788460873 1185.0382429179317" style="width: 26.259ex; height: 2.721ex; vertical-align: -0.68ex; margin: 1px 0px;"><g stroke="black" fill="black" stroke-width="0" transform="matrix(1 0 0 -1 0 0)"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMATHI-6C"/><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMATHI-6F" x="303" y="0"/><g transform="translate(793,0)"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMATHI-67"/><use transform="scale(0.7071067811865476)" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMAIN-32" x="681" y="-213"/></g><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMAIN-28" x="1732" y="0"/><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMAIN-34" x="2126" y="0"/><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMAIN-29" x="2631" y="0"/><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMAIN-3D" x="3302" y="0"/><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMATHI-6C" x="4363" y="0"/><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMATHI-6F" x="4666" y="0"/><g transform="translate(5156,0)"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMATHI-67"/><use transform="scale(0.7071067811865476)" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMAIN-32" x="681" y="-213"/></g><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMAIN-28" x="6095" y="0"/><g transform="translate(6489,0)"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMAIN-32"/><use transform="scale(0.7071067811865476)" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMAIN-32" x="714" y="583"/></g><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMAIN-29" x="7451" y="0"/><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMAIN-3D" x="8123" y="0"/><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMAIN-32" x="9184" y="0"/><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMATHI-62" x="9689" y="0"/><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMATHI-69" x="10123" y="0"/><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMATHI-74" x="10473" y="0"/><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#MJMATHI-73" x="10839" y="0"/></g><defs id="MathJax_SVG_glyphs"><path id="MJSZ2-2211" stroke-width="10" d="M60 948Q63 950 665 950H1267L1325 815Q1384 677 1388 669H1348L1341 683Q1320 724 1285 761Q1235 809 1174 838T1033 881T882 898T699 902H574H543H251L259 891Q722 258 724 252Q725 250 724 246Q721 243 460 -56L196 -356Q196 -357 407 -357Q459 -357 548 -357T676 -358Q812 -358 896 -353T1063 -332T1204 -283T1307 -196Q1328 -170 1348 -124H1388Q1388 -125 1381 -145T1356 -210T1325 -294L1267 -449L666 -450Q64 -450 61 -448Q55 -446 55 -439Q55 -437 57 -433L590 177Q590 178 557 222T452 366T322 544L56 909L55 924Q55 945 60 948Z"/><path id="MJMATHI-69" stroke-width="10" d="M184 600Q184 624 203 642T247 661Q265 661 277 649T290 619Q290 596 270 577T226 557Q211 557 198 567T184 600ZM21 287Q21 295 30 318T54 369T98 420T158 442Q197 442 223 419T250 357Q250 340 236 301T196 196T154 83Q149 61 149 51Q149 26 166 26Q175 26 185 29T208 43T235 78T260 137Q263 149 265 151T282 153Q302 153 302 143Q302 135 293 112T268 61T223 11T161 -11Q129 -11 102 10T74 74Q74 91 79 106T122 220Q160 321 166 341T173 380Q173 404 156 404H154Q124 404 99 371T61 287Q60 286 59 284T58 281T56 279T53 278T49 278T41 278H27Q21 284 21 287Z"/><path id="MJMAIN-3D" stroke-width="10" d="M56 347Q56 360 70 367H707Q722 359 722 347Q722 336 708 328L390 327H72Q56 332 56 347ZM56 153Q56 168 72 173H708Q722 163 722 153Q722 140 707 133H70Q56 140 56 153Z"/><path id="MJMAIN-30" stroke-width="10" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z"/><path id="MJMATHI-6E" stroke-width="10" d="M21 287Q22 293 24 303T36 341T56 388T89 425T135 442Q171 442 195 424T225 390T231 369Q231 367 232 367L243 378Q304 442 382 442Q436 442 469 415T503 336T465 179T427 52Q427 26 444 26Q450 26 453 27Q482 32 505 65T540 145Q542 153 560 153Q580 153 580 145Q580 144 576 130Q568 101 554 73T508 17T439 -10Q392 -10 371 17T350 73Q350 92 386 193T423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 180T152 343Q153 348 153 366Q153 405 129 405Q91 405 66 305Q60 285 60 284Q58 278 41 278H27Q21 284 21 287Z"/><path id="MJMAIN-28" stroke-width="10" d="M94 250Q94 319 104 381T127 488T164 576T202 643T244 695T277 729T302 750H315H319Q333 750 333 741Q333 738 316 720T275 667T226 581T184 443T167 250T184 58T225 -81T274 -167T316 -220T333 -241Q333 -250 318 -250H315H302L274 -226Q180 -141 137 -14T94 250Z"/><path id="MJMAIN-2B" stroke-width="10" d="M56 237T56 250T70 270H369V420L370 570Q380 583 389 583Q402 583 409 568V270H707Q722 262 722 250T707 230H409V-68Q401 -82 391 -82H389H387Q375 -82 369 -68V230H70Q56 237 56 250Z"/><path id="MJMAIN-31" stroke-width="10" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"/><path id="MJMAIN-29" stroke-width="10" d="M60 749L64 750Q69 750 74 750H86L114 726Q208 641 251 514T294 250Q294 182 284 119T261 12T224 -76T186 -143T145 -194T113 -227T90 -246Q87 -249 86 -250H74Q66 -250 63 -250T58 -247T55 -238Q56 -237 66 -225Q221 -64 221 250T66 725Q56 737 55 738Q55 746 60 749Z"/><path id="MJMAIN-32" stroke-width="10" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z"/><path id="MJMATHI-6C" stroke-width="10" d="M117 59Q117 26 142 26Q179 26 205 131Q211 151 215 152Q217 153 225 153H229Q238 153 241 153T246 151T248 144Q247 138 245 128T234 90T214 43T183 6T137 -11Q101 -11 70 11T38 85Q38 97 39 102L104 360Q167 615 167 623Q167 626 166 628T162 632T157 634T149 635T141 636T132 637T122 637Q112 637 109 637T101 638T95 641T94 647Q94 649 96 661Q101 680 107 682T179 688Q194 689 213 690T243 693T254 694Q266 694 266 686Q266 675 193 386T118 83Q118 81 118 75T117 65V59Z"/><path id="MJMATHI-6F" stroke-width="10" d="M201 -11Q126 -11 80 38T34 156Q34 221 64 279T146 380Q222 441 301 441Q333 441 341 440Q354 437 367 433T402 417T438 387T464 338T476 268Q476 161 390 75T201 -11ZM121 120Q121 70 147 48T206 26Q250 26 289 58T351 142Q360 163 374 216T388 308Q388 352 370 375Q346 405 306 405Q243 405 195 347Q158 303 140 230T121 120Z"/><path id="MJMATHI-67" stroke-width="10" d="M311 43Q296 30 267 15T206 0Q143 0 105 45T66 160Q66 265 143 353T314 442Q361 442 401 394L404 398Q406 401 409 404T418 412T431 419T447 422Q461 422 470 413T480 394Q480 379 423 152T363 -80Q345 -134 286 -169T151 -205Q10 -205 10 -137Q10 -111 28 -91T74 -71Q89 -71 102 -80T116 -111Q116 -121 114 -130T107 -144T99 -154T92 -162L90 -164H91Q101 -167 151 -167Q189 -167 211 -155Q234 -144 254 -122T282 -75Q288 -56 298 -13Q311 35 311 43ZM384 328L380 339Q377 350 375 354T369 368T359 382T346 393T328 402T306 405Q262 405 221 352Q191 313 171 233T151 117Q151 38 213 38Q269 38 323 108L331 118L384 328Z"/><path id="MJMAIN-34" stroke-width="10" d="M462 0Q444 3 333 3Q217 3 199 0H190V46H221Q241 46 248 46T265 48T279 53T286 61Q287 63 287 115V165H28V211L179 442Q332 674 334 675Q336 677 355 677H373L379 671V211H471V165H379V114Q379 73 379 66T385 54Q393 47 442 46H471V0H462ZM293 211V545L74 212L183 211H293Z"/><path id="MJMATHI-62" stroke-width="10" d="M73 647Q73 657 77 670T89 683Q90 683 161 688T234 694Q246 694 246 685T212 542Q204 508 195 472T180 418L176 399Q176 396 182 402Q231 442 283 442Q345 442 383 396T422 280Q422 169 343 79T173 -11Q123 -11 82 27T40 150V159Q40 180 48 217T97 414Q147 611 147 623T109 637Q104 637 101 637H96Q86 637 83 637T76 640T73 647ZM336 325V331Q336 405 275 405Q258 405 240 397T207 376T181 352T163 330L157 322L136 236Q114 150 114 114Q114 66 138 42Q154 26 178 26Q211 26 245 58Q270 81 285 114T318 219Q336 291 336 325Z"/><path id="MJMATHI-74" stroke-width="10" d="M26 385Q19 392 19 395Q19 399 22 411T27 425Q29 430 36 430T87 431H140L159 511Q162 522 166 540T173 566T179 586T187 603T197 615T211 624T229 626Q247 625 254 615T261 596Q261 589 252 549T232 470L222 433Q222 431 272 431H323Q330 424 330 420Q330 398 317 385H210L174 240Q135 80 135 68Q135 26 162 26Q197 26 230 60T283 144Q285 150 288 151T303 153H307Q322 153 322 145Q322 142 319 133Q314 117 301 95T267 48T216 6T155 -11Q125 -11 98 4T59 56Q57 64 57 83V101L92 241Q127 382 128 383Q128 385 77 385H26Z"/><path id="MJMATHI-73" stroke-width="10" d="M131 289Q131 321 147 354T203 415T300 442Q362 442 390 415T419 355Q419 323 402 308T364 292Q351 292 340 300T328 326Q328 342 337 354T354 372T367 378Q368 378 368 379Q368 382 361 388T336 399T297 405Q249 405 227 379T204 326Q204 301 223 291T278 274T330 259Q396 230 396 163Q396 135 385 107T352 51T289 7T195 -10Q118 -10 86 19T53 87Q53 126 74 143T118 160Q133 160 146 151T160 120Q160 94 142 76T111 58Q109 57 108 57T107 55Q108 52 115 47T146 34T201 27Q237 27 263 38T301 66T318 97T323 122Q323 150 302 164T254 181T195 196T148 231Q131 256 131 289Z"/></defs></svg></p> <p>using a single nucleotide. In this way, we are able to use the 4 bases that compose the DNA strand to encode each byte of data.</p> <table> <thead> <tr> <th>Two bits</th> <th>Nucleotides</th> </tr> </thead> <tbody> <tr> <td>00</td> <td><strong>A</strong> (Adenine)</td> </tr> <tr> <td>10</td> <td><strong>G</strong> (Guanine)</td> </tr> <tr> <td>01</td> <td><strong>C</strong> (Cytosine)</td> </tr> <tr> <td>11</td> <td><strong>T</strong> (Thymine)</td> </tr> </tbody> </table> <p>With this in mind we can simply encode any data by using two-bit to Nucleotides conversion.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>{ Algorithm 1: Naive byte array to DNA encode } </span></span><span style="display:flex;"><span>procedure EncodeToDNASequence(f) string </span></span><span style="display:flex;"><span>begin </span></span><span style="display:flex;"><span> enc string </span></span><span style="display:flex;"><span> <span style="color:#00f">while</span> <span style="color:#00f">not</span> eof(f) do </span></span><span style="display:flex;"><span> c byte := buffer[0] { Read 1 byte <span style="color:#00f">from</span> buffer } </span></span><span style="display:flex;"><span> bin integer := sprintf(<span style="color:#a31515">&#39;08b&#39;</span>, c) { Convert to string binary } </span></span><span style="display:flex;"><span> <span style="color:#00f">for</span> e <span style="color:#00f">in</span> range[0, 2, 4, 6] do </span></span><span style="display:flex;"><span> <span style="color:#00f">if</span> e[0] == 48 <span style="color:#00f">and</span> e[1] == 48 then { 0x00 - A (Adenine) } </span></span><span style="display:flex;"><span> enc += <span style="color:#a31515">&#39;A&#39;</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">else</span> <span style="color:#00f">if</span> e[0] == 48 <span style="color:#00f">and</span> e[1] == 49 then { 0x01 - G (Guanine) } </span></span><span style="display:flex;"><span> enc += <span style="color:#a31515">&#39;G&#39;</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">else</span> <span style="color:#00f">if</span> e[0] == 49 <span style="color:#00f">and</span> e[1] == 48 then { 0x10 - C (Cytosine) } </span></span><span style="display:flex;"><span> enc += <span style="color:#a31515">&#39;C&#39;</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">else</span> <span style="color:#00f">if</span> e[0] == 49 <span style="color:#00f">and</span> e[1] == 49 then { 0x11 - T (Thymine) } </span></span><span style="display:flex;"><span> enc += <span style="color:#a31515">&#39;T&#39;</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">return</span> enc { Return DNA sequence } </span></span><span style="display:flex;"><span>end </span></span></code></pre><p>Another encoding would be <strong>Goldman encoding</strong>. Using this encoding helps with Nonsense mutation (amino acids replaced by a stop codon) that occurs and is the most problematic during translation because it leads to truncated amino acid sequences, which in turn results in truncated proteins.</p> <p><a href="https://www.youtube.com/watch?v=a4PiGWNsIEU">Where to store big data? In DNA: Nick Goldman at TEDxPrague</a></p> <h3 id="fasta-file-format">FASTA file format</h3> <p>In bioinformatics, FASTA format is a text-based format for representing either nucleotide sequences or peptide sequences, in which nucleotides or amino acids are represented using single-letter codes. The format also allows for sequence names and comments to precede the sequences. The format originates from the FASTA software package, but has now become a standard in the field of bioinformatics.</p> <p>The first line in a FASTA file started either with a &quot;&gt;&quot; (greater-than) symbol or, less frequently, a &quot;;&quot; (semicolon) was taken as a comment. Subsequent lines starting with a semicolon would be ignored by software. Since the only comment used was the first, it quickly became used to hold a summary description of the sequence, often starting with a unique library accession number, and with time it has become commonplace to always use &quot;&gt;&quot; for the first line and to not use &quot;;&quot; comments (which would otherwise be ignored).</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>;LCBO - Prolactin precursor - Bovine </span></span><span style="display:flex;"><span>; a sample sequence in FASTA format </span></span><span style="display:flex;"><span>MDSKGSSQKGSRLLLLLVVSNLLLCQGVVSTPVCPNGPGNCQVSLRDLFDRAVMVSHYIHDLSS </span></span><span style="display:flex;"><span>EMFNEFDKRYAQGKGFITMALNSCHTSSLPTPEDKEQAQQTHHEVLMSLILGLLRSWNDPLYHL </span></span><span style="display:flex;"><span>VTEVRGMKGAPDAILSRAIEIEEENKRLLEGMEMIFGQVIPGAKETEPYPVWSGLPSLQTKDED </span></span><span style="display:flex;"><span>ARYSAFYNLLHCLRRDSSKIDTYLKLLNCRIIYNNNC* </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>&gt;MCHU - Calmodulin - Human, rabbit, bovine, rat, and chicken </span></span><span style="display:flex;"><span>ADQLTEEQIAEFKEAFSLFDKDGDGTITTKELGTVMRSLGQNPTEAELQDMINEVDADGNGTID </span></span><span style="display:flex;"><span>FPEFLTMMARKMKDTDSEEEIREAFRVFDKDGNGYISAAELRHVMTNLGEKLTDEEVDEMIREA </span></span><span style="display:flex;"><span>DIDGDGQVNYEEFVQMMTAK* </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>&gt;gi|5524211|gb|AAD44166.1| cytochrome b [Elephas maximus maximus] </span></span><span style="display:flex;"><span>LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV </span></span><span style="display:flex;"><span>EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG </span></span><span style="display:flex;"><span>LLILILLLLLLALLSPDMLGDPDNHMPADPLNTPLHIKPEWYFLFAYAILRSVPNKLGGVLALFLSIVIL </span></span><span style="display:flex;"><span>GLMPFLHTSKHRSMMLRPLSQALFWTLTMDLLTLTWIGSQPVEYPYTIIGQMASILYFSIILAFLPIAGX </span></span><span style="display:flex;"><span>IENY </span></span></code></pre><p>FASTA format was extended by <a href="https://en.wikipedia.org/wiki/FASTQ_format">FASTQ</a> format from the <a href="https://www.sanger.ac.uk/">Sanger Centre</a> in Cambridge.</p> <h3 id="png-encoded-dna-sequence">PNG encoded DNA sequence</h3> <table> <thead> <tr> <th>Nucleotides</th> <th>RGB</th> <th>Color name</th> </tr> </thead> <tbody> <tr> <td>A ➞ Adenine</td> <td>(0,0,255)</td> <td>Blue</td> </tr> <tr> <td>G ➞ Guanine</td> <td>(0,100,0)</td> <td>Green</td> </tr> <tr> <td>C ➞ Cytosine</td> <td>(255,0,0)</td> <td>Red</td> </tr> <tr> <td>T ➞ Thymine</td> <td>(255,255,0)</td> <td>Yellow</td> </tr> </tbody> </table> <p>With this in mind we can create a simple algorithm to create PNG representation of a DNA sequence.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>{ Algorithm 2: Naive DNA to PNG encode <span style="color:#00f">from</span> FASTA file } </span></span><span style="display:flex;"><span>procedure EncodeDNASequenceToPNG(f) </span></span><span style="display:flex;"><span>begin </span></span><span style="display:flex;"><span> i image </span></span><span style="display:flex;"><span> <span style="color:#00f">while</span> <span style="color:#00f">not</span> eof(f) do </span></span><span style="display:flex;"><span> c char := buffer[0] { Read 1 char <span style="color:#00f">from</span> buffer } </span></span><span style="display:flex;"><span> case c of </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;A&#39;</span>: color := RGB(0, 0, 255) { Blue } </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;G&#39;</span>: color := RGB(0, 100, 0) { Green } </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;C&#39;</span>: color := RGB(255, 0, 0) { Red } </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#39;T&#39;</span>: color := RGB(255, 255, 0) { Yellow } </span></span><span style="display:flex;"><span> drawRect(i, [x, y], color) </span></span><span style="display:flex;"><span> save(i) { Save PNG image } </span></span><span style="display:flex;"><span>end </span></span></code></pre><h2 id="encoding-text-file-in-practice">Encoding text file in practice</h2> <p>In this example we will take a simple text file as our input stream for encoding. This file will have a quote from Niels Bohr and saved as txt file.</p> <blockquote> <p>How wonderful that we have met with a paradox. Now we have some hope of making progress. ― Niels Bohr</p> </blockquote> <p>First we encode text file into FASTA file.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>./dnae-encode -i quote.txt -o quote.fa </span></span><span style="display:flex;"><span>2019/01/10 00:38:29 Gathering input file stats </span></span><span style="display:flex;"><span>2019/01/10 00:38:29 Starting encoding ... </span></span><span style="display:flex;"><span> 106 B / 106 B [==================================] 100.00% 0s </span></span><span style="display:flex;"><span>2019/01/10 00:38:29 Saving to FASTA file ... </span></span><span style="display:flex;"><span>2019/01/10 00:38:29 Output FASTA file length is 438 B </span></span><span style="display:flex;"><span>2019/01/10 00:38:29 Process took 987.263µs </span></span><span style="display:flex;"><span>2019/01/10 00:38:29 Done ... </span></span></code></pre><p>Output of <code>quote.fa</code> file contains the encoded DNA sequence in ASCII format.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>&gt;SEQ1 </span></span><span style="display:flex;"><span>GACAGCTTGTGTACAAGTGTGCTTGCTCGCGAGCGGGTACGCGCGTGGGCTAACAAGTGA </span></span><span style="display:flex;"><span>GCCAGCAGGTGAACAAGTGTGCGGACAAGCCAGCAGGTGCGCGGACAAGCTGGCGGGTGA </span></span><span style="display:flex;"><span>ACAAGTGTGCCGGTGAGCCAACAAGCAGACAAGTAAGCAGGTACGCAGGCGAGCTTGTCA </span></span><span style="display:flex;"><span>ACTCACAAGATCGCTTGTGTACAAGTGTGCGGACAAGCCAGCAGGTGCGCGGACAAGTAT </span></span><span style="display:flex;"><span>GCTTGCTGGCGGACAAGCCAGCTTGTAAGCGGACAAGCTTGCGCACAAGCTGGCAGGCCT </span></span><span style="display:flex;"><span>GCCGGCTCGCGTACAAATTCACAAGTAAGTACGCTTGCGTGTACGCGGGTATGTATACTC </span></span><span style="display:flex;"><span>AACCTCACCAAACGGGACAAGATCGCCGGCGGGCTAGTATACAAGAACGCTTGCCAGTAC </span></span><span style="display:flex;"><span>AACC </span></span></code></pre><p>Then we encode FASTA file from previous operation to encode this data into PNG.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>./dnae-png -i quote.fa -o quote.png </span></span><span style="display:flex;"><span>2019/01/10 00:40:09 Gathering input file stats ... </span></span><span style="display:flex;"><span>2019/01/10 00:40:09 Deconstructing FASTA file ... </span></span><span style="display:flex;"><span>2019/01/10 00:40:09 Compositing image file ... </span></span><span style="display:flex;"><span> 424 / 424 [==================================] 100.00% 0s </span></span><span style="display:flex;"><span>2019/01/10 00:40:09 Saving output file ... </span></span><span style="display:flex;"><span>2019/01/10 00:40:09 Output image file length is 1.1 kB </span></span><span style="display:flex;"><span>2019/01/10 00:40:09 Process took 19.036117ms </span></span><span style="display:flex;"><span>2019/01/10 00:40:09 Done ... </span></span></code></pre><p>After encoding into PNG format this file looks like this.</p> <figure> <img src="/posts/dna-sequence/quote.png" alt="Encoded Quote in PNG format" /> <figcaption><p>The larger the input stream is the larger the PNG file would be.</p></figcaption> </figure> <p>Compiled basic Hello World C program with <a href="https://www.gnu.org/software/gcc/">GCC</a> would <a href="/posts/dna-sequence/sample.png">look like</a>.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000">// gcc -O3 -o sample sample.c </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span><span style="color:#00f">#include</span> <span style="color:#00f">&lt;stdio.h&gt;</span><span style="color:#00f"> </span></span></span><span style="display:flex;"><span><span style="color:#00f"></span> </span></span><span style="display:flex;"><span>main() { </span></span><span style="display:flex;"><span> printf(<span style="color:#a31515">&#34;Hello, world!</span><span style="color:#a31515">\n</span><span style="color:#a31515">&#34;</span>); </span></span><span style="display:flex;"><span> <span style="color:#00f">return</span> 0; </span></span><span style="display:flex;"><span>} </span></span></code></pre><h2 id="toolkit-for-encoding-data">Toolkit for encoding data</h2> <p>I have created a toolkit with two main programs:</p> <ul> <li>dnae-encode (encodes file into FASTA file)</li> <li>dnae-png (encodes FASTA file into PNG)</li> </ul> <p>Toolkit with full source code is available on <a href="https://github.com/mitjafelicijan/dna-encoding">github.com/mitjafelicijan/dna-encoding</a>.</p> <h3 id="dnae-encode">dnae-encode</h3> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>&gt; ./dnae-encode --help </span></span><span style="display:flex;"><span>usage: dnae-encode --input=INPUT [&lt;flags&gt;] </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>A command-line application that encodes file into DNA sequence. </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>Flags: </span></span><span style="display:flex;"><span> --help Show context-sensitive help (also try --help-long and --help-man). </span></span><span style="display:flex;"><span> -i, --input=INPUT Input file (ASCII or binary) which will be encoded into DNA sequence. </span></span><span style="display:flex;"><span> -o, --output=<span style="color:#a31515">&#34;out.fa&#34;</span> Output file which stores DNA sequence in FASTA format. </span></span><span style="display:flex;"><span> -s, --sequence=SEQ1 The description line (defline) or header/identifier line, gives a name and/or a unique identifier <span style="color:#00f">for</span> the sequence. </span></span><span style="display:flex;"><span> -c, --columns=60 Row characters length (no more than 120 characters). Devices preallocate fixed line sizes in software. </span></span><span style="display:flex;"><span> --version Show application version. </span></span></code></pre><h3 id="dnae-png">dnae-png</h3> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>&gt; ./dnae-png --help </span></span><span style="display:flex;"><span>usage: dnae-png --input=INPUT [&lt;flags&gt;] </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>A command-line application that encodes FASTA file into PNG image. </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>Flags: </span></span><span style="display:flex;"><span> --help Show context-sensitive help (also try --help-long and --help-man). </span></span><span style="display:flex;"><span> -i, --input=INPUT Input FASTA file which will be encoded into PNG image. </span></span><span style="display:flex;"><span> -o, --output=<span style="color:#a31515">&#34;out.png&#34;</span> Output file in PNG format that represents DNA sequence in graphical way. </span></span><span style="display:flex;"><span> -s, --size=10 Size of pairings of DNA bases on image in pixels (lower resolution lower file size). </span></span><span style="display:flex;"><span> --version Show application version. </span></span></code></pre><h2 id="benchmarks">Benchmarks</h2> <p>First we generate some binary sample data with dd.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>dd <span style="color:#00f">if</span>=&lt;(openssl enc -aes-256-ctr -pass pass:<span style="color:#a31515">&#34;</span><span style="color:#00f">$(</span>dd <span style="color:#00f">if</span>=/dev/urandom bs=128 count=1 2&gt;/dev/null | base64<span style="color:#00f">)</span><span style="color:#a31515">&#34;</span> -nosalt &lt; /dev/zero) of=1KB.bin bs=1KB count=1 iflag=fullblock </span></span></code></pre><p>Our freshly generated 1KB file looks something like this (its full of garbage data as intended).</p> <figure> <img src="/posts/dna-sequence/sample-binary-file.png" alt="Sample binary file 1KB" /> </figure> <p>We create following binary files:</p> <ul> <li>1KB.bin</li> <li>10KB.bin</li> <li>100KB.bin</li> <li>1MB.bin</li> <li>10MB.bin</li> <li>100MB.bin</li> </ul> <p>After this we create FASTA files for all the binary files by encoding them into DNA sequence.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>./dnae-encode -i 100MB.bin -o 100MB.fa </span></span></code></pre><p>Then we GZIP all the FASTA files to see how much the can be compressed.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>gzip -9 &lt; 10MB.fa &gt; 10MB.fa.gz </span></span></code></pre><figure> <img src="/posts/dna-sequence/chart-speed.svg" alt="Encode to FASTA" /> <figcaption><p>The speed increase that occurs when encoding to FASTA format.</p></figcaption> </figure> <figure> <img src="/posts/dna-sequence/chart-size.svg" alt="File sizes" /> <figcaption><p>Size of the out file after encoding.</p></figcaption> </figure> <p><a href="/posts/dna-sequence/benchmarks.csv">Download CSV file with benchmarks</a>.</p> <h2 id="references">References</h2> <ul> <li><a href="https://www.techopedia.com/definition/948/encoding">https://www.techopedia.com/definition/948/encoding</a></li> <li><a href="https://www.dna-worldwide.com/resource/160/history-dna-timeline">https://www.dna-worldwide.com/resource/160/history-dna-timeline</a></li> <li><a href="https://opentextbc.ca/biology/chapter/9-1-the-structure-of-dna/">https://opentextbc.ca/biology/chapter/9-1-the-structure-of-dna/</a></li> <li><a href="https://arxiv.org/abs/1801.04774">https://arxiv.org/abs/1801.04774</a></li> <li><a href="https://en.wikipedia.org/wiki/FASTA_format">https://en.wikipedia.org/wiki/FASTA_format</a></li> </ul> Using DigitalOcean Spaces Object Storage with FUSE https://mitjafelicijan.com/using-digitalocean-spaces-object-storage-with-fuse.html Tue, 16 Jan 2018 12:00:00 +0200 https://mitjafelicijan.com/using-digitalocean-spaces-object-storage-with-fuse.html Couple of months ago DigitalOcean introduced newproduct calledSpaces whichis Object Storage very similar to Amazon&#39;s S3. <p>Couple of months ago <a href="https://www.digitalocean.com">DigitalOcean</a> introduced new product called <a href="https://blog.digitalocean.com/introducing-spaces-object-storage/">Spaces</a> which is Object Storage very similar to Amazon's S3. This really peaked my interest, because this was something I was missing and even the thought of going over the internet for such functionality was in no interest to me. Also in fashion with their previous pricing this also is very cheap and pricing page is a no-brainer compared to AWS or GCE. <a href="https://www.digitalocean.com/pricing/">Prices are clearly and precisely defined and outlined</a>. You must love them for that :)</p> <h2 id="initial-requirements">Initial requirements</h2> <ul> <li>Is it possible to use them as a mounted drive with FUSE? (tl;dr YES)</li> <li>Will the performance degrade over time and over different sizes of objects? (tl;dr NO&amp;YES)</li> <li>Can storage be mounted on multiple machines at the same time and be writable? (tl;dr YES)</li> </ul> <blockquote> <p>Let me be clear. This scripts I use are made just for benchmarking and are not intended to be used in real-life situations. Besides that, I am looking into using this approaches but adding caching service in front of it and then dumping everything as an object to storage. This could potentially be some interesting post of itself. But in case you would need real-time data without eventual consistency please take this scripts as they are: not usable in such situations.</p> </blockquote> <h2 id="is-it-possible-to-use-them-as-a-mounted-drive-with-fuse">Is it possible to use them as a mounted drive with FUSE?</h2> <p>Well, actually they can be used in such manor. Because they are similar to <a href="https://aws.amazon.com/s3/">AWS S3</a> many tools are available and you can find many articles and <a href="https://stackoverflow.com/search?q=s3+fuse">Stackoverflow items</a>.</p> <p>To make this work you will need DigitalOcean account. If you don't have one you will not be able to test this code. But if you have an account then you go and <a href="https://cloud.digitalocean.com/droplets/new?size=s-1vcpu-1gb&amp;region=ams3&amp;distro=debian&amp;distroImage=debian-9-x64&amp;options=private_networking,install_agent">create new Droplet</a>. If you click on this link you will already have preselected Debian 9 with smallest VM option.</p> <ul> <li>Please be sure to add you SSH key, because we will login to this machine remotely.</li> <li>If you change your region please remember which one you choose because we will need this information when we try to mount space to our machine.</li> </ul> <p>Instuctions on how to use SSH keys and how to setup them are available in article <a href="https://www.digitalocean.com/community/tutorials/how-to-use-ssh-keys-with-digitalocean-droplets">How To Use SSH Keys with DigitalOcean Droplets</a>.</p> <figure> <img src="/posts/do-fuse/fuse-droplets.png" alt="DigitalOcean Droplets" /> </figure> <p>After we created Droplet it's time to create new Space. This is done by clicking on a button <a href="https://cloud.digitalocean.com/spaces/new">Create</a> (right top corner) and selecting Spaces. Choose pronounceable <code>Unique name</code> because we will use it in examples below. You can either choose Private or Public, it doesn't matter in our case. And you can always change that in the future.</p> <p>When you have created new Space we should <a href="https://cloud.digitalocean.com/settings/api/tokens">generate Access key</a>. This link will guide to the page when you can generate this key. After you create new one, please save provided Key and Secret because Secret will not be shown again.</p> <figure> <img src="/posts/do-fuse/fuse-spaces.png" alt="DigitalOcean Spaces" /> </figure> <p>Now that we have new Space and Access key we should SSH into our machine.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># replace IP with the ip of your newly created droplet</span> </span></span><span style="display:flex;"><span>ssh root@IP </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># this will install utilities for mounting storage objects as FUSE</span> </span></span><span style="display:flex;"><span>apt install s3fs </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># we now need to provide credentials (access key we created earlier)</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># replace KEY and SECRET with your own credentials but leave the colon between them</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># we also need to set proper permissions</span> </span></span><span style="display:flex;"><span>echo <span style="color:#a31515">&#34;KEY:SECRET&#34;</span> &gt; .passwd-s3fs </span></span><span style="display:flex;"><span>chmod 600 .passwd-s3fs </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># now we mount space to our machine</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># replace UNIQUE-NAME with the name you choose earlier</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># if you choose different region for your space be careful about -ourl option (ams3)</span> </span></span><span style="display:flex;"><span>s3fs UNIQUE-NAME /mnt/ -ourl=https://ams3.digitaloceanspaces.com -ouse_cache=/tmp </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># now we try to create a file</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># once you mount it may take a couple of seconds to retrieve data</span> </span></span><span style="display:flex;"><span>echo <span style="color:#a31515">&#34;Hello cruel world&#34;</span> &gt; /mnt/hello.txt </span></span></code></pre><p>After all this you can return to your browser and go to <a href="https://cloud.digitalocean.com/spaces">DigitalOcean Spaces</a> and click on your created space. If file hello.txt is present you have successfully mounted space to your machine and wrote data to it.</p> <p>I choose the same region for my Droplet and my Space but you don't have to. You can have different regions. What this actually does to performance I don't know.</p> <p>Additional information on FUSE:</p> <ul> <li><a href="https://github.com/s3fs-fuse/s3fs-fuse">Github project page for s3fs</a></li> <li><a href="https://en.wikipedia.org/wiki/Filesystem_in_Userspace">FUSE - Filesystem in Userspace</a></li> </ul> <h2 id="will-the-performance-degrade-over-time-and-over-different-sizes-of-objects">Will the performance degrade over time and over different sizes of objects?</h2> <p>For this task I didn't want to just read and write text files or uploading images. I actually wanted to figure out if using something like SQlite is viable in this case.</p> <h3 id="measurement-experiment-1-file-copy">Measurement experiment 1: File copy</h3> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># first we create some dummy files at different sizes</span> </span></span><span style="display:flex;"><span>dd <span style="color:#00f">if</span>=/dev/zero of=10KB.dat bs=1024 count=10 <span style="color:#008000">#10KB</span> </span></span><span style="display:flex;"><span>dd <span style="color:#00f">if</span>=/dev/zero of=100KB.dat bs=1024 count=100 <span style="color:#008000">#100KB</span> </span></span><span style="display:flex;"><span>dd <span style="color:#00f">if</span>=/dev/zero of=1MB.dat bs=1024 count=1024 <span style="color:#008000">#1MB</span> </span></span><span style="display:flex;"><span>dd <span style="color:#00f">if</span>=/dev/zero of=10MB.dat bs=1024 count=10240 <span style="color:#008000">#10MB</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># now we set time command to only return real</span> </span></span><span style="display:flex;"><span>TIMEFORMAT=%R </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># now lets test it</span> </span></span><span style="display:flex;"><span>(time cp 10KB.dat /mnt/) |&amp; tee -a 10KB.results.txt </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># and now we automate</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># this will perform the same operation 100 times</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># this will output results into separated files based on objecty size</span> </span></span><span style="display:flex;"><span>n=0; <span style="color:#00f">while</span> (( n++ &lt; 100 )); <span style="color:#00f">do</span> (time cp 10KB.dat /mnt/10KB.$n.dat) |&amp; tee -a 10KB.results.txt; <span style="color:#00f">done</span> </span></span><span style="display:flex;"><span>n=0; <span style="color:#00f">while</span> (( n++ &lt; 100 )); <span style="color:#00f">do</span> (time cp 100KB.dat /mnt/100KB.$n.dat) |&amp; tee -a 100KB.results.txt; <span style="color:#00f">done</span> </span></span><span style="display:flex;"><span>n=0; <span style="color:#00f">while</span> (( n++ &lt; 100 )); <span style="color:#00f">do</span> (time cp 1MB.dat /mnt/1MB.$n.dat) |&amp; tee -a 1MB.results.txt; <span style="color:#00f">done</span> </span></span><span style="display:flex;"><span>n=0; <span style="color:#00f">while</span> (( n++ &lt; 100 )); <span style="color:#00f">do</span> (time cp 10MB.dat /mnt/10MB.$n.dat) |&amp; tee -a 10MB.results.txt; <span style="color:#00f">done</span> </span></span></code></pre><p>Files of size 100MB were not successfully transferred and ended up displaying error (cp: failed to close '/mnt/100MB.1.dat': Operation not permitted).</p> <p>As I suspected, object size is not really that important. Sadly I don't have the time to test performance over periods of time. But if some of you would do it please send me your data. I would be interested in seeing results.</p> <p><strong>Here are plotted results</strong></p> <p>You can download <a href="/posts/do-fuse/copy-benchmarks.tsv">raw result here</a>. Measurements are in seconds.</p> <script src="//cdn.plot.ly/plotly-latest.min.js"></script> <div id="copy-benchmarks"></div> <script> (function(){ var request = new XMLHttpRequest(); request.open("GET", "/posts/do-fuse/copy-benchmarks.tsv", true); request.onload = function() { if (request.status >= 200 && request.status < 400) { var payload = request.responseText.trim(); var tsv = payload.split("\n"); for (var i=0; i<tsv.length; i++) { tsv[i] = tsv[i].split("\t"); } var traces = []; var headers = tsv[0]; tsv.shift(); Array.prototype.forEach.call(headers, function(el, idx) { var x = []; var y = []; for (var j=0; j<tsv.length; j++) { x.push(j); y.push(parseFloat(tsv[j][idx].replace(",", "."))); } traces.push({ x: x, y: y, type: "scatter", name: el, line: { width: 1, shape: "spline" } }); }); var copy = Plotly.newPlot("copy-benchmarks", traces, { legend: {"orientation": "h"}, height: 400, margin: { l: 40, r: 0, b: 20, t: 30, pad: 0 }, yaxis: { title: "execution time in seconds", titlefont: { size: 12 } }, xaxis: { title: "fn(i)", titlefont: { size: 12 } } }); } else { } }; request.onerror = function() { }; request.send(null); })(); </script> <p>As far as these tests show, performance is quite stable and can be predicted which is fantastic. But this is a small test and spans only over couple of hours. So you should not completely trust them.</p> <h3 id="measurement-experiment-2-sqlite-performanse">Measurement experiment 2: SQLite performanse</h3> <p>I was unable to use database file directly from mounted drive so this is a no-go as I suspected. So I executed code below on a local disk just to get some benchmarks. I inserted 1000 records with DROPTABLE, CREATETABLE, INSERTMANY, FETCHALL, COMMIT for 1000 times to generate statistics. As you can see performance of SQLite is quite amazing. You could then potentially just copy file to mounted drive and be done with it.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">import</span> time </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> sqlite3 </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> sys </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">if</span> len(sys.argv) &lt; 3: </span></span><span style="display:flex;"><span> print(<span style="color:#a31515">&#34;usage: python sqlite-benchmark.py DB_PATH NUM_RECORDS REPEAT&#34;</span>) </span></span><span style="display:flex;"><span> exit() </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">def</span> data_iter(x): </span></span><span style="display:flex;"><span> <span style="color:#00f">for</span> i <span style="color:#00f">in</span> range(x): </span></span><span style="display:flex;"><span> <span style="color:#00f">yield</span> <span style="color:#a31515">&#34;m&#34;</span> + str(i), <span style="color:#a31515">&#34;f&#34;</span> + str(i*i) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>header_line = <span style="color:#a31515">&#34;</span><span style="color:#a31515">%s</span><span style="color:#a31515">\t</span><span style="color:#a31515">%s</span><span style="color:#a31515">\t</span><span style="color:#a31515">%s</span><span style="color:#a31515">\t</span><span style="color:#a31515">%s</span><span style="color:#a31515">\t</span><span style="color:#a31515">%s</span><span style="color:#a31515">\n</span><span style="color:#a31515">&#34;</span> % (<span style="color:#a31515">&#34;DROPTABLE&#34;</span>, <span style="color:#a31515">&#34;CREATETABLE&#34;</span>, <span style="color:#a31515">&#34;INSERTMANY&#34;</span>, <span style="color:#a31515">&#34;FETCHALL&#34;</span>, <span style="color:#a31515">&#34;COMMIT&#34;</span>) </span></span><span style="display:flex;"><span><span style="color:#00f">with</span> open(<span style="color:#a31515">&#34;sqlite-benchmarks.tsv&#34;</span>, <span style="color:#a31515">&#34;w&#34;</span>) <span style="color:#00f">as</span> fp: </span></span><span style="display:flex;"><span> fp.write(header_line) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>start_time = time.time() </span></span><span style="display:flex;"><span>conn = sqlite3.connect(sys.argv[1]) </span></span><span style="display:flex;"><span>c = conn.cursor() </span></span><span style="display:flex;"><span>end_time = time.time() </span></span><span style="display:flex;"><span>result_time = CONNECT = end_time - start_time </span></span><span style="display:flex;"><span>print(<span style="color:#a31515">&#34;CONNECT: </span><span style="color:#a31515">%g</span><span style="color:#a31515"> seconds&#34;</span> % (result_time)) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>start_time = time.time() </span></span><span style="display:flex;"><span>c.execute(<span style="color:#a31515">&#34;PRAGMA journal_mode=WAL&#34;</span>) </span></span><span style="display:flex;"><span>c.execute(<span style="color:#a31515">&#34;PRAGMA temp_store=MEMORY&#34;</span>) </span></span><span style="display:flex;"><span>c.execute(<span style="color:#a31515">&#34;PRAGMA synchronous=OFF&#34;</span>) </span></span><span style="display:flex;"><span>result_time = PRAGMA = end_time - start_time </span></span><span style="display:flex;"><span>print(<span style="color:#a31515">&#34;PRAGMA: </span><span style="color:#a31515">%g</span><span style="color:#a31515"> seconds&#34;</span> % (result_time)) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">for</span> i <span style="color:#00f">in</span> range(int(sys.argv[3])): </span></span><span style="display:flex;"><span> print(<span style="color:#a31515">&#34;#</span><span style="color:#a31515">%i</span><span style="color:#a31515">&#34;</span> % (i)) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> start_time = time.time() </span></span><span style="display:flex;"><span> c.execute(<span style="color:#a31515">&#34;drop table if exists test&#34;</span>) </span></span><span style="display:flex;"><span> end_time = time.time() </span></span><span style="display:flex;"><span> result_time = DROPTABLE = end_time - start_time </span></span><span style="display:flex;"><span> print(<span style="color:#a31515">&#34;DROPTABLE: </span><span style="color:#a31515">%g</span><span style="color:#a31515"> seconds&#34;</span> % (result_time)) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> start_time = time.time() </span></span><span style="display:flex;"><span> c.execute(<span style="color:#a31515">&#34;create table if not exists test(a,b)&#34;</span>) </span></span><span style="display:flex;"><span> end_time = time.time() </span></span><span style="display:flex;"><span> result_time = CREATETABLE = end_time - start_time </span></span><span style="display:flex;"><span> print(<span style="color:#a31515">&#34;CREATETABLE: </span><span style="color:#a31515">%g</span><span style="color:#a31515"> seconds&#34;</span> % (result_time)) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> start_time = time.time() </span></span><span style="display:flex;"><span> c.executemany(<span style="color:#a31515">&#34;INSERT INTO test VALUES (?, ?)&#34;</span>, data_iter(int(sys.argv[2]))) </span></span><span style="display:flex;"><span> end_time = time.time() </span></span><span style="display:flex;"><span> result_time = INSERTMANY = end_time - start_time </span></span><span style="display:flex;"><span> print(<span style="color:#a31515">&#34;INSERTMANY: </span><span style="color:#a31515">%g</span><span style="color:#a31515"> seconds&#34;</span> % (result_time)) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> start_time = time.time() </span></span><span style="display:flex;"><span> c.execute(<span style="color:#a31515">&#34;select count(*) from test&#34;</span>) </span></span><span style="display:flex;"><span> res = c.fetchall() </span></span><span style="display:flex;"><span> end_time = time.time() </span></span><span style="display:flex;"><span> result_time = FETCHALL = end_time - start_time </span></span><span style="display:flex;"><span> print(<span style="color:#a31515">&#34;FETCHALL: </span><span style="color:#a31515">%g</span><span style="color:#a31515"> seconds&#34;</span> % (result_time)) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> start_time = time.time() </span></span><span style="display:flex;"><span> conn.commit() </span></span><span style="display:flex;"><span> end_time = time.time() </span></span><span style="display:flex;"><span> result_time = COMMIT = end_time - start_time </span></span><span style="display:flex;"><span> print(<span style="color:#a31515">&#34;COMMIT: </span><span style="color:#a31515">%g</span><span style="color:#a31515"> seconds&#34;</span> % (result_time)) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> print </span></span><span style="display:flex;"><span> log_line = <span style="color:#a31515">&#34;</span><span style="color:#a31515">%f</span><span style="color:#a31515">\t</span><span style="color:#a31515">%f</span><span style="color:#a31515">\t</span><span style="color:#a31515">%f</span><span style="color:#a31515">\t</span><span style="color:#a31515">%f</span><span style="color:#a31515">\t</span><span style="color:#a31515">%f</span><span style="color:#a31515">\n</span><span style="color:#a31515">&#34;</span> % (DROPTABLE, CREATETABLE, INSERTMANY, FETCHALL, COMMIT) </span></span><span style="display:flex;"><span> <span style="color:#00f">with</span> open(<span style="color:#a31515">&#34;sqlite-benchmarks.tsv&#34;</span>, <span style="color:#a31515">&#34;a&#34;</span>) <span style="color:#00f">as</span> fp: </span></span><span style="display:flex;"><span> fp.write(log_line) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>start_time = time.time() </span></span><span style="display:flex;"><span>conn.close() </span></span><span style="display:flex;"><span>end_time = time.time() </span></span><span style="display:flex;"><span>result_time = CLOSE = end_time - start_time </span></span><span style="display:flex;"><span>print(<span style="color:#a31515">&#34;CLOSE: </span><span style="color:#a31515">%g</span><span style="color:#a31515"> seconds&#34;</span> % (result_time)) </span></span></code></pre><p>You can download <a href="/posts/do-fuse/sqlite-benchmarks.tsv">raw result here</a>. And again, these results are done on a local block storage and do not represent capabilities of object storage. With my current approach and state of the test code these can not be done. I would need to make Python code much more robust and check locking etc.</p> <div id="sqlite-benchmarks"></div> <script> (function(){ var request = new XMLHttpRequest(); request.open("GET", "/posts/do-fuse/sqlite-benchmarks.tsv", true); request.onload = function() { if (request.status >= 200 && request.status < 400) { var payload = request.responseText.trim(); var tsv = payload.split("\n"); for (var i=0; i<tsv.length; i++) { tsv[i] = tsv[i].split("\t"); } var traces = []; var headers = tsv[0]; tsv.shift(); Array.prototype.forEach.call(headers, function(el, idx) { var x = []; var y = []; for (var j=0; j<tsv.length; j++) { x.push(j); y.push(parseFloat(tsv[j][idx].replace(",", "."))); } traces.push({ x: x, y: y, type: "scatter", name: el, line: { width: 1, shape: "spline" } }); }); var sqlite = Plotly.newPlot("sqlite-benchmarks", traces, { legend: {"orientation": "h"}, height: 400, margin: { l: 50, r: 0, b: 20, t: 30, pad: 0 }, yaxis: { title: "execution time in seconds", titlefont: { size: 12 } } }); } else { } }; request.onerror = function() { }; request.send(null); })(); </script> <h2 id="can-storage-be-mounted-on-multiple-machines-at-the-same-time-and-be-writable">Can storage be mounted on multiple machines at the same time and be writable?</h2> <p>Well, this one didn't take long to test. And the answer is <strong>YES</strong>. I mounted space on both machines and measured same performance on both machines. But because file is downloaded before write and then uploaded on complete there could potentially be problems is another process is trying to access the same file.</p> <h2 id="observations-and-conslusion">Observations and conslusion</h2> <p>Using Spaces in this way makes it easier to access and manage files. But besides that you would need to write additional code to make this one play nice with you applications.</p> <p>Nevertheless, this was extremely simple to setup and use and this is just another excellent product in DigitalOcean product line. I found this exercise very valuable and am thinking about implementing some sort of mechanism for SQLite, so data can be stored on Spaces and accessed by many VM's. For a project where data doesn't need to be accessible in real-time and can have couple of minutes old data this would be very interesting. If any of you find this proposal interesting please write in a comment box below or shoot me an email and I will keep you posted.</p> Simple IOT application supported by real-time monitoring and data history https://mitjafelicijan.com/simple-iot-application.html Fri, 11 Aug 2017 12:00:00 +0200 https://mitjafelicijan.com/simple-iot-application.html Initial thoughtsI have been developing these kind of application for the better part of my last5 years and people keep asking me how to approach developing such applicationand I will give a try explaining it here. <h2 id="initial-thoughts">Initial thoughts</h2> <p>I have been developing these kind of application for the better part of my last 5 years and people keep asking me how to approach developing such application and I will give a try explaining it here.</p> <p>IOT applications are really no different than any other kind of applications. We have data that needs to be collected and visualized in some form of tables or charts. The main difference here is that most of the times these data is collected by some kind of device foreign to developer that mainly operates in web domain. But fear not, it's not that different than writing some JavaScript.</p> <p>There are many devices able to transmit data via wireless or wired network by default but for the sake of example we will be using commonly known Arduino with wireless module already on the board → <a href="https://store.arduino.cc/arduino-mkr1000">Arduino MKR1000</a>.</p> <p>In order to make this little project as accessible to others as possible I will try to make it as inexpensive as possible. And by this I mean that I will avoid using hosted virtual servers and will be using my own laptop as a server. But you must buy Arduino MKR1000 to follow steps below. But if you would want to deploy this software I would suggest using <a href="https://www.digitalocean.com">DigitalOcean</a> → smallest VPS is only per month making this one of the most affordable option out there. Please notice that this software will not run on stock web hosting that only supports LAMP (Linux, Apache, MySQL, and PHP).</p> <p>But before we begin please take notice that this is strictly experimental code and not well optimized and there are much better ways in handling some aspects of the application but that requires much deeper knowledge of technology that is not needed for an example like this.</p> <p><strong>Development steps</strong></p> <ol> <li>Simple Python API that will receive and store incoming data.</li> <li>Prototype C++ code that will read &quot;sensor data&quot; and transmit it to API.</li> <li>Data visualization with charts → extends Python web application.</li> </ol> <p>Step 1. and 3. will share the same web application. One route will be dedicated to API and another to serving HTML with chart.</p> <p>Schema below represents what we will try to achieve and how different parts correlates to each other.</p> <figure> <img src="/posts/iot-application/simple-iot-application-overview.svg" alt="Overview" /> </figure> <h2 id="simple-python-api">Simple Python API</h2> <p>I have always been a fan of simplicity so we will be using <a href="https://bottlepy.org/docs/dev/">Bottle: Python Web Framework</a>. It is a single file web framework that seriously simplifies working with routes, templating and has built-in web server that satisfies our need in this case.</p> <p>First we need to install bottle package. This can be done by downloading <code>bottle.py</code> and placing it in the root of your application or by using pip software <code>pip install bottle --user</code>.</p> <p>If you are using Linux or MacOS then Python is already installed. If you will try to test this on Windows please install <a href="https://www.python.org/downloads/windows/">Python for Windows</a>. There may be some problems with path when you will try to launch <code>python webapp.py</code> so please take care of this before you continue.</p> <h3 id="basic-web-application">Basic web application</h3> <p>Most basic bottle application is quite simple. Paste code below in <code>webapp.py</code> file and save.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># -*- coding: utf-8 -*-</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> bottle </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># initializing bottle app</span> </span></span><span style="display:flex;"><span>app = bottle.Bottle() </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># triggered when / is accessed from browser</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># only accepts GET → no POST allowed</span> </span></span><span style="display:flex;"><span>@app.route(<span style="color:#a31515">&#34;/&#34;</span>, method=[<span style="color:#a31515">&#34;GET&#34;</span>]) </span></span><span style="display:flex;"><span><span style="color:#00f">def</span> route_default(): </span></span><span style="display:flex;"><span> <span style="color:#00f">return</span> <span style="color:#a31515">&#34;howdy from python&#34;</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># starting server on http://0.0.0.0:5000</span> </span></span><span style="display:flex;"><span><span style="color:#00f">if</span> __name__ == <span style="color:#a31515">&#34;__main__&#34;</span>: </span></span><span style="display:flex;"><span> bottle.run( </span></span><span style="display:flex;"><span> app = app, </span></span><span style="display:flex;"><span> host = <span style="color:#a31515">&#34;0.0.0.0&#34;</span>, </span></span><span style="display:flex;"><span> port = 5000, </span></span><span style="display:flex;"><span> debug = <span style="color:#00f">True</span>, </span></span><span style="display:flex;"><span> reloader = <span style="color:#00f">True</span>, </span></span><span style="display:flex;"><span> catchall = <span style="color:#00f">True</span>, </span></span><span style="display:flex;"><span> ) </span></span></code></pre><p>To run this simple application you should open command prompt or terminal on your machine and go to the folder containing your file and type <code>python webapp.py</code>. If everything goes ok then open your web browser and point it to <code>http://0.0.0.0:5000</code>.</p> <p>If you would like change the port of your application (like port 80) and not use root to run your app this will present a problem. The TCP/IP port numbers below 1024 are privileged ports → this is a security feature. So in order of simplicity and security use a port number above 1024 like I have used port 5000.</p> <p>If this fails at any time please fix it before you continue, because nothing below will work otherwise.</p> <p>We use 0.0.0.0 as default host so that this app is available over your local network. If you find your local ip <code>ifconfig</code> and try accessing this site with your phone (if on same network/router as your machine) this should work as well (example of such ip <code>http://192.168.1.15:5000</code>). This is a must have because Arduino will be accessing this application to send it's data.</p> <h3 id="web-application-security">Web application security</h3> <p>There is a lot to be said about security and is a topic of many books. Of course all this can not be written here but to just establish some basic security → you should always use SSL with your application. Some fantastic free certificates are available by <a href="https://letsencrypt.org">Let's Encrypt - Free SSL/TLS Certificates</a>. With SSL certificate installed you should then make use of HTTP headers and send your &quot;API key&quot; via a header. If your key is send via header then this key is encrypted by SSL and send encrypted over the network. Never send your api keys by GET parameter like <code>http://example.com/?api_key=somekeyvalue</code>. The problem that this kind of sending presents is that this key is visible in logs and by network sniffers.</p> <p>There is a fantastic article describing some aspects about security: <a href="https://www.keycdn.com/blog/web-application-security-best-practices/">11 Web Application Security Best Practices</a>. Please check it out.</p> <h3 id="simple-api-for-writing-data-points">Simple API for writing data-points</h3> <p>We will now be using boilerplate code from example above and extend it to be SQLite3 because it plays well with Python and can store quite large amount of able to write data received by API to local storage. For example use I will use data. I have been using it to collect gigabytes of data in a single database without any corruption or problems → your experience may vary.</p> <p>To avoid learning SQLite I will be using <a href="https://dataset.readthedocs.io/en/latest/index.html">Dataset: databases for lazy people</a>. This package abstracts SQL and simplifies writing and reading data from database. You should install this package with pip software <code>pip install dataset --user</code>.</p> <p>Because API will use POST method I will be testing if code works correctly by using <a href="https://chrome.google.com/webstore/detail/restlet-client-rest-api-t/aejoelaoggembcahagimdiliamlcdmfm">Restlet Client for Google Chrome</a>. This software also allows you to set headers → for basic security with API_KEY.</p> <p>To quickly generate passwords or API keys I usually use this nifty website <a href="https://randomkeygen.com/">RandomKeygen</a>.</p> <p>Copy and paste code below over your previous code in file <code>webapp.py</code>.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># -*- coding: utf-8 -*-</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> time </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> bottle </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> random </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> dataset </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># initializing bottle app</span> </span></span><span style="display:flex;"><span>app = bottle.Bottle() </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># connects to sqlite database</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># check_same_thread=False allows using it in multi-threaded mode</span> </span></span><span style="display:flex;"><span>app.config[<span style="color:#a31515">&#34;dsn&#34;</span>] = dataset.connect(<span style="color:#a31515">&#34;sqlite:///data.db?check_same_thread=False&#34;</span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># api key that will be used in Arduino code</span> </span></span><span style="display:flex;"><span>app.config[<span style="color:#a31515">&#34;api_key&#34;</span>] = <span style="color:#a31515">&#34;JtF2aUE5SGHfVJBCG5SH&#34;</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># triggered when /api is accessed from browser</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># only accepts POST → no GET allowed</span> </span></span><span style="display:flex;"><span>@app.route(<span style="color:#a31515">&#34;/api&#34;</span>, method=[<span style="color:#a31515">&#34;POST&#34;</span>]) </span></span><span style="display:flex;"><span><span style="color:#00f">def</span> route_default(): </span></span><span style="display:flex;"><span> status = 400 </span></span><span style="display:flex;"><span> ts = int(time.time()) <span style="color:#008000"># current timestamp</span> </span></span><span style="display:flex;"><span> value = bottle.request.body.read() <span style="color:#008000"># data from device</span> </span></span><span style="display:flex;"><span> api_key = bottle.request.get_header(<span style="color:#a31515">&#34;Api_Key&#34;</span>) <span style="color:#008000"># api key from header</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000"># outputs to console received data for debug reason</span> </span></span><span style="display:flex;"><span> print <span style="color:#a31515">&#34;&gt;&gt;&gt; </span><span style="color:#a31515">{}</span><span style="color:#a31515"> :: </span><span style="color:#a31515">{}</span><span style="color:#a31515">&#34;</span>.format(value, api_key) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000"># if api_key is correct and value is present</span> </span></span><span style="display:flex;"><span> <span style="color:#008000"># then writes attribute to point table</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">if</span> api_key == app.config[<span style="color:#a31515">&#34;api_key&#34;</span>] <span style="color:#00f">and</span> value: </span></span><span style="display:flex;"><span> app.config[<span style="color:#a31515">&#34;dsn&#34;</span>][<span style="color:#a31515">&#34;point&#34;</span>].insert(dict(ts=ts, value=value)) </span></span><span style="display:flex;"><span> status = 200 </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000"># we only need to return status</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">return</span> bottle.HTTPResponse(status=status, body=<span style="color:#a31515">&#34;&#34;</span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># starting server on http://0.0.0.0:5000</span> </span></span><span style="display:flex;"><span><span style="color:#00f">if</span> __name__ == <span style="color:#a31515">&#34;__main__&#34;</span>: </span></span><span style="display:flex;"><span> bottle.run( </span></span><span style="display:flex;"><span> app = app, </span></span><span style="display:flex;"><span> host = <span style="color:#a31515">&#34;0.0.0.0&#34;</span>, </span></span><span style="display:flex;"><span> port = 5000, </span></span><span style="display:flex;"><span> debug = <span style="color:#00f">True</span>, </span></span><span style="display:flex;"><span> reloader = <span style="color:#00f">True</span>, </span></span><span style="display:flex;"><span> catchall = <span style="color:#00f">True</span>, </span></span><span style="display:flex;"><span> ) </span></span></code></pre><p>To run this simply go to folder containing python file and run <code>python webapp.py</code> from terminal. If everything goes ok you should have simple API available via POST method on /api route.</p> <p>After testing the service with Restlet Client you should be able to view your data in a database file <code>data.db</code>.</p> <figure> <img src="/posts/iot-application/iot-rest-example.png" alt="REST settings example" /> </figure> <p>You can also check the contents of new database file by using desktop client for SQLite → <a href="http://sqlitebrowser.org/">DB Browser for SQLite</a>.</p> <figure> <img src="/posts/iot-application/iot-sqlite-db.png" alt="SQLite database example" /> </figure> <p>Table structure is as simple as it can be. We have ts (timestamp) and value (value from Arduino). As you can see timestamp is generated on API side. If you would happen to have atomic clock on Arduino it would be then better to generate and send timestamp with the value. This would be particularity useful if we would be collecting sensor data at a higher frequency and then sending this data in bulk to API.</p> <p>If you will deploy this app with uWSGI and multi-threaded, use DSN (Data Source Name) url with <code>?check_same_thread=False</code>.</p> <p>Ok, now that we have some sort of a working API with some basic security so unwanted people can not post data to your database can we proceed further and try to program Arduino to send data to API.</p> <h2 id="sending-data-to-api-with-arduino-mkr1000">Sending data to API with Arduino MKR1000</h2> <p>First of all you should have MKR1000 module and microUSB cable to proceed. If you have ever done any work with Arduino you should know that you also need <a href="https://www.arduino.cc/en/Main/Software">Arduino IDE</a>. On provided link you should be able to download and install IDE. Once that task is completed and you have successfully run blink example you should proceed to the next step.</p> <p>In order to use wireless capabilities of MKR1000 you need to first install <a href="https://www.arduino.cc/en/Reference/WiFi101">WiFi101 library</a> in Arduino IDE. Please check before you install, you may already have it installed.</p> <p>Code below is a working example that sends data to API. Before you try to test your code make sure you have run Python web application. Then change settings for wifi, api endpoint and api_key. If by some reason code bellow doesn't work for you please leave a comment and I'll try to help.</p> <p>Once you have opened IDE and copied this code try to compile and upload it. Then open &quot;Serial monitor&quot; to see if any output is presented by Arduino.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">#include</span> <span style="color:#00f">&lt;WiFi101.h&gt;</span><span style="color:#00f"> </span></span></span><span style="display:flex;"><span><span style="color:#00f"></span> </span></span><span style="display:flex;"><span><span style="color:#008000">// wifi settings </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span><span style="color:#2b91af">char</span> ssid[] = <span style="color:#a31515">&#34;ssid-name&#34;</span>; </span></span><span style="display:flex;"><span><span style="color:#2b91af">char</span> pass[] = <span style="color:#a31515">&#34;ssid-password&#34;</span>; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000">// api server enpoint </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span><span style="color:#2b91af">char</span> server[] = <span style="color:#a31515">&#34;192.168.6.22&#34;</span>; </span></span><span style="display:flex;"><span><span style="color:#2b91af">int</span> port = 5000; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000">// api key that must be the same as the one in Python code </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span>String api_key = <span style="color:#a31515">&#34;JtF2aUE5SGHfVJBCG5SH&#34;</span>; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000">// frequency data is sent in ms - every 5 seconds </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span><span style="color:#2b91af">int</span> timeout = 1000 * 5; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#2b91af">int</span> status = WL_IDLE_STATUS; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#2b91af">void</span> setup() { </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">// initialize serial and wait for port to open: </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> Serial.begin(9600); </span></span><span style="display:flex;"><span> delay(1000); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">// check for the presence of the shield </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> <span style="color:#00f">if</span> (WiFi.status() == WL_NO_SHIELD) { </span></span><span style="display:flex;"><span> Serial.println(<span style="color:#a31515">&#34;WiFi shield not present&#34;</span>); </span></span><span style="display:flex;"><span> <span style="color:#00f">while</span> (true); </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">// attempt to connect to wifi network </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> <span style="color:#00f">while</span> (status != WL_CONNECTED) { </span></span><span style="display:flex;"><span> Serial.print(<span style="color:#a31515">&#34;Attempting to connect to SSID: &#34;</span>); </span></span><span style="display:flex;"><span> Serial.println(ssid); </span></span><span style="display:flex;"><span> status = WiFi.begin(ssid, pass); </span></span><span style="display:flex;"><span> <span style="color:#008000">// wait 10 seconds for connection </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> delay(10000); </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">// output wifi status to serial monitor </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> Serial.print(<span style="color:#a31515">&#34;SSID: &#34;</span>); </span></span><span style="display:flex;"><span> Serial.println(WiFi.SSID()); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> IPAddress ip = WiFi.localIP(); </span></span><span style="display:flex;"><span> Serial.print(<span style="color:#a31515">&#34;IP Address: &#34;</span>); </span></span><span style="display:flex;"><span> Serial.println(ip); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#2b91af">long</span> rssi = WiFi.RSSI(); </span></span><span style="display:flex;"><span> Serial.print(<span style="color:#a31515">&#34;signal strength (RSSI):&#34;</span>); </span></span><span style="display:flex;"><span> Serial.print(rssi); </span></span><span style="display:flex;"><span> Serial.println(<span style="color:#a31515">&#34; dBm&#34;</span>); </span></span><span style="display:flex;"><span>} </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#2b91af">void</span> loop() { </span></span><span style="display:flex;"><span> WiFiClient client; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">if</span> (client.connect(server, port)) { </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">// I use random number generator for this example </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> <span style="color:#008000">// but you can use analog or digital inputs from arduino </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> String content = String(random(1000)); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> client.println(<span style="color:#a31515">&#34;POST /api HTTP/1.1&#34;</span>); </span></span><span style="display:flex;"><span> client.println(<span style="color:#a31515">&#34;Connection: close&#34;</span>); </span></span><span style="display:flex;"><span> client.println(<span style="color:#a31515">&#34;Api-Key: &#34;</span> + api_key); </span></span><span style="display:flex;"><span> client.println(<span style="color:#a31515">&#34;Content-Length: &#34;</span> + String(content.length())); </span></span><span style="display:flex;"><span> client.println(); </span></span><span style="display:flex;"><span> client.println(content); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> delay(100); </span></span><span style="display:flex;"><span> client.stop(); </span></span><span style="display:flex;"><span> Serial.println(<span style="color:#a31515">&#34;Data sent successfully ...&#34;</span>); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> } <span style="color:#00f">else</span> { </span></span><span style="display:flex;"><span> Serial.println(<span style="color:#a31515">&#34;Problem sending data ...&#34;</span>); </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">// waits for x seconds and continue looping </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> delay(timeout); </span></span><span style="display:flex;"><span>} </span></span></code></pre><p>As seen from example you can notice that Arduino is generating random integer between [ 0 .. 1000 ]. You can easily replace this with a temperature sensor or any other kind of sensor.</p> <p>Now that we have API under the hood and Arduino is sending demo data we can now focus on data visualization.</p> <h2 id="data-visualization">Data visualization</h2> <p>Before we continue we should examine our project folder structure. Currently we only have two files in our project:</p> <p><em>simple-iot-app/</em></p> <ul> <li><em>webapp.py</em></li> <li><em>data.db</em></li> </ul> <p>We will now add HTML template that will contain CSS and JavaScript code inline for the simplicity reason. And for the bottle framework to be able to scan root application folder for templates we will add <code>bottle.TEMPLATE_PATH.insert(0, &quot;./&quot;)</code> in <code>webapp.py</code>. By default bottle framework uses <code>views/</code> subfolder to store templates. This is not the ideal situation and if you will use bottle to develop web applications you should use native behavior and store templates in it's predefined folder. But for the sake of example we will over-ride this. Be careful to fully replace your code with new code that is provided below. Avoid partially replacing code in file :) Also new code for reading data-points is provided in Python example below.</p> <p>First we add new route to our web application. It should be trigger when browser hits root of application <code>http://0.0.0.0:5000/</code>. This route will do nothing more than render <code>frontend.html</code> template. This is done by <code>return bottle.template(&quot;frontend.html&quot;)</code>. Check code below to further examine how exactly this is done.</p> <p>Now we will expand <code>/api</code> route and use different methods to write or read data-points. For writing data-point we will use POST method and for reading points we will use GET method. GET method will return JSON object with latest readings and historical data.</p> <p>There is a fantastic JavaScript library for plotting time-series charts called <a href="https://www.metricsgraphicsjs.org">MetricsGraphics.js</a> that is based on <a href="https://d3js.org/">D3.js</a> library for visualizing data.</p> <p>Data schema required by MetricsGraphics.js → to achieve this we need to transform data from database into this format:</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>[ </span></span><span style="display:flex;"><span> { </span></span><span style="display:flex;"><span> &#34;date&#34;: <span style="color:#a31515">&#34;2017-08-11 01:07:20&#34;</span>, </span></span><span style="display:flex;"><span> &#34;value&#34;: 933 </span></span><span style="display:flex;"><span> }, </span></span><span style="display:flex;"><span> { </span></span><span style="display:flex;"><span> &#34;date&#34;: <span style="color:#a31515">&#34;2017-08-11 01:07:30&#34;</span>, </span></span><span style="display:flex;"><span> &#34;value&#34;: 743 </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span>] </span></span></code></pre><p>Web application is now complete and we only need <code>frontend.html</code> that we will develop now. If you would try to start web app now and go to root app this will return error because we don't have frontend.html yet.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># -*- coding: utf-8 -*-</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> time </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> bottle </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> json </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> datetime </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> random </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> dataset </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># initializing bottle app</span> </span></span><span style="display:flex;"><span>app = bottle.Bottle() </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># adds root directory as template folder</span> </span></span><span style="display:flex;"><span>bottle.TEMPLATE_PATH.insert(0, <span style="color:#a31515">&#34;./&#34;</span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># connects to sqlite database</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># check_same_thread=False allows using it in multi-threaded mode</span> </span></span><span style="display:flex;"><span>app.config[<span style="color:#a31515">&#34;db&#34;</span>] = dataset.connect(<span style="color:#a31515">&#34;sqlite:///data.db?check_same_thread=False&#34;</span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># api key that will be used in Arduino code</span> </span></span><span style="display:flex;"><span>app.config[<span style="color:#a31515">&#34;api_key&#34;</span>] = <span style="color:#a31515">&#34;JtF2aUE5SGHfVJBCG5SH&#34;</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># triggered when / is accessed from browser</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># only accepts GET → no POST allowed</span> </span></span><span style="display:flex;"><span>@app.route(<span style="color:#a31515">&#34;/&#34;</span>, method=[<span style="color:#a31515">&#34;GET&#34;</span>]) </span></span><span style="display:flex;"><span><span style="color:#00f">def</span> route_default(): </span></span><span style="display:flex;"><span> <span style="color:#00f">return</span> bottle.template(<span style="color:#a31515">&#34;frontend.html&#34;</span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># triggered when /api is accessed from browser</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># accepts POST and GET</span> </span></span><span style="display:flex;"><span>@app.route(<span style="color:#a31515">&#34;/api&#34;</span>, method=[<span style="color:#a31515">&#34;GET&#34;</span>, <span style="color:#a31515">&#34;POST&#34;</span>]) </span></span><span style="display:flex;"><span><span style="color:#00f">def</span> route_default(): </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000"># if method is POST then we write datapoint</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">if</span> bottle.request.method == <span style="color:#a31515">&#34;POST&#34;</span>: </span></span><span style="display:flex;"><span> status = 400 </span></span><span style="display:flex;"><span> ts = int(time.time()) <span style="color:#008000"># current timestamp</span> </span></span><span style="display:flex;"><span> value = bottle.request.body.read() <span style="color:#008000"># data from device</span> </span></span><span style="display:flex;"><span> api_key = bottle.request.get_header(<span style="color:#a31515">&#34;Api-Key&#34;</span>) <span style="color:#008000"># api key from header</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000"># outputs to console recieved data for debug reason</span> </span></span><span style="display:flex;"><span> print <span style="color:#a31515">&#34;&gt;&gt;&gt; </span><span style="color:#a31515">{}</span><span style="color:#a31515"> :: </span><span style="color:#a31515">{}</span><span style="color:#a31515">&#34;</span>.format(value, api_key) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000"># if api_key is correct and value is present</span> </span></span><span style="display:flex;"><span> <span style="color:#008000"># then writes attribute to point table</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">if</span> api_key == app.config[<span style="color:#a31515">&#34;api_key&#34;</span>] <span style="color:#00f">and</span> value: </span></span><span style="display:flex;"><span> app.config[<span style="color:#a31515">&#34;db&#34;</span>][<span style="color:#a31515">&#34;point&#34;</span>].insert(dict(ts=ts, value=value)) </span></span><span style="display:flex;"><span> status = 200 </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000"># we only need to return status</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">return</span> bottle.HTTPResponse(status=status, body=<span style="color:#a31515">&#34;&#34;</span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000"># if method is GET then we read datapoint</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">else</span>: </span></span><span style="display:flex;"><span> response = [] </span></span><span style="display:flex;"><span> datapoints = app.config[<span style="color:#a31515">&#34;db&#34;</span>][<span style="color:#a31515">&#34;point&#34;</span>].all() </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#00f">for</span> point <span style="color:#00f">in</span> datapoints: </span></span><span style="display:flex;"><span> response.append({ </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#34;date&#34;</span>: datetime.datetime.fromtimestamp(int(point[<span style="color:#a31515">&#34;ts&#34;</span>])).strftime(<span style="color:#a31515">&#34;%Y-%m-</span><span style="color:#a31515">%d</span><span style="color:#a31515"> %H:%M:%S&#34;</span>), </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#34;value&#34;</span>: point[<span style="color:#a31515">&#34;value&#34;</span>] </span></span><span style="display:flex;"><span> }) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> bottle.response.content_type = <span style="color:#a31515">&#34;application/json&#34;</span> </span></span><span style="display:flex;"><span> <span style="color:#00f">return</span> json.dumps(response) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># starting server on http://0.0.0.0:5000</span> </span></span><span style="display:flex;"><span><span style="color:#00f">if</span> __name__ == <span style="color:#a31515">&#34;__main__&#34;</span>: </span></span><span style="display:flex;"><span> bottle.run( </span></span><span style="display:flex;"><span> app = app, </span></span><span style="display:flex;"><span> host = <span style="color:#a31515">&#34;0.0.0.0&#34;</span>, </span></span><span style="display:flex;"><span> port = 5000, </span></span><span style="display:flex;"><span> debug = <span style="color:#00f">True</span>, </span></span><span style="display:flex;"><span> reloader = <span style="color:#00f">True</span>, </span></span><span style="display:flex;"><span> catchall = <span style="color:#00f">True</span>, </span></span><span style="display:flex;"><span> ) </span></span></code></pre><p>And now finally we can implement <code>frontend.html</code>. Create file with this name and copy code below. When you are done you can start web application. Steps for this part are listed below the code.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">&lt;!DOCTYPE html&gt;</span> </span></span><span style="display:flex;"><span>&lt;html&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;head&gt; </span></span><span style="display:flex;"><span> &lt;meta charset=<span style="color:#a31515">&#34;utf-8&#34;</span>&gt; </span></span><span style="display:flex;"><span> &lt;title&gt;Simple IOT application&lt;/title&gt; </span></span><span style="display:flex;"><span> &lt;/head&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;body&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;h1&gt;Simple IOT application&lt;/h1&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;div class=<span style="color:#a31515">&#34;chart-placeholder&#34;</span>&gt; </span></span><span style="display:flex;"><span> &lt;div id=<span style="color:#a31515">&#34;chart&#34;</span>&gt;&lt;/div&gt; </span></span><span style="display:flex;"><span> &lt;/div&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">&lt;!-- application main script --&gt;</span> </span></span><span style="display:flex;"><span> &lt;script src=<span style="color:#a31515">&#34;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js&#34;</span>&gt;&lt;/script&gt; </span></span><span style="display:flex;"><span> &lt;script src=<span style="color:#a31515">&#34;https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js&#34;</span>&gt;&lt;/script&gt; </span></span><span style="display:flex;"><span> &lt;script src=<span style="color:#a31515">&#34;https://cdnjs.cloudflare.com/ajax/libs/metrics-graphics/2.11.0/metricsgraphics.min.js&#34;</span>&gt;&lt;/script&gt; </span></span><span style="display:flex;"><span> &lt;script&gt; </span></span><span style="display:flex;"><span> <span style="color:#00f">function</span> fetch_and_render() { </span></span><span style="display:flex;"><span> d3.json(<span style="color:#a31515">&#34;/api&#34;</span>, <span style="color:#00f">function</span>(data) { </span></span><span style="display:flex;"><span> data = MG.convert.date(data, <span style="color:#a31515">&#34;date&#34;</span>, <span style="color:#a31515">&#34;%Y-%m-%d %H:%M:%S&#34;</span>); </span></span><span style="display:flex;"><span> MG.data_graphic({ </span></span><span style="display:flex;"><span> data: data, </span></span><span style="display:flex;"><span> chart_type: <span style="color:#a31515">&#34;line&#34;</span>, </span></span><span style="display:flex;"><span> full_width: <span style="color:#00f">true</span>, </span></span><span style="display:flex;"><span> height: 270, </span></span><span style="display:flex;"><span> target: document.getElementById(<span style="color:#a31515">&#34;chart&#34;</span>), </span></span><span style="display:flex;"><span> x_accessor: <span style="color:#a31515">&#34;date&#34;</span>, </span></span><span style="display:flex;"><span> y_accessor: <span style="color:#a31515">&#34;value&#34;</span> </span></span><span style="display:flex;"><span> }); </span></span><span style="display:flex;"><span> }); </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> window.onload = <span style="color:#00f">function</span>() { </span></span><span style="display:flex;"><span> <span style="color:#008000">// initial call for rendering </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> fetch_and_render(); </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">// updates chart every 5 seconds </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span> setInterval(<span style="color:#00f">function</span>() { </span></span><span style="display:flex;"><span> fetch_and_render(); </span></span><span style="display:flex;"><span> }, 5000); </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> &lt;/script&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> <span style="color:#008000">&lt;!-- application styles --&gt;</span> </span></span><span style="display:flex;"><span> &lt;style&gt; </span></span><span style="display:flex;"><span> body { </span></span><span style="display:flex;"><span> <span style="color:#00f">font</span>: 13<span style="color:#2b91af">px</span> <span style="color:#00f">sans-serif</span>; </span></span><span style="display:flex;"><span> <span style="color:#00f">padding</span>: 20<span style="color:#2b91af">px</span> 50<span style="color:#2b91af">px</span>; </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> .<span style="color:#2b91af">chart-placeholder</span> { </span></span><span style="display:flex;"><span> <span style="color:#00f">border</span>: 2<span style="color:#2b91af">px</span> <span style="color:#00f">solid</span> #ccc; </span></span><span style="display:flex;"><span> <span style="color:#00f">width</span>: 100<span style="color:#2b91af">%</span>; </span></span><span style="display:flex;"><span> <span style="color:#00f">user-select</span>: <span style="color:#00f">none</span>; </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> <span style="color:#008000">/* chart styles */</span> </span></span><span style="display:flex;"><span> .<span style="color:#2b91af">mg-line1-color</span> { </span></span><span style="display:flex;"><span> stroke: <span style="color:#00f">red</span>; </span></span><span style="display:flex;"><span> stroke-width: 2; </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> .<span style="color:#2b91af">mg-main-area</span>, .<span style="color:#2b91af">mg-main-line</span> { </span></span><span style="display:flex;"><span> fill: #fff; </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> .<span style="color:#2b91af">mg-x-axis</span> line, .<span style="color:#2b91af">mg-y-axis</span> line { </span></span><span style="display:flex;"><span> stroke: #b3b2b2; </span></span><span style="display:flex;"><span> stroke-width: 1<span style="color:#2b91af">px</span>; </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> &lt;/style&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;/body&gt; </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>&lt;/html&gt; </span></span></code></pre><p>Now the folder structure should look like:</p> <p><em>simple-iot-app/</em></p> <ul> <li><em>webapp.py</em></li> <li><em>data.db</em></li> <li><em>frontend.html</em></li> </ul> <p>Ok, lets now start application and start feeding it data.</p> <ol> <li><code>python webapp.py</code></li> <li>connect Arduino MKR1000 to power source</li> <li>open browser and go to <code>http://0.0.0.0:5000</code></li> </ol> <p>If everything goes well you should be seeing new data-points rendered on chart every 5 seconds.</p> <p>If you navigate to <code>http://0.0.0.0:5000</code> you should see rendered chart as shown on picture below.</p> <figure> <img src="/posts/iot-application/iot-app-output.png" alt="Application output" /> </figure> <p>Complete application with all the code is available for <a href="/posts/iot-application/simple-iot-application.zip">download</a>.</p> <h2 id="conclusion">Conclusion</h2> <p>I hope this clarifies some aspects of IOT application development. Of course this is a minimal example and is far from what can be done in real life with some further dive into other technologies.</p> <p>If you would like to continue exploring IOT world here are some interesting resources for you to examine:</p> <ul> <li><a href="https://www.allaboutcircuits.com/projects/reading-sensors-with-an-arduino/">Reading Sensors with an Arduino</a></li> <li><a href="http://www.hivemq.com/blog/how-to-get-started-with-mqtt">MQTT 101 – How to Get Started with the lightweight IoT Protocol</a></li> <li><a href="https://www.html5rocks.com/en/tutorials/eventsource/basics/">Stream Updates with Server-Sent Events</a></li> <li><a href="http://www.tutorialspoint.com/internet_of_things/">Internet of Things (IoT) Tutorials</a></li> </ul> <p>Any comment or additional ideas are welcomed in comments below.</p> Profiling Python web applications with visual tools https://mitjafelicijan.com/profiling-python-web-applications-with-visual-tools.html Fri, 21 Apr 2017 12:00:00 +0200 https://mitjafelicijan.com/profiling-python-web-applications-with-visual-tools.html I have been profiling my software with KCachegrind for a long time now and I wasmissing this option when I am developing API&#39;s or other web services. <p>I have been profiling my software with KCachegrind for a long time now and I was missing this option when I am developing API's or other web services. I always knew that this is possible but never really took the time and dive into it.</p> <p>Before we begin there are some requirements. We will need to:</p> <ul> <li>implement <a href="https://docs.python.org/2/library/profile.html#module-cProfile">cProfile</a> into our web app,</li> <li>convert output to <a href="http://valgrind.org/docs/manual/cl-manual.html">callgrind</a> format with <a href="https://pypi.python.org/pypi/pyprof2calltree/">pyprof2calltree</a>,</li> <li>visualize data with <a href="http://kcachegrind.sourceforge.net/html/Home.html">KCachegrind</a> or <a href="http://www.profilingviewer.com/">Profiling Viewer</a>.</li> </ul> <p>If you are using MacOS you should check out <a href="http://www.profilingviewer.com/">Profiling Viewer</a> or <a href="http://www.maccallgrind.com/">MacCallGrind</a>.</p> <figure> <img src="/posts/python-profiling/kcachegrind.png" alt="KCachegrind" /> </figure> <p>We will be dividing this post into two main categories:</p> <ul> <li>writing simple web-service,</li> <li>visualize profile of this web-service.</li> </ul> <h2 id="simple-web-service">Simple web-service</h2> <p>Let's use virtualenv so we won't pollute our base system. If you don't have virtualenv installed on your system you can install it with pip command.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># let&#39;s install virtualenv globally</span> </span></span><span style="display:flex;"><span>$ sudo pip install virtualenv </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># let&#39;s also install pyprof2calltree globally</span> </span></span><span style="display:flex;"><span>$ sudo pip install pyprof2calltree </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># now we create project</span> </span></span><span style="display:flex;"><span>$ mkdir demo-project </span></span><span style="display:flex;"><span>$ cd demo-project/ </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># now let&#39;s create folder where we will store profiles</span> </span></span><span style="display:flex;"><span>$ mkdir prof </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># now we create empty virtualenv in venv/ folder</span> </span></span><span style="display:flex;"><span>$ virtualenv --no-site-packages venv </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># we now need to activate virtualenv</span> </span></span><span style="display:flex;"><span>$ source venv/bin/activate </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># you can check if virtualenv was correctly initialized by</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># checking where your python interpreter is located</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># if command bellow points to your created directory and not some</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># system dir like /usr/bin/python then everything is fine</span> </span></span><span style="display:flex;"><span>$ which python </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># we can check now if all is good ➜ if ok couple of</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># lines will be displayed</span> </span></span><span style="display:flex;"><span>$ pip freeze </span></span><span style="display:flex;"><span><span style="color:#008000"># appdirs==1.4.3</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># packaging==16.8</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># pyparsing==2.2.0</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># six==1.10.0</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># now we are ready to install bottlepy ➜ web micro-framework</span> </span></span><span style="display:flex;"><span>$ pip install bottle </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># you can deactivate virtualenv but you will then go</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># under system domain ➜ for now don&#39;t deactivate</span> </span></span><span style="display:flex;"><span>$ deactivate </span></span></code></pre><p>We are now ready to write simple web service. Let's create file app.py and paste code bellow in this newly created file.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># -*- coding: utf-8 -*-</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> bottle </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> random </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> cProfile </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>app = bottle.Bottle() </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># this function is a decorator and encapsulates function</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># and performs profiling and then saves it to subfolder</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># prof/function-name.prof</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># in our example only awesome_random_number function will</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># be profiled because it has do_cprofile defined</span> </span></span><span style="display:flex;"><span><span style="color:#00f">def</span> do_cprofile(func): </span></span><span style="display:flex;"><span> <span style="color:#00f">def</span> profiled_func(*args, **kwargs): </span></span><span style="display:flex;"><span> profile = cProfile.Profile() </span></span><span style="display:flex;"><span> <span style="color:#00f">try</span>: </span></span><span style="display:flex;"><span> profile.enable() </span></span><span style="display:flex;"><span> result = func(*args, **kwargs) </span></span><span style="display:flex;"><span> profile.disable() </span></span><span style="display:flex;"><span> <span style="color:#00f">return</span> result </span></span><span style="display:flex;"><span> <span style="color:#00f">finally</span>: </span></span><span style="display:flex;"><span> profile.dump_stats(<span style="color:#a31515">&#34;prof/&#34;</span> + str(func.__name__) + <span style="color:#a31515">&#34;.prof&#34;</span>) </span></span><span style="display:flex;"><span> <span style="color:#00f">return</span> profiled_func </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># we use profiling over specific function with including</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># @do_cprofile above function declaration</span> </span></span><span style="display:flex;"><span>@app.route(<span style="color:#a31515">&#34;/&#34;</span>) </span></span><span style="display:flex;"><span>@do_cprofile </span></span><span style="display:flex;"><span><span style="color:#00f">def</span> awesome_random_number(): </span></span><span style="display:flex;"><span> awesome_random_number = random.randint(0, 100) </span></span><span style="display:flex;"><span> <span style="color:#00f">return</span> <span style="color:#a31515">&#34;awesome random number is &#34;</span> + str(awesome_random_number) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span>@app.route(<span style="color:#a31515">&#34;/test&#34;</span>) </span></span><span style="display:flex;"><span><span style="color:#00f">def</span> test(): </span></span><span style="display:flex;"><span> <span style="color:#00f">return</span> <span style="color:#a31515">&#34;dummy test&#34;</span> </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">if</span> __name__ == <span style="color:#a31515">&#39;__main__&#39;</span>: </span></span><span style="display:flex;"><span> bottle.run( </span></span><span style="display:flex;"><span> app = app, </span></span><span style="display:flex;"><span> host = <span style="color:#a31515">&#34;0.0.0.0&#34;</span>, </span></span><span style="display:flex;"><span> port = 4000 </span></span><span style="display:flex;"><span> ) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># run with &#39;python app.py&#39;</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># open browser &#39;http://0.0.0.0:4000&#39;</span> </span></span></code></pre><p>When browser hits awesome_random_number() function profile is created in prof/ subfolder.</p> <h2 id="visualize-profile">Visualize profile</h2> <p>Now let's create callgrind format from this cProfile output.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>$ cd prof/ </span></span><span style="display:flex;"><span>$ pyprof2calltree -i awesome_random_number.prof </span></span><span style="display:flex;"><span><span style="color:#008000"># this creates &#39;awesome_random_number.prof.log&#39; file in the same folder</span> </span></span></code></pre><p>This file can be opened with visualizing tools listed above. In this case we will be using Profilling Viewer under MacOS. You can open image in new tab. As you can see from this example there is hierarchy of execution order of your code.</p> <figure> <img src="/posts/python-profiling/profiling-viewer.png" alt="Profilling Viewer" /> </figure> <blockquote> <p>Make sure you convert output of the cProfile output every time you want to refresh and take a look at your possible optimizations because cProfile updates .prof file every time browser hits the function.</p> </blockquote> <p>This is just a simple example but when you are developing real-life applications this can be very illuminating, especially to see which parts of your code are bottlenecks and need to be optimized.</p> <h2 id="update-2017-04-22">Update 2017-04-22</h2> <p>Reddit user <a href="https://www.reddit.com/user/mvt">mvt</a> also recommended this awesome web based profile visualizer <a href="https://jiffyclub.github.io/snakeviz/">SnakeViz</a> that directly takes output from <a href="https://docs.python.org/2/library/profile.html#module-cProfile">cProfile</a> module.</p> <div class="reddit-embed" data-embed-media="www.redditmedia.com" data-embed-parent="false" data-embed-live="false" data-embed-uuid="583880c1-002e-41ed-a373-020a0ef2cff9" data-embed-created="2017-04-22T19:46:54.810Z"><a href="https://www.reddit.com/r/Python/comments/66v373/profiling_python_web_applications_with_visual/dgljhsb/">Comment</a> from discussion <a href="https://www.reddit.com/r/Python/comments/66v373/profiling_python_web_applications_with_visual/">Profiling Python web applications with visual tools</a>.</div><script async src="https://www.redditstatic.com/comment-embed.js"></script> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># let&#39;s install it globally as well</span> </span></span><span style="display:flex;"><span>$ sudo pip install snakeviz </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># now let&#39;s visualize</span> </span></span><span style="display:flex;"><span>$ cd prof/ </span></span><span style="display:flex;"><span>$ snakeviz awesome_random_number.prof </span></span><span style="display:flex;"><span><span style="color:#008000"># this automatically opens browser window and</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># shows visualized profile</span> </span></span></code></pre><figure> <img src="/posts/python-profiling/snakeviz.png" alt="SnakeViz" /> </figure> <p>Reddit user <a href="https://www.reddit.com/user/ccharles">ccharles</a> suggested a better way for installing pip software by targeting user level instead of using sudo.</p> <div class="reddit-embed" data-embed-media="www.redditmedia.com" data-embed-parent="false" data-embed-live="false" data-embed-uuid="f4f0459e-684d-441e-bebe-eb49b2f0a31d" data-embed-created="2017-04-22T19:46:10.874Z"><a href="https://www.reddit.com/r/Python/comments/66v373/profiling_python_web_applications_with_visual/dglpzkx/">Comment</a> from discussion <a href="https://www.reddit.com/r/Python/comments/66v373/profiling_python_web_applications_with_visual/">Profiling Python web applications with visual tools</a>.</div><script async src="https://www.redditstatic.com/comment-embed.js"></script> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># now we need to add this path to our $PATH variable</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># we do this my adding this line at the end of your</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># ~/.bashrc file</span> </span></span><span style="display:flex;"><span>PATH=$PATH:$HOME/.local/bin/ </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># in order to use this new configuration you can close</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># and reopen terminal or reload .bashrc file</span> </span></span><span style="display:flex;"><span>$ source ~/.bashrc </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># now let&#39;s test if new directory is present in $PATH</span> </span></span><span style="display:flex;"><span>$ echo $PATH </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># now we can install on user level by adding --user</span> </span></span><span style="display:flex;"><span><span style="color:#008000"># without use of sudo</span> </span></span><span style="display:flex;"><span>$ pip install snakeviz --user </span></span></code></pre><p>Or as suggested by <a href="https://www.reddit.com/user/mvt">mvt</a> you can use <a href="https://github.com/mitsuhiko/pipsi">pipsi</a>.</p> What I've learned developing ad server https://mitjafelicijan.com/what-i-ve-learned-developing-ad-server.html Mon, 17 Apr 2017 12:00:00 +0200 https://mitjafelicijan.com/what-i-ve-learned-developing-ad-server.html For the past year and half I have been developing native advertising server thatcontextually matches ads and displays them in different template forms onvariety of websites. <p>For the past year and half I have been developing native advertising server that contextually matches ads and displays them in different template forms on variety of websites. This project grew from serving thousands of ads per day to millions.</p> <p>The system is made from couple of core components:</p> <ul> <li>API for serving ads,</li> <li>Utils - cronjobs and queue management tools,</li> <li>Dashboard UI.</li> </ul> <p>Initial release was using <a href="https://www.mongodb.com/">MongoDB</a> for full-text search but was later replaced by <a href="https://www.elastic.co/">Elasticsearch</a> for better CPU utilization and better search performance. This provided us with many amazing functionalities of <a href="https://www.elastic.co/">Elasticsearch</a>. You should check it out if you do any search related operations.</p> <p>Because the premise of the server is to provide native ad experience, they are rendered on the client side via simple templating engine. This ensures that ads can be displayed number of different ways based on the visual style of the page. And this makes JavaScript client library quite complex.</p> <p>So now that you know basic information about the product lets get into the lessons we learned.</p> <h2 id="aggregate-everything">Aggregate everything</h2> <p>After beta version was released everything (impressions, clicks, etc) was written in nanosecond resolution in the database. At that time we were using <a href="https://www.postgresql.org/">PostgreSQL</a> and database quickly grew way above 200GB in disk space. And that was problematic. Statistics took disturbingly long time to aggregate. Also using indexes on stats table in database was no help after we reached 500 million datapoints.</p> <blockquote> <p>There is a marketing product information and there is real life experience. And the tend to be quite the opposite.</p> </blockquote> <p>This was the reason that now everything is aggregated on daily basis and this data is then fed to Elastic in form of daily summary. With this we achieved we can now track many more dimensions such as zone, channel and platform information. And with this information we can now adapt occurrences of ads on specific places more precisely.</p> <p>We have also adapted <a href="https://redis.io/">Redis</a> as a full-time citizen in our stack. Because Redis also stores information on a local disk we have some sort of backup if server would accidentally suffer some failure.</p> <p>All the real-time statistics for ad serving and redirecting is presented as counters in Redis instance and daily extracted and pushed to Elastic.</p> <h2 id="measure-everything">Measure everything</h2> <p>The thing about software is that we really don't know how well it is performing under load until such load is presented. When testing locally everything is fine but when on production things tend to fall apart.</p> <p>As a solution for this we are measuring everything we can. Function execution time (by encapsulating functions with timers), server performance (cpu, memory, disk, etc), Nginx and <a href="https://uwsgi-docs.readthedocs.io/">uWSGI</a> performance. We sacrifice a bit of performance for the sake of this information. And we store all this information for later analysis.</p> <p><strong>Example of function execution time</strong></p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span>{ </span></span><span style="display:flex;"><span> &#34;get_final_filtered_ads&#34;: { </span></span><span style="display:flex;"><span> &#34;counter&#34;: 1931250, </span></span><span style="display:flex;"><span> &#34;avg&#34;: 0.0066143431, </span></span><span style="display:flex;"><span> &#34;elapsed&#34;: 12773.9500310003 </span></span><span style="display:flex;"><span> }, </span></span><span style="display:flex;"><span> &#34;store_keywords_statistics&#34;: { </span></span><span style="display:flex;"><span> &#34;counter&#34;: 1931011, </span></span><span style="display:flex;"><span> &#34;avg&#34;: 0.0004605267, </span></span><span style="display:flex;"><span> &#34;elapsed&#34;: 889.2821669996 </span></span><span style="display:flex;"><span> }, </span></span><span style="display:flex;"><span> &#34;match_by_context&#34;: { </span></span><span style="display:flex;"><span> &#34;counter&#34;: 1931011, </span></span><span style="display:flex;"><span> &#34;avg&#34;: 0.0055960716, </span></span><span style="display:flex;"><span> &#34;elapsed&#34;: 10806.0758889999 </span></span><span style="display:flex;"><span> }, </span></span><span style="display:flex;"><span> &#34;match_by_high_performance&#34;: { </span></span><span style="display:flex;"><span> &#34;counter&#34;: 262, </span></span><span style="display:flex;"><span> &#34;avg&#34;: 0.0152770229, </span></span><span style="display:flex;"><span> &#34;elapsed&#34;: 4.00258 </span></span><span style="display:flex;"><span> }, </span></span><span style="display:flex;"><span> &#34;store_impression_stats&#34;: { </span></span><span style="display:flex;"><span> &#34;counter&#34;: 1931250, </span></span><span style="display:flex;"><span> &#34;avg&#34;: 0.0006189991, </span></span><span style="display:flex;"><span> &#34;elapsed&#34;: 1195.4419869999 </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span>} </span></span></code></pre><p>We have also started profiling with <a href="https://pymotw.com/2/profile/">cProfile</a> and then visualizing with <a href="http://kcachegrind.sourceforge.net/">KCachegrind</a>. This provides much more detailed look into code execution.</p> <h2 id="cache-control-is-your-friend">Cache control is your friend</h2> <p>Because we use Javascript library for rendering ads we rely on this script extensively and when in need we need to be able to change behavior of the script quickly.</p> <p>In our case we can not simply replace javascript url in html code. It usually takes a day or two for the guys who maintain sites to change code or add ?ver=xxx attribute. And this makes rapid deployment and testing very difficult and time consuming. There is a limitation of how much you can test locally.</p> <p>We are now in the process of integrating <a href="https://www.google.com/analytics/tag-manager/">Google Tag Manager</a> but couple of websites are developed on ASP.net platform that have some problems with tag manager. With a solution below we are certain that we are serving latest version of the script.</p> <p>And it only takes one mistake and users have the script cached and in case of caching it for 1 year you probably know where the problem is.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># nginx ➜ /etc/nginx/sites-available/default </span></span></span><span style="display:flex;"><span><span style="color:#008000"></span><span style="color:#00f">location</span> <span style="color:#a31515">/static/</span> { </span></span><span style="display:flex;"><span> <span style="color:#00f">alias</span> <span style="color:#a31515">/path-to-static-content/</span>; </span></span><span style="display:flex;"><span> <span style="color:#00f">autoindex</span> off; </span></span><span style="display:flex;"><span> <span style="color:#00f">charset</span> <span style="color:#a31515">utf-8</span>; </span></span><span style="display:flex;"><span> <span style="color:#00f">gzip</span> on; </span></span><span style="display:flex;"><span> <span style="color:#00f">gzip_types</span> <span style="color:#a31515">text/plain</span> <span style="color:#a31515">application/javascript</span> <span style="color:#a31515">application/x-javascript</span> <span style="color:#a31515">text/javascript</span> <span style="color:#a31515">text/xml</span> <span style="color:#a31515">text/css</span>; </span></span><span style="display:flex;"><span> <span style="color:#00f">location</span> ~<span style="color:#a31515">*</span> <span style="color:#a31515">\.(ico|gif|jpeg|jpg|png|woff|ttf|otf|svg|woff2|eot)</span>$ { </span></span><span style="display:flex;"><span> <span style="color:#00f">expires</span> <span style="color:#a31515">1y</span>; </span></span><span style="display:flex;"><span> <span style="color:#00f">add_header</span> <span style="color:#a31515">Pragma</span> <span style="color:#a31515">public</span>; </span></span><span style="display:flex;"><span> <span style="color:#00f">add_header</span> <span style="color:#a31515">Cache-Control</span> <span style="color:#a31515">&#34;public&#34;</span>; </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> <span style="color:#00f">location</span> ~<span style="color:#a31515">*</span> <span style="color:#a31515">\.(css|js|txt)</span>$ { </span></span><span style="display:flex;"><span> <span style="color:#00f">expires</span> <span style="color:#a31515">3600s</span>; </span></span><span style="display:flex;"><span> <span style="color:#00f">add_header</span> <span style="color:#a31515">Pragma</span> <span style="color:#a31515">public</span>; </span></span><span style="display:flex;"><span> <span style="color:#00f">add_header</span> <span style="color:#a31515">Cache-Control</span> <span style="color:#a31515">&#34;public,</span> <span style="color:#a31515">must-revalidate&#34;</span>; </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span>} </span></span></code></pre><p>Also be careful when redirecting to url in your python code. We noticed that if we didn't precisely setup cache control and expire headers in response we didn't get the request on the server and therefore couldn't measure clicks. So when redirecting do as follows and there will be no problems.</p> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># python ➜ bottlepy web micro-framework</span> </span></span><span style="display:flex;"><span>response = bottle.HTTPResponse(status=302) </span></span><span style="display:flex;"><span>response.set_header(<span style="color:#a31515">&#34;Cache-Control&#34;</span>, <span style="color:#a31515">&#34;no-store, no-cache, must-revalidate&#34;</span>) </span></span><span style="display:flex;"><span>response.set_header(<span style="color:#a31515">&#34;Expires&#34;</span>, <span style="color:#a31515">&#34;Thu, 01 Jan 1970 00:00:00 GMT&#34;</span>) </span></span><span style="display:flex;"><span>response.set_header(<span style="color:#a31515">&#34;Location&#34;</span>, url) </span></span><span style="display:flex;"><span><span style="color:#00f">return</span> response </span></span></code></pre><blockquote> <p>Cache control in browsers is quite aggressive and you need to be precise to avoid future problems. We learned that lesson the hard way.</p> </blockquote> <h2 id="learn-nginx">Learn NGINX</h2> <p>When deciding on a web server we went with Nginx as a reverse proxy for our applications. We adapted micro-service oriented architecture early in the project to ensure when we scale we can easily add additional servers to our cluster. And Nginx was crucial to perform load balancing and static content delivery.</p> <p>At first our config file was quite simple and later grew larger. After patching and adding new settings I sat down and learned more about the guts of Nginx. This proved to be very useful and we were able to squeeze much more out of our setup. So I advise you to take your time and read through the <a href="https://nginx.org/en/docs/">documentation</a>. This saved us a lot of headache. Googling for solutions only goes so far.</p> <h2 id="use-redismemcached">Use Redis/Memcached</h2> <p>As explained above we are using caching basically for everything. It is the corner stone of our services. At first we were very careful about the quantity of things we stored in <a href="https://redis.io/">Redis</a>. But we later found out that the memory footprint is very low even when storing large amount of data in it.</p> <p>So we gradually increased our usage to caching whole HTML outputs of dashboard. This improved our performance in order of magnitude. And by using native TTL support this goes hand in hand with our needs.</p> <p>The reason why we choose <a href="https://redis.io/">Redis</a> over <a href="https://memcached.org/">Memcached</a> was the nature of scalability of Redis out of the box. But all this can be achieved with Memcached.</p> <h2 id="conclusion">Conclusion</h2> <p>There are a lot more details that could have been written and every single topic in here deserves it's own post but you probably got the idea about the problems we faced.</p> Golang profiling simplified https://mitjafelicijan.com/golang-profiling-simplified.html Tue, 07 Mar 2017 12:00:00 +0200 https://mitjafelicijan.com/golang-profiling-simplified.html Many posts have been written regarding profiling in Golang and I haven’t foundproper tutorial regarding this. <p>Many posts have been written regarding profiling in Golang and I haven’t found proper tutorial regarding this. Almost all of them are missing some part of important information and it gets pretty frustrating when you have a deadline and are not finding simple distilled solution.</p> <p>Nevertheless, after searching and experimenting I have found a solution that works for me and probably should also for you.</p> <h2 id="where-are-my-pprof-files">Where are my pprof files?</h2> <p>By default pprof files are generated in /tmp/ folder. You can override folder where this files are generated programmatically in your golang code as we will see below in example.</p> <h2 id="why-is-my-cpu-profile-empty">Why is my CPU profile empty?</h2> <p>I have found out that sometimes CPU profile is empty because program was not executing long enough. Programs, that execute too quickly don’t produce pprof file in my cases. Well, file is generated but only contains 4KB of information.</p> <h2 id="profiling">Profiling</h2> <p>As you can see from examples we are executing dummy_benchmark functions to ensure some sort of execution. Memory profiling can be done without such a “complex” function. But CPU profiling needs it.</p> <p>Both memory and CPU profiling examples are almost the same. Only parameters in main function when calling profile.Start are different. When we set profile.ProfilePath(“.”) we tell profiler to store pprof files in the same folder as our program.</p> <h3 id="memory-profiling">Memory profiling</h3> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">package</span> main </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> ( </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#34;fmt&#34;</span> </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#34;time&#34;</span> </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#34;github.com/pkg/profile&#34;</span> </span></span><span style="display:flex;"><span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">func</span> dummy_benchmark() { </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> fmt.Println(<span style="color:#a31515">&#34;first set ...&#34;</span>) </span></span><span style="display:flex;"><span> <span style="color:#00f">for</span> i := 0; i &lt; 918231333; i++ { </span></span><span style="display:flex;"><span> i *= 2 </span></span><span style="display:flex;"><span> i /= 2 </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;-time.After(time.Second*3) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> fmt.Println(<span style="color:#a31515">&#34;sencond set ...&#34;</span>) </span></span><span style="display:flex;"><span> <span style="color:#00f">for</span> i := 0; i &lt; 9182312232; i++ { </span></span><span style="display:flex;"><span> i *= 2 </span></span><span style="display:flex;"><span> i /= 2 </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span>} </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">func</span> main() { </span></span><span style="display:flex;"><span> <span style="color:#00f">defer</span> profile.Start(profile.MemProfile, profile.ProfilePath(<span style="color:#a31515">&#34;.&#34;</span>), profile.NoShutdownHook).Stop() </span></span><span style="display:flex;"><span> dummy_benchmark() </span></span><span style="display:flex;"><span>} </span></span></code></pre><h3 id="cpu-profiling">CPU profiling</h3> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#00f">package</span> main </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">import</span> ( </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#34;fmt&#34;</span> </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#34;time&#34;</span> </span></span><span style="display:flex;"><span> <span style="color:#a31515">&#34;github.com/pkg/profile&#34;</span> </span></span><span style="display:flex;"><span>) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">func</span> dummy_benchmark() { </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> fmt.Println(<span style="color:#a31515">&#34;first set ...&#34;</span>) </span></span><span style="display:flex;"><span> <span style="color:#00f">for</span> i := 0; i &lt; 918231333; i++ { </span></span><span style="display:flex;"><span> i *= 2 </span></span><span style="display:flex;"><span> i /= 2 </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> &lt;-time.After(time.Second*3) </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span> fmt.Println(<span style="color:#a31515">&#34;sencond set ...&#34;</span>) </span></span><span style="display:flex;"><span> <span style="color:#00f">for</span> i := 0; i &lt; 9182312232; i++ { </span></span><span style="display:flex;"><span> i *= 2 </span></span><span style="display:flex;"><span> i /= 2 </span></span><span style="display:flex;"><span> } </span></span><span style="display:flex;"><span>} </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#00f">func</span> main() { </span></span><span style="display:flex;"><span> <span style="color:#00f">defer</span> profile.Start(profile.CPUProfile, profile.ProfilePath(<span style="color:#a31515">&#34;.&#34;</span>), profile.NoShutdownHook).Stop() </span></span><span style="display:flex;"><span> dummy_benchmark() </span></span><span style="display:flex;"><span>} </span></span></code></pre><h3 id="generating-profiling-reports">Generating profiling reports</h3> <pre tabindex="0" style="background-color:#fff;"><code><span style="display:flex;"><span><span style="color:#008000"># memory profiling</span> </span></span><span style="display:flex;"><span>go build mem.go </span></span><span style="display:flex;"><span>./mem </span></span><span style="display:flex;"><span>go tool pprof -pdf ./mem mem.pprof &gt; mem.pdf </span></span><span style="display:flex;"><span> </span></span><span style="display:flex;"><span><span style="color:#008000"># cpu profiling</span> </span></span><span style="display:flex;"><span>go build cpu.go </span></span><span style="display:flex;"><span>./cpu </span></span><span style="display:flex;"><span>go tool pprof -pdf ./cpu cpu.pprof &gt; cpu.pdf </span></span></code></pre><p>This will generate PDF document with visualized profile.</p> <ul> <li><a href="/posts/go-profiling/golang-profiling-mem.pdf">Memory PDF profile example</a></li> <li><a href="/posts/go-profiling/golang-profiling-cpu.pdf">CPU PDF profile example</a></li> </ul> Software development and my favorite pitfalls https://mitjafelicijan.com/software-development-pitfalls.html Tue, 10 Nov 2015 12:00:00 +0200 https://mitjafelicijan.com/software-development-pitfalls.html Over the years I had the privilege to work on some very excited projects both insoftware development field and also in electronics field and every experiencetaught me some invaluable lessons about how NOT TO approach development. <p>Over the years I had the privilege to work on some very excited projects both in software development field and also in electronics field and every experience taught me some invaluable lessons about how NOT TO approach development. And through this post I will try to point out some absurd, outdated techniques I find the most annoying and damaging during a development cycle. There will be swearing because this topic really gets on my nerves and I never coherently tried to explain them in writing. So if I get heated up, please bear with me.</p> <p>As new methods of project management are emerging, underlying processes still stay old and outdated. This is mainly because we as people are unable to completely shift away from these approaches.</p> <p>I was always struggling with communication, and many times that cost me a relationship or two because I was not on the ball all the time. Through every experience, I became more convinced that I am the problem and never ever doubted that the problem may be that communication never evolved a single step from emails. And if you think for a second, not many things have changed around this topic. We just have different representations of email (message boards, chats, project management tools). And I believe this is the real issue we are facing now.</p> <p>There are many articles written about hyper connectivity and the effects that are a direct result of it. But mainstream does nothing towards it. We are just putting out fires, and we do nothing to prevent it. I am certain this will be a major source of grief in coming years. And what we all can do to avoid this is to change our mindset and experiment on our communication skills, development approaches. We need to maximize possible output that a person can give. And to achieve this we need to listen to them, encourage them. I know that not everybody is a naturally born leader, but with enough practice and encouragement they also can become active participants in leadership.</p> <p>There are many talks now about methodologies such as Scrum, Kanban, Cleanroom and they all fucking piss me of :). These are all boxes that imprison people and take away their freedom of thought. This is a straightforward mindfuck / amputation of creativity.</p> <p>Let me list a couple of things that I find really destructive and bad for a project and in a long run company.</p> <h2 id="ping-emails">Ping emails</h2> <p>Ping emails are emails you have to write as soon as you receive an email. Its sole purpose is to inform the sender that you received their email, and you are working on it. Its result is only to calm down the sender that their task is being dealt with. It’s intent basically is, I did my job by sending you this email, so I am on clear grounds. I categorize this email as fuck you email. This is one of the most irritating types of emails I need to write. This is the ultimate control freak show you can experience, and it gives the sender a false feeling of control. Newsflash: We do not live in 1982 where there was a possibility that email never reached the destination. I really hate this from the bottom of my heart.</p> <p>They should be like: “Yes, I am fucking alive, and I am at your service my leash!”. I guess if I would reply like this, I wouldn’t have to write any more of this kind of messages.</p> <h2 id="everybody-is-a-project-manager">Everybody is a project manager</h2> <p>Well, this is a tough one. I noticed that as soon as you let people to give their suggestions, you are basically screwed. There is a truth in the saying: “Give low expectations and deliver little more than you promised.”.</p> <p>People tend to take a role of a manager as soon as they are presented with an opportunity. And by getting angry at them, you only provoke yourself. They are not at fault. You just need to tell them they are only giving suggestions and not tasks at the beginning and everything will be alright. But if you give them a feeling that they are in control, you will have immense problems explaining why their features are not in current release.</p> <p>Project mission must be always leading project requirements and any deviation from it will result in major project butchering. And by this, I mean that the project will get its own path, and you will be left with half done software that helps nobody. Clear mission goals and clean execution will allow you to develop software will clear intent.</p> <h2 id="we-are-never-wrong">We are never wrong</h2> <p>I find this type of arrogance the worst. We must always conduct ourselves that we are infallible and cannot make mistakes. As soon as a procedure or process is established, there is no room for changes or improvements. This is the most idiotic thing someone can say of think. I think that processes need to involve and change over time. This is imperative and need to have in your organization if you want to improve and develop company. We all need to grow balls and change everything in order to adapt to current situations. Being a prisoner of predefined processes kills creativity.</p> <p>I am constantly trying new software for project managing and communication. I believe every team has its own dynamic, and it needs to be discovered organically and naturally through many experiments. By putting the team in a box, you are amputating their creativity and therefore minimizing their potential. But if you talk to an executive, you will mainly find archetypical thinking and a strong need to compartmentalize everything from business processes to resource management. And this type of management that often displays micromanagement techniques only works for short periods (couple of years) and then employees either leave the company or become basically retarded drones on autopilot.</p> <h2 id="micromanaging">Micromanaging</h2> <p>This basically implies that everybody on the team is an idiot who needs to have a to-do list that they cannot write themselves. How about spoon-feeding the team at launch because besides the team leader, everybody must be a retarded idiot at best?</p> <p>I prefer milestones as they give developers much more freedom and creativity in developing and not waste their time checking some bizarre to-do list that was not even thought through. Projects constantly change throughout the development cycle, and all you are left at the end is a list of unchecked tasks and the wrath of management why they are not completed. Best WTF moment!</p> <h2 id="human-contact--no-need-for-it">Human contact — no need for it!</h2> <p>We are vigorously trying to eliminate physical contact by replacing short meetings with software, with no regards that we are not machines. Many times a simple 5-min meeting at morning can solve most of the problems. In rapid development, short bursts of man to man communication is possibly the best way to go.</p> <p>We now have all this software available, and all what we get out of it is a giant clusterfuck. An obstacle and not a solution. So, why we still use them?</p> <h2 id="mvp-is-killing-innovation">MVP is killing innovation</h2> <p>Many will disagree with me on this one, but I stand strong by this statement. What I noticed in my experience that all this buzz words around us only mislead and capture us in a circle of solving issues that already have a solution, but we are unable to see it without using some fancy word for it.</p> <p>The toughest thing to do for a developer is to minimize requirements. Well, this is though only for bad developers. Yes, I said it. There are many types of developers out there. And those unable to minimize feature scope are the ones you don’t need on your team. Their only goal is to solve problems that exist only in their heads. And then you have to argue with them, and waste energy on them, instead of developing your awesome product. They are a cancer and I suggest you cut them off.</p> <p>MVP as an idea is great, but sadly people don’t understand underlying philosophy, and they spent too much time focusing and fixating on something that every sane person with normal IQ will understand without some made up acronym. And the result is a lot of talking and barely no execution.</p> <p>Well, MVP is not directly killing innovation, but stupid people do when they try to understand it.</p> <h2 id="pressure-wasteland">Pressure wasteland</h2> <p>You must never allow to be pressured into confirming a deadline if you are not confident. We often feel a need that we are in service of others, which is true to some extent. But it is also true that others are in service to us to some extent. And we forget this all the time. We are all pressured all the time to make decisions just to calm other people down. And when they leave your office you experience WTF moment :) How the hell did they manage to fuck me up again?</p> <p>People need to realize that the more pressure you put on somebody, the less they will be able to do. So 5-min update email requests will only resolve in mental breakdown and inability to work that day. Constant poking is probably the only thing I lose my mind instantly. For all you that are doing this: “Stop bothering us with your insecurities and let us do our job. We will do it quicker and better without you breathing down our necks.”</p> <p>If this happens to me, I end up with no energy at the end. Don’t you get it? You will get much more from and out of me if you ask me like a human person and not your personal butler. On a long run, you are destroying your relationships and nobody would want to work with you. Your schizophrenic approach will damage only you in a long run. Nobody is anybody’s property.</p> <h2 id="conclusion">Conclusion</h2> <p>I am guilty of many things described in this post. And I find it hard sometimes to acknowledge this. And I lie to myself and try vigorously to find some explanation why I do these things. There is always space for growth. And maybe you will also find some of yourself in this post and realize what needs to change for you to evolve.</p> Wireless sensor networks https://mitjafelicijan.com/wireless-sensor-networks.html Thu, 24 Oct 2013 12:00:00 +0200 https://mitjafelicijan.com/wireless-sensor-networks.html Zigbee networks have this wonderful capability to self-heal, which means theycan reorder connections between them if one of them is inoperable. <p>Zigbee networks have this wonderful capability to self-heal, which means they can reorder connections between them if one of them is inoperable. This works our of the box when you deploy them. But you have to have in mind that achieving this is not as easy as you would think. None of it is plug&amp;play. So to make your life a bit easier, here are some pointers which, I hope, will help you.</p> <ul> <li>Be careful when you are ordering your equipment abroad. There are many rules and regulations you need to comply before you get your Xbee radios. What they do is they wait until you prove that you won’t use the technology for some kind of evil take over control of the world project :). For this, they have EAR (Export Administration Regulations) which basically means “This product may require a license to export from the United States.”.</li> <li>I don’t know if this applies for every country, but when we purchased our Xbee radios from Mouser, this was mandatory! What we needed to do was to print out a form and write information about our company and send them a copy via email. With this document, we proved that we are a legitimate company.</li> <li>When you complete your purchase and send all the documentation, you are not clear yet. Then customs will take it from there :). There will be some additional costs. Before purchasing, make sure you have as much information about costs as possible. Because it can get costly in the end.</li> <li>I suggest you use companies from your country. You can seriously cut your costs. Here in Slovenia, the best option so far as I know is Farnell. And based on my personal experience, they rock! All I need to say!</li> <li>Make plans when ordering larger quantities. Do not, I say, do not make your orders in December! :) Believe me! You will have problems with stock they can provide for you. So, we were forced to buy some things from Mouser, which was extremely painful because of all the regulations you need to obey when importing goods from the USA.</li> <li>Make sure that firmware version on your Xbee radios is exactly the same! Do not get creative!!! I propose using templates. You can get template by exporting settings/profile in X-CTU application. Make sure you have enabled “Upgrade firmware” so you can be sure each radio has the same firmware.</li> <li>And again: make plans! Plan everything! In months advanced! You will thank me later :)</li> <li>Test, test, test. Wireless networks can be tricky.</li> </ul> <p>If you are serious, I suggest you buy this book, Building Wireless Sensor Networks. You will get a glimpse of how networks work in lumens terms. It is a good starting point for everybody who wants to build wireless networks.</p> <p><strong>Additional resources:</strong></p> <ul> <li><a href="http://www.digi.com/aboutus/export/generalexportinfo">http://www.digi.com/aboutus/export/generalexportinfo</a></li> <li><a href="http://doresearch.stanford.edu/research-scholarship/export-controls/export-controlled-or-embargoed-countries-entities-and-persons">http://doresearch.stanford.edu/research-scholarship/export-controls/export-controlled-or-embargoed-countries-entities-and-persons</a></li> <li><a href="http://www.bis.doc.gov/licensing/exportingbasics.htm">http://www.bis.doc.gov/licensing/exportingbasics.htm</a></li> </ul> LED technology might not be as eco-friendly as you think https://mitjafelicijan.com/led-technology-not-so-eco.html Fri, 09 Mar 2012 12:00:00 +0200 https://mitjafelicijan.com/led-technology-not-so-eco.html There is a lot of talk about LED technology. <p>There is a lot of talk about LED technology. It is beginning to infiltrate industry at a fast rate, and it’s a challenge for designers and also engineers. I wondered when a weakness will be revealed. Then I stomped on an article talking about harm in using LED technology. It looks like this magical technology is not so magical and eco-friendly.</p> <p>A new study from the University of California indicates that LED lights contain toxic metals, and should be produced, used and disposed of carefully. Besides the lead and nickel, the bulbs and their associated parts were also found to contain arsenic, copper, and other metals that have been linked to different cancers, neurological damage, kidney disease, hypertension, skin rashes and other illnesses in humans, and to ecological damage in waterways.</p> <p>Since then, I haven’t yet found any regulation for disposal of LED lights or any other regulation or standard. This might be a problem in the future. And it is a massive drawback. This might have quite an impact on consumer market.</p> <p>Nevertheless, there is a potential, and I am sure the market will adapt. I also hope I will be reading documents regarding solution for this concern soon.</p> <p><strong>Additional resources:</strong></p> <ul> <li><a href="http://ezinearticles.com/?Recycling-and-Disposal-of-Light-Bulbs&amp;id=1091304">Recycling and Disposal of Light Bulbs</a></li> <li><a href="http://www.ehow.com/how_7483442_dispose-lowenergy-light-bulb.html">How to Dispose of a Low-Energy Light Bulb</a></li> </ul> Most likely to succeed in the year of 2011 https://mitjafelicijan.com/most-likely-to-succeed-in-year-of-2011.html Thu, 13 Jan 2011 12:00:00 +0200 https://mitjafelicijan.com/most-likely-to-succeed-in-year-of-2011.html The year of 2010 was definitely the year of Geo-location. <p>The year of 2010 was definitely the year of Geo-location. The market responded beautifully and lots of very cool services were launched. We all have to thank the mobile market for such extensive adoption. With new generations of mobile phones that are not only buffed with high-tech hardware but are also affordable. We can now manage tasks that were not so long time ago, almost Star Trek’ish. And all this had and has great influence on the destination to which we are going now.</p> <p>Reading all this articles about new innovation about new thriving technologies makes me wonder what’s the next step. The future is the mesh, like Lisa Gansky said in her book The Mesh.</p> <p>Many still have conservative views on distributed systems. The problems with security of information. Fear of not controlling every aspect of information flow. I am very opened to distributed systems and heterogeneous applications, and I think this is the correct and best way to proceed.</p> <p>This year will definitely be about communication platforms. Mobile to mobile. Machine to mobile and vice versa. All the tech is available and ready to put into action. Wireless is today’s new mantra. And the concept of semantic web is now ready for industry.</p> <p>Applications and developers now can gain access to new layers of systems and can prepare and build solutions to meet the high quality needs of market. The speed is everything now.</p> <p>My vote goes to “Machine to Machine” and “Embedded Systems”!</p> <ul> <li><a href="http://en.wikipedia.org/wiki/Machine-to-Machine">Machine-to-Machine</a></li> <li><a href="http://www.bitxml.org/">The ultimate M2M communication protocol</a></li> <li><a href="http://www.coosproject.org/maven-site/1.0.0/project-info.html">COOS Project (connectivity initiative)</a></li> <li><a href="http://m2m.com/index.jspa">Community for machine-to-machine</a></li> <li><a href="http://en.wikipedia.org/wiki/Embedded_system">Embedded system</a></li> </ul>