<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sampsa Riikonen on Medium]]></title>
        <description><![CDATA[Stories by Sampsa Riikonen on Medium]]></description>
        <link>https://medium.com/@sampsa.riikonen?source=rss-f9489cd2c8d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*t94dAsgR3ZoKfeHh_YvKMw.jpeg</url>
            <title>Stories by Sampsa Riikonen on Medium</title>
            <link>https://medium.com/@sampsa.riikonen?source=rss-f9489cd2c8d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:27:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sampsa.riikonen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Remote CCTV System with TailScale]]></title>
            <link>https://medium.com/@sampsa.riikonen/building-a-remote-cctv-system-with-tailscale-7532e8744e3f?source=rss-f9489cd2c8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7532e8744e3f</guid>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[tailscale]]></category>
            <category><![CDATA[cctv-installation]]></category>
            <category><![CDATA[vlc-media-player]]></category>
            <category><![CDATA[ip-camera]]></category>
            <dc:creator><![CDATA[Sampsa Riikonen]]></dc:creator>
            <pubDate>Wed, 19 Jun 2024 10:48:41 GMT</pubDate>
            <atom:updated>2024-06-19T10:48:41.858Z</atom:updated>
            <content:encoded><![CDATA[<p><em>View your home or business (or mother-in-law) from a remote location anywhere in the globe with encrypted video. For free.</em></p><p>IP cameras are ubiquitous in today’s society — they are those “CCTV” / surveillance cameras you can see zooming in at every commercial center, gas station and grocery shop — just to mention a few places where you might have a close encounter with them.</p><p>They’re not just “cameras”, but instead versatile “internet-of-things” gadgets that can be used to view remote locations <em>live</em> at over the internet and be spiced up with AI machine vision, alerts, etc.</p><p>You can buy one of them from anywhere, your local electronics store, amazon, alibaba, you name it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jwYGLCKi0rD7XgoVMyRzjg.png" /><figcaption>Image 1: A bunch of IP cameras</figcaption></figure><p>Once you plug them in to your home network router, you can access their configuration via a web interface which they provide, and start vieving live video.</p><p>The IP camera manufacturers offer all kinds of services for remote viewing, recording and analysis, while cloud-based CCTV and security firms offer subscription-based services where you pay a license per camera and per month.</p><p>But then you must trust <em>them </em>to keep your video stream encrypted, safe and secret and to keep their services online forever in the future.</p><p>But if you just want to live view streams from a remote location with your laptop and/or smartphone, none of those (paid) services are needed.</p><p>In this tutorial, we will setup a VPN (Virtual Private Network) with your IP cameras and smartphone for viewing the cameras remotely from anywhere in the world — for free! And you are not dependent on any weirdo cloud startup nor IP camera manufacturer neither to keep your cameras online.</p><p><em>Your live camera view will be encrypted and accessible from your mobile device anywhere in the globe.</em></p><p>You can easily scale up your system to include tens or even hundreds of IP cameras.</p><p>Creating such a system used to be kinda painful — setting up a VPN with, say, OpenVPN and subscribing to some dynamic IP service or paying up for a fixed IP address (so that you can find your router and cameras from the internet).</p><p>But nowadays it is all <em>soo</em> much easier with the rise of <a href="https://tailscale.com/">TailScale</a>.</p><h4><strong>1. What you need</strong></h4><p>You need, of course, a broadband service and a <strong>router</strong> (as provided by your broadband provider).</p><p>At least one <strong>IP camera</strong>. When you buy one, be sure that it is “RTSP” and “OnVif” compatible and that it supports the H264 video codec.</p><p>Finally, a dedicated linux computer. This can be an old laptop you want to recycle or even better, a “thin client”, such as raspberry pi. You need to know how to install linux on that thing. I recommend <a href="https://ubuntu.com/download/raspberry-pi">Ubuntu</a>.</p><p>This computer, which we will refer to simply as the <strong>linux box</strong>, is connected directly to the <strong>router</strong>.</p><p>The linux box will be online 24/7.</p><p>During the configuration stage of the linux box, you need to have keyboard and a monitor connected to it. Once the configuration is done, you just leave it on and connected to your router <em>para siempre</em>.</p><h4><strong>2. Configure your router</strong></h4><p>Go to your router’s admin page. It’s typically <a href="http://192.168.1.1/">http://192.168.1.1</a> or <a href="http://192.168.0.1/">http://192.168.0.1.</a></p><p>Next we need to see your IP camera in the list of devices that are connected to your router. So plug in your IP camera into the router if you haven’t done so yet.</p><p>There are as many user interfaces as there are router manufacturers and models, but try to find a list of devices and their MAC and IP addresses. For my (mother-in-law’s) ZTE router it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIoFBCAX-TRjaJhliGkhLA.png" /><figcaption>Image 2: List of devices connected to your router</figcaption></figure><p>A MAC address is inherent to each device (connected computers, IP cameras, smartphones, tvs, etc.), while the IP address (say, 192.168.1.133) is assigned dynamically to each device by your router.</p><p>Try to locate the camera’s assigned IP address by connecting with your browser to the device IP address that appear in the list.</p><p>In my case (see the image above), the camera has appeared as 192.168.1.149 and when I go with my browser to http://192.168.1.149, then <em>bingo — </em>I can see the camera’s web interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8irfB8sw5tg5y_TbEU_-g.jpeg" /><figcaption>Image 3: A typical web interface of an older HIKVision IP camera</figcaption></figure><p>Next we will fix the camera to use always the <em>same</em> IP address. In the case of my (mother-in-law’s) router the menu looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*57agoJu6_RROmTZd6C2RaA.png" /><figcaption>Image 4: Fixing MAC to an IP address</figcaption></figure><p>I write into the input fields, the camera’s unique MAC address (which I have blurred here for privacy reasons) and the assigned IP address (192.168.1.149) and <em>voilá</em> — from now on, that camera will <em>always</em> be available at 192.168.1.149.</p><h4><strong>3. Configure your camera</strong></h4><p>Once you have fixed the camera’s IP address, go (again) to the camera’s web interface, i.e. to <strong>http://192.168.1.your-particular-address</strong> (in my case this was http://192.168.1.149) and do any configuration needed (one thing you might want to do is set the camera to use wifi instead of cable connection).</p><p>Your IP camera came in a box with some manual and those should indicate the default admin username and password. A popular choice for these are “admin” and “12345” or something like that. If the manual doesn’t indicate them, try google with the brand’s name.</p><p>Once you have logged in succesfully to your camera’s web interface with the correct username and password and done any necessary configurations therein (if necessary), you should be able to stream video from the camera with the <strong>RTSP protocol</strong>.</p><p>Try these commands in your linux box’es command line:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/785c10d4a6135648ee1179f8e49f0791/href">https://medium.com/media/785c10d4a6135648ee1179f8e49f0791/href</a></iframe><p>where username is typically that “admin” mentioned above, while password is the password (typically “12345” as discussed above) and ip is the ip address of the camera in your router’s network (“192.168.1.149” in my case as explained above).</p><p><em>Tadaa</em> — now you should see the live video from the camera using VLC and ffplay in your linux box. We can now move on to the next stage.</p><h4><strong>4. Setup TailScale</strong></h4><p>Install tailscale into your linux box (using <a href="https://tailscale.com/download/linux">these instructions</a>) and then login into your very first tailnet VPN. Here is a two-liner for both of those things:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/652d6df6fdfa626ef09b1a334bc3ccb0/href">https://medium.com/media/652d6df6fdfa626ef09b1a334bc3ccb0/href</a></iframe><p>That gives you a link you should click &amp; open in the linux box’s web browser for authentication.</p><p>Use your favorite identity provider to login (I used my gmail account). This will create you a tailscale VPN (a “tailnet”) and joins the linux box automatically into it.</p><p>Now you should be able to see the linux box in tailscale’s awesome and simple web interface (see Image 6). Next, you can add/join any number of devices into your tailnet and they form a closed and secure virtual network.</p><p>Said that, join your smartphone: go to google play store and search for “tailscale” and install the app. Open the app and login <em>with the same identity provider and account as you did in the linux box above</em>. Now you should see two devices in the app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*K4h5IatoTDOSkwfHoLt0dQ.jpeg" /><figcaption>Image 5: TailScale in your smartphone</figcaption></figure><p>Now your smartphone and the linux box are in the same tailnet. Tailscale’s control panel in the linux box should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFXx7R8eItm16i8HuY9bRw.png" /><figcaption>Image 6: TailScale control panel in the linux box</figcaption></figure><p>Some other tailscale commands of interest (not required in this tutorial though) are switching between accounts and checking the status of the tailnet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dd89a00ba9d10bdb83af10f57d6f2cd/href">https://medium.com/media/4dd89a00ba9d10bdb83af10f57d6f2cd/href</a></iframe><h4><strong>5. Setup TailScale subnets</strong></h4><p>We configure tailscale subnets in the linux box as per <a href="https://tailscale.com/kb/1019/subnets?tab=linux">here</a>, with the following “spells”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97d4ee667212527403de2e62c79dba16/href">https://medium.com/media/97d4ee667212527403de2e62c79dba16/href</a></iframe><p>The first one disables the (ubuntu) firewall for good (if it was running).</p><p>NOTE: those commands are known to work for Ubuntu. For other distros, you might need to adapt them.</p><p>Finally, make your IP camera visible in the tailnet by using this command in the linux box:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4603944fec8e1d6757a8e8879c7c0ed7/href">https://medium.com/media/4603944fec8e1d6757a8e8879c7c0ed7/href</a></iframe><p>Remember to <strong>substitute 192.168.1.149</strong> with the particular IP address of your camera.</p><p>You still need to <strong>approve the subnet from the tailscale control panel</strong> (Image 6 — click the three dots for your linux box and choose “Edit Route Settings”, etc.).</p><p>No further configuration is needed: the tailscale daemon’s setup survives reboots of the linux box.</p><h4><strong>6. View from your Smartphone</strong></h4><p>(NOTE: this is applicable to <em>any</em> device that is in your tailnet and has VLC installed: iphone, mac, android, windows, etc.)</p><p>Install “VLC” into your smartphone from the app store / google play.</p><p>In order to make the streaming experience nice and smooth, we configure VLC a bit. Follow the instructions in this image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lie3KOMRtCdfnmFns0E_mA.png" /><figcaption>Image 7: VLC in your smartphone</figcaption></figure><p>(you only need to do that once)</p><p>Go again to the main menu of the VLC app and click “(+) New stream” and write in the address field</p><p><strong>rtsp://username:password@ip</strong></p><p><em>And use exactly the same credentials and ip address you did in step (3) above</em>.</p><p>And <em>tadaa</em> — I am able to spy my mother-in-law. From anywhere in the globe. Realtime. With encrypted video. For free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcUWtzHFqwB2z2sxtBpZSQ.png" /><figcaption>Figure 8: Mission accomplished — spying on my mother-in-law from anywhere in the world!</figcaption></figure><p><em>How satisfying is that!?</em></p><h4><strong>7. Scaling up</strong></h4><p>Next you could buy a “switch” (aka <em>unmanaged</em> router) that you plug into your home router. Buy one with lots of ports so you can plug in lots of cameras.</p><p>Prefer a PoE (power-on-ethernet) switch and connect it with a ton/shitload of IP cameras. You need to go through steps (2–3) for each camera though.</p><p>You need to repeat this command from step (5) as well and include always <em>all</em> the cameras:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f4382fd1fc0fdd00d371a9b0c6a982c/href">https://medium.com/media/8f4382fd1fc0fdd00d371a9b0c6a982c/href</a></iframe><p>You might want to dedicate a small and sleek linux laptop for viewing all those cameras, wherever you go. So install ubuntu into a laptop and join it to the tailnet with the instructions in step (4).</p><p>After that, install <a href="https://elsampsa.github.io/valkka-live/_build/html/index.html">Valkka Live</a> in the laptop, view a tens of live IP cameras and add machine vision applications into your setup.</p><p>Remember to make a screencaptures of your massive mother-in-law surveillance system and share it with me in discord for mutual satisfaction.</p><p><em>Thank you for reading!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7532e8744e3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Roadtrip between Object Oriented and Functional Programming]]></title>
            <link>https://medium.com/@sampsa.riikonen/a-roadtrip-between-object-oriented-and-functional-programming-d5161dc19052?source=rss-f9489cd2c8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5161dc19052</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[qt]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Sampsa Riikonen]]></dc:creator>
            <pubDate>Tue, 10 Aug 2021 12:57:51 GMT</pubDate>
            <atom:updated>2023-03-23T14:00:38.112Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to organize your object oriented code into hierarchies with restricted communication — and how this technique is related to functional programming</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*iDLFvf4sAVI3YOjz.jpg" /><figcaption>This road leads you to object-oriented enlightement</figcaption></figure><p>The eternal question: how to organize your object-oriented code in order to avoid the creation of that spaghetti codebase?</p><p>Functional Programming (FP) is the silver bullet for this. But if we are forced to use Object-Oriented Programming (OOP), can we take features from FP and apply them to OOP?</p><p>I am <em>not</em> talking about copy-pasting FP features such as filters and maps into existing OOP languages, but something much more deeper.</p><p>In this post I will first provide a self-contained, short explanation of OOP’s “<em>global state mess</em>” — the main reason for those hopeless codebases.</p><p>Then I do a compact intro into functional programming (FP) and discuss why there is no global state mess.</p><p>After that, the interesting bits start: I discuss parallels between OOP’s object hierarchies and FP’s function hierarchies. This leads to a natural way to organize your OOP code: hierarchical objects with restricted communication within the hierarchies.</p><p>There are disparate practical applications for this. I’ll give a detailed example from the world of graphical user interfaces, implemented in PyQt. Vue.js framework is also discussed.</p><p>Let’s start the trip.</p><h3>Global State Mess swamp</h3><p><em>(skip if you’re way too familiar with this)</em></p><p>The “global state mess” is an ubiquitous problem in modern programming. You probably bang your head with it on a daily basis. Even so, let’s refresh our memory about it:</p><p>Consider you create an object with some members:</p><pre>class Dummy:<br>    def __init__(self, i: int, j: int):<br>        self.i = i<br>        self.j = j</pre><pre>    def doSomething(self, par: int):<br>        self.i = self.j + par<br>    ...</pre><pre>obj1 = Dummy()<br>obj.doSomething(2)</pre><p>Here the set of values of members i and j constitutes the <em>internal state</em> of object obj1. Here are some possible states, just to name a few:</p><pre>i, j = 1,0 <br>i, j = 1,1 <br>i, j = 0,1 <br>...</pre><p>Method doSomething is a method that modifies the state of the object.</p><p>When you instantiate lots of objects in your program:</p><pre>obj1 = Dummy() <br>obj2 = Dummy() <br>obj3 = SomeOtherClass() <br>...</pre><p>The set of values of all members of all objects constitutes the <em>global state</em> of your program.</p><p>Next, let’s consider giving objects to objects:</p><pre>obj2 = SomeClass(...) <br>obj1 = SomeOtherClass(.., obj2)</pre><p>Here we give object (obj2) to another objects (obj1). Obj1 then modifies the internal state of obj2. Obj2 can also be passed around to other objects.</p><p>The so-called <em>global state mess</em> is ready to be served.</p><p>If you’ve ever been in a situation where you are wandering around a complex codebase, trying to find out what the different classes are actually <em>for</em>, while simultaneously trying to figure out how they affect each other and the global state of the program (“<em>how did the program end up in this state?</em>”), then you know what I’m talking about.</p><h3><strong>Functional Programming village</strong></h3><p>In (purely) functional programming, you don’t instantiate objects. They don’t exist. There are no members either. Everything revolves around functions. For creating complex programming logic, instead of instantiating objects, passing them around and calling their members, you just do this:</p><pre>func1(func2(func3(func4)))</pre><pre>[expression (1)]</pre><p>i.e. a function calling a function, calling a function, etc.</p><p>And the state. Where is it?</p><p>Sure, a function may have a short-lived intermediate state while its executing (imagine it doing maybe a few loops, some logic and waiting for other functions to return), but once it returns its value, it disappears from the call stack and that intermediate state says “<em>puff!</em>” — disappearing forever into the ether.</p><p>If you’re able to frame your program in terms of functional programming, then congratulations, you have achieved the holy grail of programming: stateless code that is easily debugged, with perfect “separation of concerns” between different parts of the code: each function in the call chain just does “it’s stuff”, nothing else. No global state to create a mess with.</p><p>In order to visualize this, let’s create another presentation/description of expression (1).</p><p>Describing almost <em>anything</em> with a <a href="https://www.wired.com/story/adam-savage-lists-more-lists-power-checkboxes/">hierarchical list</a> is always a good idea, so we’ll do just that: expression (1) can be written down as a hierarchical list like this:</p><pre>func1<br>    func2<br>        func3<br>            func4</pre><pre>[diagram (2)]</pre><p>which should be self-explanatory.</p><p>Lets add therein the inputs and return values of each function using this notation:</p><pre>IN = function&#39;s input parameter(s) <br>UP = function&#39;s return value(s) - as it goes UP in the hierarchy</pre><p>Resulting in:</p><pre>func1 <br>    func2 <br>        IN: int i <br>        UP: int j <br>        func3 <br>            IN: int c, d <br>            UP: str w <br>            func4 <br>                IN: int e <br>                UP: list</pre><pre>[diagram (3)]</pre><p>i.e., func2 takes as an input value, int i, returns int j, etc.</p><p>A certain function, can of course, use several functions lower in the hierarchy, resulting in trees/cascades like this:</p><pre>func1 <br>    func2 <br>        func3 <br>            func4 <br>    func2b <br>        func3b <br>            func4b <br>        func3c <br>            func4c <br>                func5c </pre><pre>[diagram (4)]</pre><p>i.e. func1 calls both functions func2 and func2b, etc.</p><p>We can think those functions as “intercommunicating entities”. But their “intercommunication” is strictly restricted, since they’re just functions, and a function just takes an input value and spits out a return value:</p><ul><li>Going down in the tree, a “parent” function can only “communicate” (i.e. perform a function call with an input) with it’s immediate “child” functions</li><li>Going up in the three, a child can only communicate with it’s immediate parent (i.e. by simply returning a result)</li><li>Data that goes from parent to child is immutable (i.e. “one time copy”)</li><li>Data returned back to parent is similarly an immutable copy</li></ul><p>There is no intercommunication in this tree that would a traverse between siblings, jump to ancestors (other than immediate parent), etc. Those restrictions arise naturally, since in functional programming you can only use functions.</p><h3>Object Oriented valley</h3><p>Next, let’s turn the steering wheel and leave the (fantasy) village of functional programming behind. Let’s turn that function cascade diagram (4) into an object instance hierarchy instead:</p><pre>obj1 <br>    obj2 <br>        obj3 <br>            obj4 <br>    obj2b <br>        obj3b <br>            obj4b <br>        obj3c <br>            obj4c <br>                obj5c<br> <br>[diagram (5)]</pre><p>Where each objN is an object <em>instance</em> (please do <em>not</em> confuse this with an inheritance diagram), i.e. obj1 instantiates and owns obj2, obj3 instantiates and owns obj4, etc.</p><p>This is an archetypical pattern in OOP: you have a “master object” (obj1) which, during it’s lifetime, instantiates various other objects (from several different classes). These other objects then perform various tasks and return results higher up.</p><p>As you can see, it looks exactly the same as the functional programming diagram (4): <strong>we do have a common denominator here</strong></p><p>Many OOP projects start in this exact (and clean) way, but it doesn’t take long until antipatterns start to emerge.</p><p>Let’s consider just one of those antipatterns:</p><p>“Master object” obj1 passes itself as a reference to obj2, which passes it to obj3, which passes it to obj4, etc. These deeper level child objects then use setters and getters of the master object obj1 to get information from it and to change obj1’s internal state.</p><p><strong>An intractable global state mess is ready.</strong></p><p>This antipattern emerges for several reasons: it can be pressure from upper-level management to “<em>get things done in an ‘agile’ way</em>”. Say, obj4 needs some data from obj1 and the easiest way out is just to pass obj1 as a reference down the chain. Future programmers just follow the flow, and anyway, once things are done this way, there is no going back anymore.</p><p>It could also be that “smart” junior programmer that was given the task to fix obj4 so that it receives data from other parts of the hierarchy tree.</p><p>Eventually, the code becomes an impenetrable spaghetti. In the worst case scenario, to change even the simplest behaviour of the code will require weeks of work as you’re desperately trying to find the response to the question: “<em>in wtf-state the code is?</em>”. This process might also involve red-faced and raving managers (who created the problem themselves in the first place, by wanting to be ‘agile’).</p><h3><strong>In between</strong></h3><p>So, how to avoid the OOP disaster ever happening?</p><p>“<em>Just use functional programming!</em>” would be the advise from the functional-programming zealots, and they’re right.</p><p>As explained above, functional programming language would have never allowed such behaviour, since it restricts the intercommunication in the tree structures of diagrams (4) and (5) by construction.</p><p>We can see that FP’s power is <em>as much about state elimination, as it is about well-defined hierarchies having restricted communication.</em></p><p>Keeping that in mind, let’s remember that your code cannot always be staged in terms of pure functional programming. Maybe it doesn’t apply to your problem. The libraries you are using are not written in functional programming.</p><p>Let’s mimic the mechanics of FP in OOP and also come up with a fancy acronym: HIerarchical Minimally Interacting Objects (HIMO):</p><ul><li>There is a clearly defined object hierarchy</li><li>Communication is done strictly between parent and child only (no cross-communication across the hierarchy tree in diagram (5))</li><li>Data is passed preferably as immutable copies between parent and child</li><li>Analyze your global state and how it is partitioned into the hierarchy</li><li>Avoid persistent states when possible. You should consider keeping the persistent states as high in the tree as possible (however, not always recommendable).</li></ul><p>A purely functional programming language enforces several of these rules by definition. In other languages we can try to follow them (of course, until that “smart” junior programmer comes along).</p><h3><strong>Graphical User Interface city</strong></h3><p>A particularly tricky situation in terms of a global state is a graphical user interface (GUIs). A GUI has <em>always</em> a state, typically a very complex one.</p><p>Ultimately, the “state” of the GUI is inside the user’s head as he/she sees the morass of buttons, forms and input fields in front of him/her. And that user won’t go “puff” into the ether, even if you wished so.</p><p>Forms, views, lists, menus, etc. are typically referred to as “widgets”. Each widget has a state (the current active element in a list, fields in a form, state of a checkbox, etc.), which then interacts with other widgets.</p><h4>Model and View</h4><p>Let’s still put all this in the concept of Model-View-Controller.</p><p>In Qt and modern JS frontend frameworks, instead of <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a> or <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel">MVVM</a> it makes more sense simply to talk about the Model and the View (the <a href="https://doc.qt.io/qt-5/model-view-programming.html#the-model-view-architecture">MV</a> model):</p><ul><li><strong>The View</strong>: Buttons, checkboxes, fields and their interactive/live/”reactive” interactions. Think of an interactive input field checker, for example.</li><li><strong>The Model</strong>: Handles communication with the data source.</li><li>The View and The Model communicate. In Qt with signals and slots. In Vue, this communication is defined by the Vue components.</li><li>Both in Qt and Vue.js, the user programs the view (as defined here), the model and the intercommunication between them.</li></ul><p>And yes, we have a great opportunity to create a variety of global state messes here:</p><ol><li>View state mess: state of the widgets becomes intractable by writing obscure widget interactions. In Qt you can create this with signals and slots. In Vue.js with your vue components.</li><li>Model state mess: the “traditional” global state mess we have discussed earlier.</li><li>View + Model state mess: State of the View and the Model become strongly coupled together.</li></ol><p>We can use HIMO to narrow down the intercommunication within the View and between the Model and the View and mitigate (1–3).</p><h3><strong>A Qt Example sideroad</strong></h3><p>Next we’ll consider a small and a silly example case and provide the code for it in Python Qt (PySide2 flavor). Implementing the same thing in Vue.js is left as an excercise. :)</p><p>Here is the goal: on the left, a list of items, showing the complete name of a person. On the right, a form appears. With the form you can do basic CRUD operations on the person data. When the database is empty, the form and the “save” and “delete” buttons are hidden:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*_3cf9QUJOVt-0cJe.png" /><figcaption>A CRUD GUI</figcaption></figure><p>To see how it <em>really</em> works, I suggest that you try it. First, download it from <a href="https://github.com/elsampsa/medium/blob/main/hierarchy/example.py">here</a>, and then do this:</p><pre>pip3 install --user PySide2 <br>python3 example.py</pre><p>We could create a state mess here by letting the different objects (list, form, fields, buttons) to call each others directly and to pass the state (= which element is chosen in the list, what has been updated in the form, etc.) around directly (of course, in this simple example, you have to kinda try to mess it up).</p><p>How can we organize this trivial example as HIMO as possible?</p><p>First of all, we need a hierarchy.</p><p>In Qt, one creates hierarchical constructions by default: widgets are placed and contained within other widgets, so it fits naturally our purposes (unfortunately, Qt does not enforce us to restrict the inter-object communication in any way).</p><p>In our example, we have lots of QWidget objects contained in other QWidget objects in our object hierarchy. The main ones to which we’ll be applying HIMO, will have their names starting with letter “W”.</p><p>This is going to be our hierachy:</p><pre>WListForm (master object: handles databases, updates other objects)<br>    WList <br>        QListWidget <br>             QListWidgetItem(s) <br>    WForm <br>         QLineTextEdit(s)<br>    WButtons <br>         QPushButton <br>         QPushButton <br>         ...</pre><p>We have a hierarchy, so let’s continue by restricting the intercommunication within that hierarchy:</p><ul><li>Going DOWN in the tree, call directly a setter method of a child (<em>could</em> also be done with a Qt signal)</li><li>Going UP in the tree, emit a Qt signal to the parent, or alternatively, offer a getter method</li></ul><p>In Vue.js, you would do this:</p><ul><li>Going DOWN in the tree, modify child’s “prop” (that has a listener in the child)</li><li>Going UP in the tree, emit a signal to the parent</li></ul><p>Moreover:</p><p>- Variables that are passed between parent and child should be immutable copies</p><p>Our final object tree and its intercommunication looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e50dd20f4a0311636794ea88ec663f31/href">https://medium.com/media/e50dd20f4a0311636794ea88ec663f31/href</a></iframe><p>Let’s analyze this for a moment.</p><p>First of all, we have added information about the state of each object.</p><p>For example, there is a state in the child object WForm, so it needs setters/getters accessible by the parent to manipulate that state.</p><p>WList’s state includes a list of data records (datums) and the current chosen record. However, as these are immediately communicated/synced with the parent WListForm object, we don’t need to worry about them — it is as if there is no state in WList (the only state we care about is in the parent object). In this case we have “moved” the state into a higher level object in the hierarchy (as discussed in “HIMO” above).</p><p>Some other things to note (also commented in the code itself):</p><ul><li>Setter functions do not trigger signals: you don’t want signals.uuid emitted when calling set_uuid. This is a good practice that avoids confusion.</li><li>Namespaces are used to further organize things, in this case, signals are always in their own “sub-namespace”.</li></ul><p>That’s it — thanks for hanging on.</p><p>The only thing left to do in this roadtrip is to take a look at the code itself. Hopefully you’ll enjoy it. If not, please leave some rants into the comments.</p><h3><strong>Finally back home</strong></h3><p>Great that you joined us on this trip from functional to object-oriented programming, object hierarchies, graphical user interfaces and from there to Qt and Vue.js.</p><p>On the road we saw how our souvenirs and that free tourist map from functional programming village can make our navigation in the object-oriented valley more organized and transparent. Namely, by defining hierarchies, restricting communication within those hierarchies and eliminating states if possible. No need to go through that global state mess swamp again.</p><p>This was applied to a trivial graphical user interface example at the Qt sideroad. However, the same principle can be applied in disparate fields of programming.</p><p>Final tip: sketching the object hierarchies, their inputs and outputs, helps in developing/debugging your code. So it’s a good idea to include them into your code comments (like we did here): better to have a map when you’re travelling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5161dc19052" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Doing python multiprocessing The Right Way]]></title>
            <link>https://medium.com/@sampsa.riikonen/doing-python-multiprocessing-the-right-way-a54c1880e300?source=rss-f9489cd2c8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a54c1880e300</guid>
            <category><![CDATA[multiprocessing]]></category>
            <category><![CDATA[pyqt5]]></category>
            <category><![CDATA[qt]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[posix]]></category>
            <dc:creator><![CDATA[Sampsa Riikonen]]></dc:creator>
            <pubDate>Tue, 27 Jul 2021 13:00:04 GMT</pubDate>
            <atom:updated>2023-03-16T17:58:03.320Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn how to combine multiprocessing- and threading, and how to organize your multiprocessing classes in the right way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*aG1IGkVH-X6NM4WGKkK6vw.jpeg" /><figcaption>A Posix Fork has taken place</figcaption></figure><p>Not a day goes by in Medium articles without someone complaining that Python is not the future of machine learning.</p><p>For example, things like “<em>I can write a GPU kernel in Julia but not in Python</em>”. However, most of us data scientists/engineers are just dummy engineers who use ready-made libraries. 95% of us are not interested in “writing a GPU kernel”.</p><p>Another complaint is about multiprocessing: on many occasions, you need to use multiprocessing instead of multithreading. People find this awkward(especially because of interprocess communication). Also, multiprocessing is very prone to errors if you’re not carefull.</p><p>Although cumbersome at first sight, multiprocessing does have several advantages.</p><p>Keeping processes separated in their own (virtual memory) “cages” can actually help in debugging and avoids confusion. Once you sort out the intercommunication problem in a systematic way and avoid some common pitfalls, programming with python multiprocesses becomes a joy.</p><p>One frequent error is to mix multithreading and multiprocessing together, creating a crashy/leaky program and then conclude that python sucks. More on this later.</p><p>Some beginners prefer, instead of writing a proper multiprocessing class, to do things like this:</p><pre>p = Process(target=foo)</pre><p>This obfuscates completely what you are doing with processes and threads (see below).</p><p>I have even seen people using multiprocessing.Pool to spawn single-use-and-dispose multiprocesses at high frequency and then complaining that &quot;python multiprocessing is inefficient&quot;.</p><p>After this article you should be able to avoid some common pitfalls and write well-structured, efficient and rich python multiprocessing programs.</p><p>This is going to be different what you learned in that <a href="https://docs.python.org/3/library/multiprocessing.html">python multiprorcessing tutorial</a>. No Managers, Pools or Queues, but more of an under-the-hood approach.</p><p>Let’s start with the basics of posix fork.</p><h3>Forking vs. Threading</h3><p>Forking/multiprocessing means that you “spawn” a new process into your system. It runs in its own (virtual) memory space. Imagine that after a fork, a copy of your code is now running “on the other side of the fork”. Think of “Stranger Things”.</p><p>On the contrary, threading means you are creating a new running instance/thread, toiling around in the same memory space with your current python process. They can access the same variables and objects.</p><p>Confusing bugs arise when you mix forking and threading together, as creating threads first and then forking, leaves “dangling”/”confused” threads in the spawned multiprocesses. Talk about mysterious freezes, segfaults and all that sort of nice things. But combining forking and threading can be done, if it’s done in the right order: fork first and then threading.</p><p>This problem is further aggravated by the fact that many libraries which you use in your python programs may start threads sneakily in the background (many times, directly in their C source code), while you are completely unaware of it.</p><p>Said all that, this is the correct/safe order of doing things:</p><ul><li>0. Import libraries that do not use multithreading</li><li>1. Create interprocess communication primitives and shared resources that are shared between multiprocesses (however, not considered in this tutorial)</li><li>2. Create interprocess communication primitives and shared resources that are shared with the main process and your current multiprocess</li><li>3. Fork (=create multiprocesses)</li><li>4. Import libraries that use multithreading</li><li>5. If you use asyncio in your multiprocess, create a new event loop</li></ul><p>Let’s blend these steps in with an actual code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bff882fdf1d712966b38d28e2fb7f551/href">https://medium.com/media/bff882fdf1d712966b38d28e2fb7f551/href</a></iframe><p>Remember that concept of code running “on the other side of the fork”? That “other side” with demogorgons (and the like) which is isolated from our universe is created when you say p.start().</p><p>The stuff that runs in that parallel universe is <em>defined</em> in the method run().</p><p>When creating complex multiprocessing programs, you will have several multiprocesses (parallel universes) each one with a large codebase.</p><p>So, we’ll be needing a “mental guideline” to keep our mind in check. Let’s introduce a concept for that purpose:</p><p>Our multiprocess class shall have a <strong>frontend</strong> and a <strong>backend</strong> (not to be confused with web development!)</p><p><strong>Frontend</strong> is the scope of your current running python interpreter. The normal world.</p><p><strong>Backend</strong> is the part of the code that runs “on the other side of the fork”. It’s a different process in its own memory space and universe. Frontend needs to communicate with the backend in some way (think again of Stranger Things).</p><p>Let’s once more emphasize that <em>everything that’s inside/originates from method run(), runs in the backend</em>.</p><p>From now on, we’ll stop talking about demogorgons, parallel realities and stick strictly to <strong>frontend</strong> and <strong>backend</strong>. Hopefully, you have made the idea by now.</p><p>The only things happening at the frontend in that example code are:</p><blockquote>p = MyProcess() # code that is executed in MyProcess.__init__</blockquote><blockquote>p.start() # performs the fork</blockquote><p>In order to avoid confusion, we need to differentiate between frontend and backend methods. We need a naming convention. Let’s use this one:</p><p><strong>All backend methods shall have a double-underscore in their name</strong></p><p>Like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e2b54f30affe0887e994af78dc55213/href">https://medium.com/media/7e2b54f30affe0887e994af78dc55213/href</a></iframe><p>i.e. listenFront__() is a backend method.</p><p>Before we move on, one extra observation: multiprocesses are not supposed to be single-use-and-dispose. You don’t want to create and start them at high frequency since creating them has considerable overhead. You should try to spawn your multiprocesses only once (or at <em>very</em> low frequency).</p><h3>Let’s Ping Pong</h3><p>Next, let’s demonstrate the frontend/backend scheme in more detail.</p><p>We do a classical multiprocessing example: sending a ping to the multiprocess, which then responds with a pong.</p><p>The frontend methods are ping() and stop(). You call these methods in your main python program (aka frontend). Under-the-hood, these methods do seamless intercommunication between front- and backend.</p><p>Backend methods listenFront__() and ping__() run at the backend and they originate from the run() method.</p><p>Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5693a25b70b438f376562139008cfd43/href">https://medium.com/media/5693a25b70b438f376562139008cfd43/href</a></iframe><p>Note that in the python main process, we use only the frontend methods (start, ping and stop).</p><p>So, we have successfully eliminated the mental load of needing to think about the fork at all. At the same time, the code has a clear distinction to and intercommunication with the forked process. We just need to think in terms of the front- and backend and their corresponding methods.</p><h3>One more pitfall</h3><p>Let’s imagine that, as your codebase grows, your code looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63c5fb4212d873bfa6aabfc4525cb0d8/href">https://medium.com/media/63c5fb4212d873bfa6aabfc4525cb0d8/href</a></iframe><p>SomeLibrary is just some library that you need in your code but is not used/related to your multiprocesses in any way.</p><p>However, if that SomeLibrary uses multithreading under-the-hood (without you knowing about it), you have created yourself a big problem.</p><p>Still remember what we said earlier?</p><p><strong>No threads before fork!</strong></p><p>As even just importing a library might silenty starts threads, to be <em>absolutely</em> on the safe side, do this instead:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d97ff104106985293840a254202e212/href">https://medium.com/media/8d97ff104106985293840a254202e212/href</a></iframe><p>i.e. instantiate and start your multiprocesses before anything else.</p><p>If the logic in your program requires using multiprocesses “on-demand”, consider this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80dbaa49877fa547c2b43c46b37886ca/href">https://medium.com/media/80dbaa49877fa547c2b43c46b37886ca/href</a></iframe><p>i.e., instead of creating and starting multiprocesses in the middle of your program, you create and start them at the very beginning and then cache them for future use.</p><h3>Some Testing and debugging tips</h3><p>For test purposes, you can run your python multiprocessing classes without forking at all, by simply not using start()in your test code. In this case you can call the backend methods directly in your tests/frontend, provided that you have structured your code correctly.</p><p>For python refleaks and resulting memory blowup issues you can use the following technique. Import the setproctitle library with</p><pre>from setproctitle import setproctitle</pre><p>In your multiprocesses run() method, include this:</p><pre>setproctitle(&quot;Your-Process-Name&quot;)</pre><p>Now your process is tagged with a name, so that you can follow the memory consumption of that single process very easily with standard linux tools, say, with smem and htop (in htop, remember to go to setup =&gt; display options and enable &quot;Hide userland process threads&quot; in order to make the output more readable).</p><h3>Finally</h3><p>In this tutorial I have given you some guidelines to succeed with your python multiprocessing program and not to fall into some typical pitfalls.</p><p>You might still have lot of questions:</p><ol><li>How to listen at several multiprocesses simultaneously at my main program? (hint: use the select module)</li><li>How do I send megabytes of streaming data to a running multiprocess? Say, images and/or video (can be done perfectly, but not trivial)</li><li>Can I run asyncio in the back- or frontend or both? (sure)</li></ol><p>These are, however, out of the scope of this tutorial.</p><p>Let’s just mention that in the case (2) that:</p><ul><li>You would <em>not</em> certainly use pipes (they are not for large streaming data)</li><li>Use posix shared memory, mapped into numpy arrays instead. Those arrays form a ring-buffer that is synchronized using posix semaphores across process boundaries</li><li>You need to listen simultaneously to the intercommunication pipe and the ringbuffer. Posix EventFd is a nice tool for this.</li></ul><p>I’ve done this kind of stuff in a python multimedia framework I’ve written. If you’re interested, please see <a href="https://elsampsa.github.io/valkka-examples/_build/html/index.html">here</a>.</p><p>That’s the end of the tutorial. I hope it gave you some food for thought.</p><p><strong>APPENDUM 1</strong></p><p>I wrote an addinitional example, available <a href="https://github.com/elsampsa/medium/blob/main/multiprocess/example2.py">here</a>:</p><ul><li>Posix shared memory and intercommunicating with several multiprocesses (questions 1 &amp; 2 above).</li><li>Special interest for PyQt / PySide2 users: mapping slots and signals to a multiprocess.</li><li>Handling multiprocesses from a multithread</li></ul><p><strong>APPENDUM 2</strong></p><p>All the ideas presented in this article, are now neatly wrapped into a python module: please see <a href="https://elsampsa.github.io/valkka-multiprocess/_build/html/index.html">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a54c1880e300" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>