<?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 Nik Vaklev on Medium]]></title>
        <description><![CDATA[Stories by Nik Vaklev on Medium]]></description>
        <link>https://medium.com/@nikolay-vaklev?source=rss-71aa094abe4c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dmNSxYRbH_aDspht.</url>
            <title>Stories by Nik Vaklev on Medium</title>
            <link>https://medium.com/@nikolay-vaklev?source=rss-71aa094abe4c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:58:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikolay-vaklev/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[Either monad (fp-ts) for processing deeply-nested documents with Typescript]]></title>
            <link>https://medium.com/analytics-vidhya/either-monad-fp-ts-for-processing-deeply-nested-documents-with-typescript-cc5934687ea9?source=rss-71aa094abe4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc5934687ea9</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Nik Vaklev]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 12:33:49 GMT</pubDate>
            <atom:updated>2023-08-22T13:32:02.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jnMIuGv1AyIalq-bjxpOgg.jpeg" /></figure><h3>Intro</h3><p>The Either monad can be very helpful, when working with nested data structures for example from API responses. Often the problem is an API response from a 3rd party system would return data structures that can vary depending on the underlying data.</p><p>Simply, the data they produce is not perfect either and could easily have gaps and it is not the job of an endpoint to make for missing or incomplete information.</p><h4>How would you process the API response below?</h4><pre>[<br> {<br>  reviewerID: &quot;A2SUAM1J3GNN3B&quot;,<br>  asin: &quot;0000013714&quot;,<br>  reviewerName: &quot;J. McDonald&quot;,<br>  helpful: [2, 3],<br>  reviewText:<br>   &quot;I bought this for my husband who plays the piano.  He is having a wonderful time playing these old hymns.&quot;,<br>  overall: 5.0,<br>  summary: &quot;Heavenly Highway Hymns&quot;,<br>  unixReviewTime: 1252800000,<br>  reviewTime: &quot;09 13, 2009&quot;,<br> },<br> {<br>  reviewerID: &quot;A2SUAM1J3GNN3A&quot;,<br>  asin: &quot;0000013714&quot;,<br>  reviewerName: &quot;J. Smith&quot;,<br>  helpful: [1, 2],<br>  overall: 3.0,<br>  summary: &quot;Heavenly Highway Hymns&quot;,<br>  unixReviewTime: 1252800001,<br>  reviewTime: &quot;09 14, 2009&quot;,<br> },<br> {<br>  reviewerID: &quot;A2SUAM1J3GNN3A&quot;,<br>  asin: &quot;0000013714&quot;,<br>  reviewerName: &quot;J. Banks&quot;,<br>  helpful: [7, 8],<br>  reviewText: &quot;&quot;,<br>  overall: 7.0,<br>  summary: &quot;Heavenly Highway Hymns&quot;,<br>  unixReviewTime: 1252800001,<br>  reviewTime: &quot;09 14, 2009&quot;,<br> },<br> null,<br>]</pre><p>We have three JSON documents in the response… Well actually they are four but the last one is simply null!</p><p>The second one is missing the reviewText key. Because we are talking about product reviews, logically, not all users will provide a full review. For brevity, the design team behind this particular API decided to make that key optional (often) in order to minimise the data transferred between servers and clients.</p><p>What about thenull value at the end of the list? Maybe this review was deleted for some reason but the system still wants us to know there was something there.</p><h4>Solution 1: The Naive Approach</h4><p>This is vanilla Typescript snippet showing the processing of a JSON API response:</p><pre>interface SingleReview {<br> reviewerID: string;<br> asin: string;<br> reviewerName: string;<br> helpful: [number, number];<br> reviewText?: string;<br> overall: number;<br> summary: string;<br> unixReviewTime: number;<br> reviewTime: string;<br>};<br><br>const complexLogic = (i: SingleReview | null) =&gt; {<br>  if (!!i) {<br>    switch (i.reviewText) {<br>      case &quot;&quot;:<br>        return &quot;&quot;;<br>      case null:<br>      case undefined:<br>        return &quot;NO_REVIEW_TEXT&quot;;<br>      default:<br>        return i.reviewText;<br>    }<br>  } else {<br>    return &quot;NO_REVIEW&quot;;<br>  }<br>};<br><br>// Get an array of all the reviews<br>function getReviewsSimpleApproach(reviews: Array&lt;SingleReview | null&gt;) {<br>  return reviews.map((i) =&gt; complexLogic(i));<br>}<br><br>// Get an array of the length of all the reviews<br>function processReviewsSimpleApproach(reviews: Array&lt;SingleReview | null&gt;) {<br>  return reviews<br>    .map((i) =&gt; {<br>      return complexLogic(i);<br>    })<br>    .map((i) =&gt; {<br>      switch (i) {<br>        case &quot;NO_REVIEW&quot;:<br>        case &quot;NO_REVIEW_TEXT&quot;:<br>          return null;<br>        default:<br>          return i.length;<br>      }<br>    });<br>}<br><br>function simpleReviewProcess() {<br>  return [<br>    processReviewsSimpleApproach(reviews), // list of review lengths<br>    getReviewsSimpleApproach(reviews) // list of all the texts<br>  ];<br>}</pre><h4>Solution 2: Either monad</h4><p>The code above works but it can be improved by using Either monad from fp-ts</p><pre>import * as E from &quot;fp-ts/Either&quot;;<br>import { flow } from &quot;fp-ts/function&quot;;<br><br>interface SingleReview {<br> reviewerID: string;<br> asin: string;<br> reviewerName: string;<br> helpful: [number, number];<br> reviewText: string;<br> overall: number;<br> summary: string;<br> unixReviewTime: number;<br> reviewTime: string;<br>};<br><br>const fromNullableText = E.fromNullable(&quot;NO_REVIEW_TEXT&quot;);<br>const fromNullableReview = E.fromNullable(&quot;NO_REVIEW&quot;);<br><br>const getReviewLength = flow(<br> E.flatMap((j: SingleReview) =&gt; fromNullableText(j.reviewText)),<br> E.map((j: string) =&gt; j.length),<br> E.match(<br>  () =&gt; undefined,<br>  (right: number) =&gt; right<br> )<br>);<br><br>const getReviewSummary = flow(<br> E.flatMap((j: SingleReview) =&gt; fromNullableText(j.reviewText)),<br> E.match(<br>  (err) =&gt; {<br>   switch (err) {<br>    case &quot;NO_REVIEW&quot;:<br>     return err;<br>    case &quot;NO_REVIEW_TEXT&quot;:<br>     return err;<br>    default:<br>     return &quot;&quot;;<br>   }<br>  },<br>  (right: string) =&gt; right<br> )<br>);<br><br>function processAllReviews() {<br> const either_reviews = reviews.map((i: SingleReview | null) =&gt;<br>  fromNullableReview(i)<br> );<br><br> return [<br>  either_reviews.map((i) =&gt; getReviewLength(i)), // list of review lengths<br>  either_reviews.map((i) =&gt; getReviewSummary(i)), // list of all the texts<br> ];<br>}</pre><p><strong>Both approaches produce the same table below:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*gCduyyZxOZi9sDWMDh9WaQ.png" /></figure><p><strong>I would argue that the use of Either monad makes it easier to follow, reason and one day refactor this code. </strong>Functional programming is all about expressing your intent and re-using code as much as possible.</p><p>Also imagine if the JSON returned by the API was actually nested, i.e. one of the keys contains not a simple value but another object. The sheer effort to write the logic to account for all the possibilities to retrieve values from deeply nested structures will be daunting and error prone. Either is good at handling this case and provides a template for how to deal with this case.</p><p>There is one down side to monads… They are still objects which exist in memory and thus take up RAM and CPU resources. Wrapping each value in a monad from a list of millions of objects, will blow up as well.</p><p><strong>The main difference between vanilla Typescript and using Either from fp-ts, is that we as humans don’t have to constantly keep writing code to check about all the possible edge cases. The code quality and maintainability deteriorates quickly when the number of if- and switch-statements explodes.</strong></p><p><em>My name is </em><a href="https://de.linkedin.com/in/nikolay-vaklev-b0582b4a"><em>Nik</em></a><em> and I am the founder of </em><a href="https://techccino.com/?utm_source=medium.com&amp;utm_medium=tech-blog&amp;utm_content=dev-locally-rancher"><em>Techccino Ltd</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc5934687ea9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/either-monad-fp-ts-for-processing-deeply-nested-documents-with-typescript-cc5934687ea9">Either monad (fp-ts) for processing deeply-nested documents with Typescript</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Safety against null / undefined at run-time with Option Monad (fp-ts +Typescript)]]></title>
            <link>https://blog.devgenius.io/safety-against-null-undefined-at-run-time-with-option-monad-fp-ts-typescript-40c4fd0f2ccf?source=rss-71aa094abe4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/40c4fd0f2ccf</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Nik Vaklev]]></dc:creator>
            <pubDate>Fri, 26 May 2023 12:34:07 GMT</pubDate>
            <atom:updated>2023-07-27T18:38:56.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akjAKtzVArg-8xjEcq4O0w.jpeg" /></figure><p>Typescript + fp-ts: Monads can make your code simpler and safer to execute.</p><h3>Intro</h3><p>Functional programming (FP) has been around for a long time but many developers consider it too cumbersome to implement. Many say this style of writing code makes it difficult to understand the code. I do see tabgible benefits from using FP and I really want to promote it with a few simple examples.</p><h3>Example 1: simple arithmetic</h3><p>In general, handling values that can be null / undefined can be cumbersome. The simplest approach is to use if statements everywhere to check for possible “bad” values.</p><p>In JavaScript in particular, null is an object which will not throw an error with the following code:</p><pre>const some_value = null;<br>console.log(some_value + 1) // -&gt; &quot;1&quot;<br><br>const some_other_value = undefined;<br>console.log(some_other_value + 1) // -&gt; &quot;NaN&quot;</pre><p>I am not going to get into the debate of undefined vs null in JavaScript. The main point is that some developers depending on the circumstances (including myself) will be tempted to “coalesce” nulls to zero like in the first example when doing calculations. It is just easier than being strict about it.</p><h4>Solution</h4><pre>import * as O from &quot;fp-ts/lib/Option&quot;;<br>import { flow } from &quot;fp-ts/lib/function&quot;;<br><br>const addOne = flow(<br> O.fromNullable&lt;number | null | undefined&gt;,<br> O.map((i: number) =&gt; i + 1),<br> O.getOrElse(() =&gt; 0)<br>);<br><br>addOne(undefined) // =&gt; 0<br>addOne(null) // =&gt; 0<br>addOne(1) // =&gt; 2</pre><p>By wrapping the input value in an option monad (in reality a JavaScript class with certain methods) I can control the execution of any operations over that input and make a conscious decision how to handle null and undefined.</p><p><strong>More importantly though, the Option monad check at run-time whether the value is defined or not. This is very different from the static type-checking with TypeScript, which is done before the code is transpiled to plain Javascript and any type-safety is, realistically speaking, an illusion.</strong></p><h3>Example 2: Displaying numbers</h3><p>Here is a better example of how wrapping something in an Option monad can be helpful. Imagine the following is user-facing code</p><pre>const some_val = undefined;<br>console.log(`The lucky number is: ${some_val}`)<br>// =&gt; &quot;The lucky number is: undefined!&quot;</pre><p>As a user I do not want to see <strong>“The lucky number is: UNDEFINED!”</strong></p><h4>Solution</h4><pre>const embedInString = flow(<br> O.fromNullable&lt;number | null | undefined&gt;,<br> O.map&lt;number, string&gt;((i: number) =&gt; `The lucky number is: ${i}`),<br> O.getOrElse(() =&gt; &quot;The lucky number is not available right now!&quot;)<br>);<br><br>embedInString(null) // =&gt; &quot;The lucky number is not available right now!&quot;<br>embedInString(1) // =&gt; &quot;The lucky number is: 1!&quot;<br>console.log(`The lucky number is: ${some_val}`) // =&gt; &quot;The lucky number is: undefined!&quot;</pre><p>As a user I can understand that the lucky number is not known sometimes!</p><h4>Is this a realistic example?</h4><p>The short answer is YES! The constant some_value can be defined in a completely different part of the code and you are asked as a developer to display it <strong>as a big banner on the front page, because everyone wants to know what the lucky number is!</strong> Normally there is nothing to tell you that this value can be actually not defined. If you receive an Option&lt;number&gt; then it is pretty clear what is going on.</p><h3>Conclusion</h3><p>Here is visual example of the results from Example 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*gbdZEpQKewaKWpqHWhd22Q.png" /></figure><p>You can find the actual code here: <a href="https://codesandbox.io/s/medium-post-simple-option-monad-hq1ujr-hq1ujr?file=/src/App.tsx">https://codesandbox.io/s/medium-post-simple-option-monad-hq1ujr-hq1ujr?file=/src/App.tsx</a></p><p>The use of the Option monad has three great benefits:</p><ol><li>It provides real checks at run-time against null/ undefined .</li><li>It forces developers to deal with these case and not assume someone else upstream has done it.</li><li>It makes the code explicit!</li></ol><p>And, yes as a developer you will have to get used to the notations and passing monads around.</p><p><em>My name is </em><a href="https://de.linkedin.com/in/nikolay-vaklev-b0582b4a"><em>Nik</em></a><em> and I am the founder of </em><a href="https://techccino.com/?utm_source=medium.com&amp;utm_medium=tech-blog&amp;utm_content=dev-locally-rancher"><em>Techccino Ltd</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40c4fd0f2ccf" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/safety-against-null-undefined-at-run-time-with-option-monad-fp-ts-typescript-40c4fd0f2ccf">Safety against null / undefined at run-time with Option Monad (fp-ts +Typescript)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why would you use TypeScript?]]></title>
            <link>https://medium.com/swlh/why-would-you-use-typescript-50db8120b126?source=rss-71aa094abe4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/50db8120b126</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[developer-tools]]></category>
            <dc:creator><![CDATA[Nik Vaklev]]></dc:creator>
            <pubDate>Tue, 09 May 2023 09:03:41 GMT</pubDate>
            <atom:updated>2023-05-09T09:12:17.770Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In essence, TypeScript comes with some overheads but there are a few benefits as well. </em><strong><em>No pain no gain they say!</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8RCgypzPF6HwrNYQ__Thg.jpeg" /></figure><h3>Intro</h3><p>This post from <a href="https://medium.com/u/c359511de780">Eric Elliott</a> called <a href="https://medium.com/javascript-scene/the-typescript-tax-132ff4cb175b">“The Typescript Tax”</a> was very interesting to me. His analysis is valid because <strong>TypeScript (TS)</strong> does not solve the problems traditionally handled by (strongly-)typed language:</p><ol><li>The types in TS are not a way of boosting performance by allocating memory resource efficiently because under the hood it is still just Javascript.</li><li>TS does not prevent from runtime errors due to type mismatch, i.e. it is still possible to pass to a function a number instead of a string at runtime .</li></ol><p><strong>But I do believe TypeScript has three main benefits!</strong></p><h3><strong>Faster development through type suggestions</strong></h3><p>TS reduces development efforts on <strong>bigger projects</strong> through type “documentation” like interfaces:</p><pre>interface SomeDataI {<br>  start_date: string;<br>  end_date: Date;<br>}</pre><p>They are used in IDEs to provide suggestions while coding. Also it is very convenient to look up what keys an object is supposed to contain.</p><p><em>Note: I find function declarations with multiple overloads in TS less useful. A normal function should not have 10 different possible signatures for example.</em></p><h3>“In-code” documentation</h3><p>The type system is also a form of short but succinct “in-code” documentation reducing the need for writing messy unstructured comments all over the code:</p><pre>const getSomeDateFromServer = (entity_id: string, start_date: Date, end_date: string) =&gt; {<br>  // Do something here<br>}</pre><p>I would argue a function defined as above does not normally need extra comments to make it clear what it does. <strong>An informative function name and variable names, and the types should be enough in most cases.</strong></p><h3>TS makes library upgrades easier</h3><p>Upgrading to a newer version of a package can be a headache especially when switching between major versions with breaking changes. These situations are unavoidable. Eventually a project will require some new functionality available only in the latest version of some package. TypeScript make this process rather quick because the type checker will immediately flag up any mismatch with new interface and function signatures in the API. As a developer there is no need to search for all the places where the API has changed. You are immediately told where TS finds the errors.</p><h3>Conclusion</h3><p>In essence, TypeScript comes with some overheads but there are a few benefits as well. No pain no gain they say! I personally often struggled in the past to document my code mainly because comments are free-text and every time I had to think exactly how to explain the code. TypeScript is a structured way of documenting your intentions with a minimum effort.</p><p>This way of thinking about type-checking is very different from traditional typed languages where types are about performance. <strong>I use types in Python as well! Not because they make my code faster or safer but because they make it clearer!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50db8120b126" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/why-would-you-use-typescript-50db8120b126">Why would you use TypeScript?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop locally containers for Kubernetes with K3s Rancher]]></title>
            <link>https://blog.devgenius.io/develop-locally-containers-for-kubernetes-with-k3s-rancher-219d5d0ba34a?source=rss-71aa094abe4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/219d5d0ba34a</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[rancher-labs]]></category>
            <dc:creator><![CDATA[Nik Vaklev]]></dc:creator>
            <pubDate>Thu, 23 Dec 2021 10:41:51 GMT</pubDate>
            <atom:updated>2021-12-23T14:06:16.984Z</atom:updated>
            <content:encoded><![CDATA[<h4>Replacing docker-compose with Rancher for local development</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cB_tPBaOiNw_-w5h8Rqo-w.jpeg" /></figure><h3>Intro</h3><p>Setting up Kubernetes locally is difficult, which makes it difficult to develop locally and try out things quickly. <a href="https://rancher.com/docs/k3s/latest/en/">K3s Rancher</a> is a lightweight version of K8s (Kubernetes) which can run even on Raspberry Pi. It can also be a good starting point for anyone learning about K8s deployments.</p><p>The pros of using K3s are:</p><ul><li>Develop and test (Docker) containers locally without polluting the local machine by installing many additional packages.</li><li>It is quick and easy to orchestrate a few containers locally with Kubernetes-like API</li><li>Once you are happy with the deployment locally, all the YAML configs can be deployed to Kubernetes without any (significant) changes.</li><li>There is nothing more annoying than trying to work out why container A is not talking to B or why container C is just refusing to start. Having access to things locally can save you A LOT OF TIME.</li></ul><p>For comparison, these are the system requirements for working with <a href="https://minikube.sigs.k8s.io/docs/">Minikube</a> (in 2021), which is a local deployment of Kubernetes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*3j71uhcF9prMj5eIlypDWA.png" /></figure><p><em>It is not nothing and this is before you even start running any containers on it.</em></p><h3>Part 1: Set up K3s locally</h3><p><strong>!!This tutorial assumes a Linux development environment!!</strong></p><p>The nice thing about K3s is that it comes as a single binary, k3s , which can be configured to keep all its data in one folder like so:</p><pre>sudo ./k3s-system/k3s server  \<br>  --data-dir  ./k3s-system \<br>  --config ./config.yaml \<br>  --write-kubeconfig ./k3s.yaml</pre><p>All its internal data goes under this folder ./k3-system . The config file, config.yaml can be as simple as:</p><pre>write-kubeconfig-mode: &quot;0644&quot;<br>tls-san:<br>  - &quot;foo.local&quot;<br>node-label:<br>  - &quot;foo=bar&quot;<br>  - &quot;something=amazing&quot;</pre><p>Starting the K3s servers generates a configuration file, k3s.yaml :</p><pre>apiVersion: v1<br>clusters:<br>- cluster:<br>    certificate-authority-data: ...<br>    server: <a href="https://127.0.0.1:6443/">https://127.0.0.1:6443</a><br>  name: default<br>contexts:<br>- context:<br>    cluster: default<br>    user: default<br>  name: default<br>current-context: default<br>kind: Config<br>preferences: {}<br>users:<br>- name: default<br>  user:<br>    client-certificate-data: ...<br>    client-key-data: ...</pre><p>which can be used with the standard Kubernetes CLI kubectl .</p><h3>Part 2: Example with PostgreSQL running locally on K3s</h3><p>Being able to test things locally is a treat. It is also great doing that without filling your machine with lots of junk all the time. Hence, running PostgreSQL as a container accessible on localhost makes sense. docker-compose can do that but the configuration files are useless unless you are running <a href="https://docs.docker.com/engine/swarm/">Docker Swarm</a> in production. In practice, many people use Kubernetes for container orchestration.</p><p>This is a simple (Helm) chart for deploying PostgreSQL on K8s/K3s</p><pre>---<br># Source: postgresql/templates/serviceaccount.yaml<br>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: k3s-env-postgresql<br>  labels:<br>    helm.sh/chart: postgresql-0.1.0<br>    app.kubernetes.io/name: postgresql<br>    app.kubernetes.io/instance: k3s-env<br>    app.kubernetes.io/version: &quot;14.1-bullseye&quot;<br>    app.kubernetes.io/managed-by: Helm<br>---<br># Source: postgresql/templates/service.yaml<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: k3s-env-postgresql<br>  labels:<br>    helm.sh/chart: postgresql-0.1.0<br>    app.kubernetes.io/name: postgresql<br>    app.kubernetes.io/instance: k3s-env<br>    app.kubernetes.io/version: &quot;14.1-bullseye&quot;<br>    app.kubernetes.io/managed-by: Helm<br>spec:<br>  type: NodePort<br>  ports:<br>    - port: 5432<br>      nodePort: 30001<br>      targetPort: http<br>      protocol: TCP<br>      name: http<br>  selector:<br>    app.kubernetes.io/name: postgresql<br>    app.kubernetes.io/instance: k3s-env<br>---<br># Source: postgresql/templates/deployment.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: k3s-env-postgresql<br>  labels:<br>    helm.sh/chart: postgresql-0.1.0<br>    app.kubernetes.io/name: postgresql<br>    app.kubernetes.io/instance: k3s-env<br>    app.kubernetes.io/version: &quot;14.1-bullseye&quot;<br>    app.kubernetes.io/managed-by: Helm<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app.kubernetes.io/name: postgresql<br>      app.kubernetes.io/instance: k3s-env<br>  template:<br>    metadata:<br>      labels:<br>        app.kubernetes.io/name: postgresql<br>        app.kubernetes.io/instance: k3s-env<br>    spec:<br>      serviceAccountName: k3s-env-postgresql<br>      securityContext:<br>        {}<br>      containers:<br>        - name: postgresql<br>          securityContext:<br>            {}<br>          image: &quot;postgres:14.1-bullseye&quot;<br>          imagePullPolicy: IfNotPresent<br>          env:<br>            - name: POSTGRES_PASSWORD<br>              value: &quot;password&quot;<br>          ports:<br>            - name: http<br>              containerPort: 5432<br>              protocol: TCP</pre><p>It contains a service account used by the PostgreSQL deployment (nice to have). Then it creates a node-port service that allows access to the DB on localhost:30001 and finally, it defines a bare-bones deployment of a PostgreSQL instance with only one server (replicas: 1 )</p><p>That’s it! The DB can be accessed using <a href="https://www.pgadmin.org/download/">pgAdmin III</a> or something similar on localhost:30001 with username root and password password.</p><h3>Summary</h3><p>The example with PostgreSQL is nice because it shows how to set up things locally but it can go further. For instance, the DB can be combined with <a href="https://superset.apache.org/">Apache Superset</a> also running in a container to create a nice data analytics environment locally.</p><p>Nevertheless, there is only so much that can be done locally before the data gets too big for the local machine, for example. The next step is deploying the containers in a hosted Kubernetes in a cloud and continuing the development work using <a href="https://skaffold.dev/"><strong>skafold</strong></a>, which allows files to be synced between a local machine and a remote container. For example, this is very useful for developing Node.js servers with hot-reload switched on.</p><p><a href="https://k8slens.dev/"><strong>K8sLens</strong></a><strong> </strong>is a self-contained UI that can be used to monitor K3s/K8s deployments. It performs the same tasks as kubectl but it presents the information visually and offers a nice UI.</p><p>In short, K3s can be used to develop and test deployments locally. it cab also be used to orchestrate different services into local environments for data analytics, ML and so on.</p><h3>A brief history of how we got here?</h3><p>Five years ago Docker was still very popular. The containerization of applications was still relatively new and running containers on docker-compose was the way to go. I even had my first website running on docker-compose on a <a href="https://www.digitalocean.com/products/droplets/">DigitalOcean “droplet</a>”. (They had no managed Kubernetes offering at the time.) <em>Docker-compose</em> was clunky and limited in terms of functionality.</p><p>Hence, I started learning the Kubernetes container-orchestration platform. It came out of Google and it was supposedly rather flexible and scalable. I can testify it is definitely full of features and it is getting better every day. Getting used to it takes a bit of time (well lots of time) but it is worth it. Fast forward, I am happily running containers on Google GKE, which is a managed Kubernetes deployment on Google Cloud.</p><p>The only struggle I ever had with Kubernetes was the lack of options to deploy containers in a predefined sequence, e.g. start the DB and only then the main server application. That is more of a feature of microservice architecture though because any service/container should be able to run on its own. Tight coupling between microservices is in general discouraged and for a good reason;<strong> inter-dependencies hinder scaling</strong>.</p><p><em>My name is </em><a href="https://de.linkedin.com/in/nikolay-vaklev-b0582b4a"><em>Nik Vaklev</em></a><em> and I am the founder of </em><a href="https://techccino.com/?utm_source=medium.com&amp;utm_medium=tech-blog&amp;utm_content=dev-locally-rancher"><em>Techccino Ltd</em></a><em>. If you are interested in building your own apps and products </em><a href="https://techccino.com/contact-us/?utm_source=medium.com&amp;utm_medium=tech-blog&amp;utm_content=dev-locally-rancher"><em>get in touch</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=219d5d0ba34a" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/develop-locally-containers-for-kubernetes-with-k3s-rancher-219d5d0ba34a">Develop locally containers for Kubernetes with K3s Rancher</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to call Google Cloud Run (or Cloud Functions) from Apps Scripts]]></title>
            <link>https://medium.com/geekculture/how-to-call-google-cloud-run-or-cloud-functions-from-apps-scripts-c0086289c965?source=rss-71aa094abe4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0086289c965</guid>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[google-apps-script]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Nik Vaklev]]></dc:creator>
            <pubDate>Wed, 18 Aug 2021 11:22:32 GMT</pubDate>
            <atom:updated>2021-08-27T08:19:59.159Z</atom:updated>
            <content:encoded><![CDATA[<h4>Here is hot to do it quickly and easily</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mq8C6uHqvDmfvb6CfADiMQ.jpeg" /></figure><p><em>I struggled how to make an authenticated call from </em><strong><em>Apps Scripts</em></strong><em> to </em><strong><em>Cloud Run</em></strong><em> even though I had </em><strong><em>owner</em></strong><em> rights on the GCP project. This post describes how to do it without reinventing the wheel.</em></p><h4>Background reading</h4><p>Hence, here are the references I used to get this work done. This post by <a href="https://medium.com/u/fcdb71c20074">guillaume blaquiere</a> was a good start but it didn’t work completely:</p><p><a href="https://medium.com/google-cloud/call-cloud-run-from-app-script-the-easy-way-70677086efa1">Call Cloud Run from App Script: The easy way</a></p><p>This stackoverflow issue also helped me to piece together the puzzle:</p><p><a href="https://stackoverflow.com/questions/66543047/call-google-cloud-functions-from-app-scripts">Call Google Cloud Functions from App Scripts</a></p><p>FYI, this is a good resource by <a href="https://medium.com/u/b78c1a5c6205">salmaan rashid</a> on the different GCP tokens used for authentication:</p><p><a href="https://medium.com/google-cloud/authenticating-using-google-openid-connect-tokens-e7675051213b">Authenticating using Google OpenID Connect Tokens</a></p><h3>Step by step</h3><ol><li><strong>Make sure the Apps Script is in the same GCP project as the Cloud Run service.</strong> Without that it is pretty much hopeless. Google has manuals explaining how to set the Apps Sritps project <a href="https://developers.google.com/apps-script/guides/cloud-platform-projects#standard_cloud_platform_projects">here</a>.</li></ol><p><em>Authentication and authorization work on a project level.</em> Apps Scripts creates a <strong>hidden</strong> GCP project by default. Hence, if you want Apps Scripts to interact with other GCP services, you need to move the Apps Scripts execution to the target GCP project.</p><p><strong>2. Enable the OAuth consent screen under <em>APIs &amp; Services</em> in you GCP project</strong></p><p>This is a mandatory step and there are many manuals out there describing how to do it. <a href="https://support.google.com/cloud/answer/6158849?hl=en#">Here</a> is the GCP one. The consent screen allows users with access to a given project to give permission to the OAuth 2.0 client to access services on their behalf. Just select a testing or internal type of app to avoid the verification on behalf of Google as long as this is only for internal purposes of course. Then add your email account to the test-users list.</p><p><strong>3. This Apps Scripts function calls a GCP Cloud Run service</strong></p><pre>CLOUD_RUN_URL=&quot;https://cloud-run-base-url&quot;;</pre><pre>function callCloudRun() {<br> // Use the OpenID token inside App Scripts<br> const token = ScriptApp.getIdentityToken();</pre><pre>var options = {<br>  &#39;method&#39; : &#39;get&#39;,<br>  &#39;headers&#39;: {&#39;Authorization&#39;: &#39;Bearer &#39; + token},<br> };</pre><pre>// call the server<br> var response = UrlFetchApp.fetch(CLOUD_RUN_URL + &#39;/hello&#39;, options);</pre><pre>}</pre><p>The Cloud Run service will be called using the Apps Scripts OAuth 2.0 client which you can see under <em>APIs &amp;Services &gt; Credentials</em> on GCP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_0ILKQPSs4T2qlHVpl41g.png" /></figure><p>In the authorization header of the request, the code above puts the <a href="https://openid.net/specs/openid-connect-core-1_0.html">OpenID</a> token which decoded looks something like this:</p><pre>{<br> at_hash=xxxxxxx,<br> sub=xxxxxxx,<br> aud=app-scripts-oauth2.0-client-id.apps.googleusercontent.com,<br> email_verified=true,<br> iss=<a href="https://accounts.google.com/">https://accounts.google.com</a>,<br> hd=example.com,<br> exp=1628072693,<br> iat=1628069093,<br> <a href="/service/mailto:email=name@example.com">email=name@example.com</a><br>}</pre><p>It tells the GCP firewall who is making the request and if the token is valid and the user is authorised to access the service or API, it will go through.</p><p><strong>4. Edit the Apps Scripts manifest</strong></p><p>Apps Scripts has JSON configuration file called appsscripts.json which is normally auto-generated. It is explained how to access it <a href="https://developers.google.com/apps-script/concepts/manifests">here</a>. Under oauthScopes add the three extra scopes below. They allow a script to access GCP and also to generate the OpenID token mentioned above.</p><pre>&quot;oauthScopes&quot;: [<br>  ...,<br>  &quot;https://www.googleapis.com/auth/script.container.ui&quot;,<br>  &quot;https://www.googleapis.com/auth/cloud-platform&quot;,<br>  &quot;openid&quot;<br>]</pre><p><strong>5. The last mile is the trickiest!</strong></p><p>The final piece came from the official GCP documentation on Cloud Run <a href="https://cloud.google.com/run/docs/authenticating/end-users#google-sign-in">here</a>.</p><blockquote>If you have multiple OAuth client IDs (for example, one each for Android, iOS, and web), you must re-deploy your service(s) after adding each one to ensure the service picks up the change. Similarly, if you delete a client ID, you must re-deploy your service(s) to remove that client ID and deny requests. All client IDs within a project will be accepted.</blockquote><p><strong>All I had to do was to redeploy the Cloud Run service! </strong>Whenever a Cloud Run service is deployed it stores somehow a snapshot of all the OAuth2.0 client IDs in the particular GCP project. Hence if you first deployed the service and only then you added the Apps Scripts to the GCP project, the service will NOT recognise the new client ID for the Apps Scripts OAuth 2.0 client. You just need to redeploy the service and it works.</p><h4>Conclusion</h4><p>The steps above make complete sense when you consider the GCP security model for authentication and authorization. Some may say that it looks complicated but in reality it keeps your info and resources safe.</p><p>The same approach should work for Google Cloud Functions as well.</p><p><em>My name is Nik Vaklev and I am the founder of </em><a href="https://techccino.com/?utm_source=medium.com&amp;utm_medium=tech-blog&amp;utm_content=call-cloudrun-from-appsscripts"><em>Techccino Ltd</em></a><em>. If you are interested in building your own web apps </em><a href="https://techccino.com/"><em>get in touch</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0086289c965" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-call-google-cloud-run-or-cloud-functions-from-apps-scripts-c0086289c965">How to call Google Cloud Run (or Cloud Functions) from Apps Scripts</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async and Distributed Python Server with Uvicorn, Starlette and Ray]]></title>
            <link>https://medium.com/codex/async-and-distributed-python-server-with-uvicorn-starlette-and-ray-185828ad2555?source=rss-71aa094abe4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/185828ad2555</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nik Vaklev]]></dc:creator>
            <pubDate>Fri, 06 Aug 2021 12:35:58 GMT</pubDate>
            <atom:updated>2021-08-19T08:22:52.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*33BSfncAgxHAc14flTcgPA.jpeg" /></figure><p><em>Python dominates data science at the moment and many companies are building server applications with it because of that. </em><strong><em>Async Python</em></strong><em> with </em><strong><em>Uvicorn</em></strong><em>, </em><strong><em>Starlette</em></strong><em> and </em><strong><em>Ray</em></strong><em> are a great opportunity for creating scalable and distributed server apps.</em></p><h4>Intro</h4><p>As a system architect I often worry whether what we do is “scalable”. But what does that mean? Scalability has many aspects and it is highly dependent on the app context. For instance, the back-end scalability for a mobile app has very different requirements compared to serving a static website. The kind of applications that concern me</p><ul><li>are normally web-based;</li><li>have a few users;</li><li>and often crunch data.</li></ul><p>The back ends for data processing are often written in Python as opposed to the faster Java.</p><p>Three years ago I went to PyCon in London. I was shocked to discover that many organisations, including bank, run server application written in Python. Fair enough, the banks were not using them for nanosecond high-frequency trading but I always assumed these guys worked only with Java or something even faster like C++.</p><p>Nowadays, we also offer customers back ends written in Python. This language is invaluable when it comes to crunching data and data scientists love it. Anyone who works with data scientists understands the pain of transforming their Python scripts into something that can be run in production. Imagine having to translate every script into a different language and the mess is complete. Every time I do it I swear that next time I will just run the script as it is!</p><p>Python is not the fastest option out there but when it comes to crunching data, users are used to waiting a little bit longer than let’s say for loading a webpage. So at least for now, this language will keep dominating data processing, wrangling, AI , etc.</p><p>Instagram for instance has invested heavily over the years in Python servers. For example they published their own compilation for Python 3.8 trying to improve the performance of their servers:</p><blockquote>Cinder is Instagram’s internal performance-oriented production version of CPython 3.8. (<a href="https://github.com/facebookincubator/cinder">source</a>)</blockquote><blockquote>Instagram Server is a several-million-line Python monolith, and it moves quickly. (<a href="https://instagram-engineering.com/python-at-scale-strict-modules-c0bb9245c834">source</a>)</blockquote><p>Ok but what about serving a moderate amount of requests from a Python server? Isn’t Python single-threaded? Yes, it is and this is a problem. Fortunately this problem has a few possible solutions.</p><h4><a href="https://www.uvicorn.org/">Uvicorn</a> + <a href="https://www.starlette.io/">Starlette</a> + async for processing</h4><p>Asynchronous servers are easy to reason about and they make it simple to squeeze more out of one CPU. While the server is waiting for an HTTP request to return, it can work on other tasks. It is as simple as that. Here is a simple async Uvicorn server example:</p><pre>from starlette.applications import Starlette<br>from starlette.requests import Request<br>from starlette.responses import JSONResponse, PlainTextResponse<br>from starlette.routing import Route</pre><pre>async def homepage(req: Request):<br>    return PlainTextResponse(&quot;ok: service is running&quot;)</pre><pre>async def echo(req: Request):<br>    try:<br>        res = await req.json()</pre><pre>    except Exception as err:<br>        res = {&quot;message&quot;: &quot;failed JSON message&quot;}</pre><pre>    return JSONResponse(res)</pre><pre>app = Starlette(<br>    debug=True,<br>    routes=[<br>        Route(&quot;/&quot;, homepage, methods=[&quot;GET&quot;]),<br>        Route(&quot;/echo&quot;, echo, methods=[&quot;POST&quot;]),<br>    ],<br>)</pre><p>To start this server all you need to do is to run this command:</p><p>uvicorn main:app --workers 2</p><p>assuming the script above is in a file called main.py.</p><p>Congrats! You just launched an HTTP server with three Python processes, main process and two workers/children. Using workers helps a lot because they are independent python processes and if one worker is busy another one can process the incoming requests. Uvicorn does not seem to have a limit on the number of workers one can launch but each worker is a separate process which takes up resources regardless of the current server load. Each process executes requests asynchronously as well.</p><p>A problem arises with these workers when the server needs to do some heavy lifting, e.g. process large batch of data, run an ETL, etc. The workers are meant for processing requests so anything long-running like ETLs is a bad idea. They by design have a timeout for responding to a request of the order of minutes, which makes sense for requests but not for longer computations. Enter ray.io!</p><h4><a href="https://ray.io/">Ray.io</a> for distributed computing</h4><p>Ray is a relatively new addition to the Python ecosystem. It was publicly announced first in 2018 I think. Ray fills in an important gap, namely the ability to orchestrate multiple python processes in a cluster. It was meant specifically for crunching through lots of data for ML training. Ray allows you to start an actor process with its own resources and wait patiently for the results to become available.</p><p>A reasonable scenario is sending a request to the server to run an ETL process. The request is answered immediately with “ok, the ETL is running” while the actual data crunching is off-loaded to Ray and the user can come back later to check the result. Ray itself scales seamlessly up and down depending on demand.</p><p>This is a simple example of how to create an Uvicorn server which uses Ray actors.</p><pre>import ray<br>from starlette.applications import Starlette<br>from starlette.responses import JSONResponse, PlainTextResponse<br>from starlette.routing import Route<br>from starlette.requests import Request</pre><pre><a href="http://twitter.com/ray">@ray</a>.remote<br>class EchoActor(object):<br>    def __init__(self):<br>        pass</pre><pre>def response(self, jsonMessage: dict):<br>        return JSONResponse(jsonMessage)</pre><pre>ray.init()<br>ray.nodes()</pre><pre>async def echo(req: Request):</pre><pre>    echoBot = EchoActor.remote()<br>    try:<br>        res = await req.json()</pre><pre>    except Exception as err:<br>        res = {&quot;message&quot;: &quot;failed JSON message&quot;}</pre><pre>    remoteJob = await echoBot.response.remote(res)</pre><pre>    return remoteJob</pre><pre>app = Starlette(<br>    debug=True,<br>    routes=[<br>        Route(&quot;/echo&quot;, echo, methods=[&quot;POST&quot;]),<br>    ],<br>)</pre><h4>Conclusion</h4><p>The actor model for computation and its use for distributed/parallel computing is not new. Scala + Akka actors have been around for more than 10 years. It is great to see similar concepts finally being available within the Python environment. One major difference is the overhead of Ray actors in comparison to Akka ones. In the case of Ray they are separate Python processes each one with its own memory and CPU requirements. Initialising a new Ray actor takes a bit of time or at least much longer than then equivalent step in Akka. Hence, spinning up and down Ray actors needs to be done with some care but that is still much easier than trying to create the same functionality from scratch (and less buggy). For comparison Akka actors are very light and have minimal footprint; so much so that easily you can have 10,000+ of them running in memory.</p><p>For completeness, Uvicorn workers are very similar to Ray actors but they are meant to process server request really and do not scale up or down based on demand.</p><p>In short Ray is not perfect but it adds a vital functionality to the Python ecosystem and combined with async server frameworks like Uvicron, it goes a very long way!</p><p><em>My name is Nik Vaklev and I am the founder of </em><a href="https://techccino.com/"><em>Techccino Ltd</em></a><em>. If you are interested in building your own web apps </em><a href="https://techccino.com/"><em>get in touch</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=185828ad2555" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/async-and-distributed-python-server-with-uvicorn-starlette-and-ray-185828ad2555">Async and Distributed Python Server with Uvicorn, Starlette and Ray</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Option and Either From fp-ts (Typescript)]]></title>
            <link>https://medium.com/swlh/using-option-and-either-from-fp-ts-typescript-30dc8894786?source=rss-71aa094abe4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/30dc8894786</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Nik Vaklev]]></dc:creator>
            <pubDate>Thu, 28 Jan 2021 14:30:22 GMT</pubDate>
            <atom:updated>2021-09-14T13:43:12.063Z</atom:updated>
            <content:encoded><![CDATA[<p>I like functional programming because it has saved me a few times over the years from either making mistakes or going down rabbit holes. It is reassuring knowing that given the same input the output is always the same.</p><p>I colleague told me about <a href="https://gcanti.github.io/fp-ts/">fp-ts</a> a few years ago. Unfortunately, I found almost no useful manuals to get started and I gave up on it. For instance, I quickly lost the plot trying to parse the dense vocabulary around groups, semi-groups, pro-functors, etc. Then I tried writing my own version of the option and either monads and they worked fine in plain JavaScript but I couldn’t get them to work with the types system of Typescript.</p><p>Fast forward, I decided to give <strong>fp-ts</strong> a second chance after going through a few books on functional programming, e.g. <a href="https://www.scalawithcats.com/">Scala with Cats</a> and <a href="https://github.com/hmemcpy/milewski-ctfp-pdf">Category Theory for Programmers</a>. I knew a great deal more about category theory (mostly what it is not) but that didn’t help me with fp-ts except that I was not afraid of “free monoids” anymore. All these definitions in category theory are mostly noise to programmers. They have precise mathematical definitions and if that’s your area of research you should know them but the actual concepts behind them are rather simple and unless you plan a career in mathematics all you need to understand is what they do. Knowing the definitions, theorems, laws and so on is useful only when you want to be an expert and impress people. I find it way more useful to know what things do and mean because that allows me to use them.</p><p>Anyhow! Having read books and watched <a href="http://www.brendanfong.com/programmingcats.html">an online course from MIT</a> on the subject I managed to get something useful done with fp-ts in a real project. I had to solve the old problem of fetching data from the server and displaying them on a web form. The problem was that the library I was using, <a href="https://www.carbondesignsystem.com/">IBM Carbon Design</a>, had a few quirks. For instance, the <em>NumberInput</em> component was not as good and it was better to use <em>TextInput</em> component even for numerical values and convert the output from text to number on the fly. The Date components turned out also to be a bit fiddly and required data manipulation. These were good examples where functional programming works really well because all you need to do is write stateless transformations to format the inputs and outputs.</p><p>Here is a en example using the <em>Option</em> monad:</p><pre>import React, { useState } from &quot;react&quot;;<br>import * as O from &quot;fp-ts/lib/Option&quot;;<br>import { flow } from &quot;fp-ts/lib/function&quot;;<br>import {<br>  FormGroup,<br>  TextInput,<br>  TextArea,<br>  Toggle,<br>  DatePicker,<br>  DatePickerInput,<br>  Select,<br>  SelectItem,<br>} from &quot;carbon-components-react&quot;;</pre><pre>// flow: Performs left-to-right function composition. The first argument may have any arity, the remaining arguments must be unary.<br>// the output of safeDate is Option&lt;Date&gt;<br>const safeDate = flow((val: Date) =&gt; val || undefined, O.fromNullable);</pre><pre>// toUndefined(date: Option&lt;Date&gt;) =&gt; Date | undefined<br>const getSafeDate = flow(O.toUndefined, (val) =&gt; val || &quot;&quot;);</pre><pre>const Component = () =&gt; {<br>  const [date, setDate] = useState();</pre><pre>return (<br>    &lt;DatePicker<br>      dateFormat=&quot;d/m/Y&quot;<br>      datePickerType=&quot;single&quot;<br>      onChange={(event: [Date]) =&gt; setDate(safeDate(event[0]))}<br>      value={getSafeDate(date)} // the DatePicker value is either Date or empty string<br>    &gt;<br>      &lt;DatePickerInput<br>        id=&quot;date-picker-calendar-id&quot;<br>        placeholder=&quot;dd/mm/yyyy&quot;<br>        labelText=&quot;My Date&quot;<br>        type=&quot;text&quot;<br>        name=&quot;date_component&quot;<br>      /&gt;<br>    &lt;/DatePicker&gt;<br>  );<br>};</pre><p>This is an example with <em>Either</em> monad:</p><pre>import React, { useState } from &quot;react&quot;;<br>import * as E from &quot;fp-ts/lib/Either&quot;;<br>import { pipe } from &quot;fp-ts/lib/function&quot;;</pre><pre>// formats number string to 2 decimal points by default<br>export const formatNumToFixed = (num: string, dps: number = 2): string =&gt; {<br>  const test = num.match(/\.\d*$/);<br>  const testStr = test &amp;&amp; test.length ? test[0] : undefined;</pre><pre>if (testStr &amp;&amp; testStr.length - 1 &gt; dps) return Number(num).toFixed(dps);</pre><pre>return num;<br>};</pre><pre>const numberInputValue = (<br>  val: string | null,<br>  transform: (i: string) =&gt; string<br>) =&gt;<br>  // pipe: Pipes the value of an expression into a pipeline of functions.<br>  pipe(<br>    E.fromNullable(null)(val),<br>    E.map((i) =&gt; i.toString()), // guards against number values<br>    E.map(transform),<br>    E.fold(() =&gt; &quot;&quot;, (i) =&gt; i)<br>  );</pre><pre>const NumberInputCompoenent = () =&gt; {<br>  const [percentage, setPercentage] = useState();</pre><pre>return (<br>    &lt;TextInput<br>      min=&quot;0&quot;<br>      max=&quot;100&quot;<br>      step=&quot;0.01&quot;<br>      type=&quot;number&quot;<br>      required<br>      labelText=&quot;Percentage&quot;<br>      id=&quot;input-percentage&quot;<br>      placeholder=&quot;0.00 %&quot;<br>      value={numberInputValue(percentage || null, formatNumToFixed)}<br>      name=&quot;percentage&quot;<br>      onChange={(event) =&gt; setPercentage(event.target.value)}<br>    /&gt;<br>  );<br>};</pre><p>The difference between <em>Option</em> and <em>Either</em> is simple:</p><p>Option&lt;T&gt; = Either&lt;undefined | null, T&gt;</p><p>i.e. <em>Option</em> is a “sum” of null and any type <em>T</em> whereas <em>Either</em> is a “sum” of any two types. In simple terms unpacking Option&lt;T&gt; will always give you a value of type <em>T</em> or null/undefined. <em>Either</em> is more flexible and holds either type <em>T</em> or some other type of your choosing called the “left” type, which often signifies an error of some kind.</p><p>In the first example, <em>Option</em> is used to represent the case where a value can either Dateor null . Typically this would be handled with if-statements all over the code checking at each step which one it is. In the FP world the actual value is wrapped in an <em>Option</em> “container” which does that for you. <em>Either</em> does a very similar job as shown in the second example. The aim there was to transform a percentage value between 0 and 1 (as it was held in the DB) into a value between 0 and 100 which is nicer for the user. Unfortunately in JavaScript things like this happen:</p><pre>0.1511*100 = 15.110000000000001</pre><p>whereas the user expects simply 15.11 % without the extra zeroes. The problem is analogous to the previous one but I solved it using Either&lt;null,string&gt; this time. The Either example also demonstrates nicely another feature of the FP style, namely code re-usability. numberInputValue function takes a value and another function called transform which in this case removes any extra zeroes from the numbers. But, transform can be any other function as long as its type signature is (value: string) =&gt; string .</p><p>One thing that is kind of a must to learn if dealing with functional programming though is how to read function type signatures, e.g. pipe&lt;A, B&gt;(a: A, ab: (a: A) =&gt; B): B Such kind of expressions are all over the documentation of FP libraries and authors kind of expect users to follow (or not).</p><p><em>My name is Nik Vaklev and I am the founder of </em><a href="https://techccino.com/?utm_source=medium.com&amp;utm_medium=tech-blog&amp;utm_content=option-either-ts"><em>Techccino Ltd</em></a><em> | Data Visualisation and Serverless Apps</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30dc8894786" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/using-option-and-either-from-fp-ts-typescript-30dc8894786">Using Option and Either From fp-ts (Typescript)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 challenges when using Plotly Dash for interactive web apps]]></title>
            <link>https://medium.com/analytics-vidhya/5-challenges-when-using-plotly-dash-for-interactive-web-apps-849f442582f7?source=rss-71aa094abe4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/849f442582f7</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Nik Vaklev]]></dc:creator>
            <pubDate>Thu, 07 May 2020 09:17:07 GMT</pubDate>
            <atom:updated>2021-08-27T11:28:31.826Z</atom:updated>
            <content:encoded><![CDATA[<h3>5 challenges when using Plotly Dash for web apps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8Y0kb-u3iwoEb4TCDAhnA.png" /></figure><p>My first proper encounter with Dash was relatively recently. I partnered with a company to host a Dash app in Google Cloud. Working with Dash was OK but the overall experience was not great. These are a few of the hiccups I encountered.</p><h4>Persisting information in the web page itself</h4><p>Dash apps are meant to be stateless and this is for a good reason. Normally the app will be run as multiple Python processes behind one server in order to serve multiple requests simultaneously. For any simple app using a stateless server is the best starting point because sharing state in-memory between these processes is just asking for trouble. Dash resolves this issue by storing the data in hidden elements on the webpage itself, thus a simple reload wipes out any <em>stored</em> information about the user session. Dash on the client side uses a Redux store it seems but there is no access to it.</p><p>OK, not a big deal if all you do is displaying a few charts but this is a real problem for any interactive applications.</p><h4><strong>Creating interactivity is challenging</strong></h4><p>The main mechanism in Dash for creating interactivity is server callbacks. In short, the browser calls the server and any updates to the DOM are sent back to the client, which is less efficient than executing Javascript code inside the browser. Recently <a href="https://dash.plotly.com/clientside-callbacks">client-side callbacks</a> have been added to Dash but I couldn’t work out how they are triggered except when (re)loading the webapge. I used a client callback to run a Javascript code when the page loads. It definitely saved the day but the approach has limitations. The callback has to be defined inside the Python code on the server though its execution has nothing to do with the server:</p><pre># Python client-side callback definition<br>app.clientside_callback(<br>    ClientsideFunction(<br>        namespace=&#39;clientside&#39;,<br>        function_name=&#39;DoSomething&#39;<br>    ),<br>    # the output field must match a property that is already defined<br>    # Output(&#39;div-id&#39;, &#39;style&#39;),<br>    Output(&#39;div-id&#39;, &#39;style&#39;),<br>    [Input(&#39;MyButton&#39;, &#39;none&#39;)]<br>)</pre><p>The code above declares that a function called DoSomething will be “triggered” by MyButton and update thestyle property of a div with id div-id .</p><p>This is the corresponding Javascript code on the client side:</p><pre># Javascript code<br>(function(){<br>  if(!window.dash_clientside) {window.dash_clientside = {};}<br>  window.dash_clientside.clientside = {<br>    <br>      DoSomething: () =&gt; {<br>        // ADD CODE HERE<br>        return {display: &#39;none&#39;}   <br>      },<br>  }<br> })();</pre><p>This is what the element looks like:</p><pre># Python code defining the page elements<br>html.Div(className=&#39;style-me-with-css&#39;, id=&#39;DIV-ID&#39;, style={&#39;display&#39;: &#39;none&#39;}, children=[<br>  // DO SOMETHING HERE<br>])</pre><p>For instance, if the Divdefined above does not have explicitly the style property referenced in the Python callback, the Javascript code will not be executed in the browser. Confused?</p><p><strong>Conclusion:</strong> this is a very convoluted scheme trying to achieve something that should be rather simple.</p><h4>It is difficult to customize the API</h4><p>In my project, the Dash app was hosted behind an API gateway, which takes care of user authentication. Here I hit a wall trying to get Dash to work with the gateway. The reason was rather unfortunate. The root for any dash app must have forward slash at the end: <a href="https://my/">https://my</a>.dashserver.com/app1<strong>/</strong></p><p>This URL htts://my.dashserver.com/app1 won’t work.</p><p>I thought that was a strange choice but hey ho. Then I realised that my gateway couldn’t work URLs with a slash at the end!</p><p><strong>Solution:</strong> hack the underlying Flask app to add a home-page route <strong>without</strong> the forward slash at the end of it. Arrgghhh!</p><p>Yes, it did work out just fine eventually but it was not easy! The major drawback for me is the lack of built-in methods to extend the Dash API/ functionality. You have to hack the Flask app.</p><h4>No lists in the Dash HTML</h4><p>Crazy! Yes, there is no simple way of defining a list. This is what I did:</p><pre># Python server code<br>html.Div([<br># li 1<br>  html.P([<br>    html.B(&#39;1. &#39;),<br>    html.Span(&#39;Click here&#39;)<br>  ]),</pre><pre># li 2<br>  html.P([<br>    html.B(&#39;2. &#39;),<br>    html.Span(&#39;Click here&#39;)<br>  ]),<br>...<br>])</pre><p>Again, it does the job especially when combined with a bit of CSS, but it does not look great!</p><p><em>That brings me to the last point:</em> it is not possible to write plain HTML with Dash. An easy workaround for the case above would have been a Python component which can render any HTML. Then I could easily render text, lists, etc. Look at the code above! Writing a simple paragraph with a bit of text formatting requires dedication!</p><p><strong>Update [11/05/2020]: </strong>It turns out it is possible to have lists and raw HTML using the Markdown component:</p><pre>dcc.Markdown(&#39;&#39;&#39;<br>* list item A<br>* list item B<br>* ...</pre><pre>&lt;ol&gt;<br>  &lt;li&gt;item one&lt;/li&gt;<br>  &lt;li&gt;item two&lt;/li&gt;<br>  &lt;li&gt;...&lt;/li&gt;<br>&lt;/ol&gt;<br>&#39;&#39;&#39;)</pre><p>dcc.Markdown accepts a boolean flag called dangerously_allow_html making it possible to write raw HTML after all.</p><p>I discovered all of this by randomly browsing the latest Dash documentation.</p><h4>Oh, one last thing</h4><p>That’s my favourite!<strong> It is impossible for two Python callbacks to update the same element! </strong>I know! This is so much fun. You are not allowed to do this:</p><pre><a href="http://twitter.com/app">@app</a>.callback([<strong>Output(&#39;target-div&#39;, &#39;children&#39;)</strong>],<br>              [Input(&#39;upload-data&#39;, &#39;contents&#39;)])<br>def callback1(contents, filename):<br>    return PreventUpdate</pre><pre><a href="http://twitter.com/app">@app</a>.callback([<strong>Output(&#39;target-div&#39;, &#39;children&#39;)</strong>],<br>              [Input(&#39;upload-data-two&#39;, &#39;contents&#39;)])<br>def callback1(contents, filename2):<br>    return PreventUpdate</pre><p>I found out that resolving this issue has been a feature request since 2018: <a href="https://community.plotly.com/t/why-can-an-output-only-have-a-single-callback-function/14691">https://community.plotly.com/t/why-can-an-output-only-have-a-single-callback-function/14691</a></p><p>Hence, developers might be tempted to create one almighty callback which accepts all the possible inputs and outputs and based on some convoluted logic sends back the “right” response.</p><p>A colleague on the project did come up with an elegant solution. Since there are no limitations on the inputs, it is OK to add extra inputs to some callbacks as to trigger different responses based on the combinations of inputs. The above example then becomes this:</p><pre><a href="http://twitter.com/app">@app</a>.callback([Output(&#39;target-div&#39;, &#39;children&#39;)],<br>              [Input(&#39;upload-data&#39;, &#39;contents&#39;), <br>               Input(&#39;upload-data-two&#39;, &#39;contents&#39;)])<br>def callback1(contents, filename):<br>    ctx = dash.callback_context<br>    source = ctx.triggered[0][&#39;prop_id&#39;].split(&#39;.&#39;)[0]<br>    if source == &#39;upload-data&#39;:<br>        return &#39;happy days&#39;<br>    elif source == &#39;upload-data-two&#39;:<br>        return &#39;this is another way of updating the same element&#39;</pre><h3>Conclusion</h3><p>Dash does work OK when you want to create a simple dashboard and host it on your laptop. For any other situation you either need to pay them to host it for you and take advantage of their enterprise features or hack your way through.</p><p>Also creating interactive applications, which requires a complex UI, is not recommended. In my next project I want to try <a href="https://bokeh.org/">Bokeh</a>. Their documentation makes more sense just looking at it!</p><p><em>My name is Nik Vaklev and I am the founder of </em><a href="https://techccino.com/?utm_source=medium.com&amp;utm_medium=tech-blog&amp;utm_content=five-dash-challenges"><em>Techccino Ltd</em></a><em> | Data Visualisation and Serverless Apps. If you are interested in building your own web apps </em><a href="https://techccino.com/about"><em>get in touch</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=849f442582f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/5-challenges-when-using-plotly-dash-for-interactive-web-apps-849f442582f7">5 challenges when using Plotly Dash for interactive web apps</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure documents in the cloud with GPG]]></title>
            <link>https://nikolay-vaklev.medium.com/secure-documents-in-the-cloud-with-gpg-3b4a61769cd1?source=rss-71aa094abe4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b4a61769cd1</guid>
            <dc:creator><![CDATA[Nik Vaklev]]></dc:creator>
            <pubDate>Fri, 07 Feb 2020 08:04:48 GMT</pubDate>
            <atom:updated>2020-04-22T14:33:34.712Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In this post I focus on why and how I created a very simple desktop app called </em><a href="https://bitbucket.org/vnl2k/encryptsync/src/master/"><em>Encrypt-Sync</em></a><em>, which can encrypt and sync files with a cloud-storage provider while you are working on them.</em></p><p>I was one of the early adopters of Google Drive. It is really good at backing up large quantities of data and giving you access wherever you are, but there is a catch… All the data are up in the cloud, the cloud vendor has access to them and they make the most of it. Google Drive now offers the ability to search inside your documents for more relevant results: a cool idea unless we are talking about your business records. Do we really want these companies to access all our information to allegedly improve their service at the cost of sensitive information?</p><p>Strictly speaking any cloud storage provider stores the data in an encrypted format on the physical hard drives, a.k.a. <em>encryption at rest</em>. Also any communication between the client, i.e. mobile apps, web browsers, etc., and the server is also encrypted with TLS (HTTPS). As an example, see Dropbox security documentation <a href="https://www.dropbox.com/business/trust/security/architecture">here</a>. The main reason for this is that even if someone was to hack a particular cloud they would not be able to read any file from any user. But still, you <em>and the storage provider</em> have full access to everything.</p><p>There are many apps which can “secure” your data in the cloud and guarantee that you are the only person who read the files. A few notable examples:</p><ul><li><a href="https://www.box.com/">Box.com</a>: starts at €4.27 per user/month with a minimum of 3 users;</li><li><a href="https://tresorit.com/">Tresorit</a>: starts at $25 for two users per month;</li><li><a href="https://www.sync.com/">Sync</a>: starts at $10 per user per month;</li><li><a href="https://storj.io/">Storj</a>: an distributed network of nodes for encrypted file storage (if you can set it up);</li><li>even more suggestions: Boxcryptor<strong>, </strong>Cryptomator, pCloud, Spideroak, etc.</li></ul><p>But, you have to pay for them because “freemium” is not really a viable option for secure-storage vendors. There are many reasons for that, but I would say that implementing security layers and encryption is an expensive business, in terms of people and technologies. Doing it on the cheap is the same as not bothering at all. Furthermore, it requires more computational resources because encrypting and decrypting data quickly is computationally expensive and the server time for it costs money.</p><p><strong>Where does that leave us?</strong> Paying for these services is an option but frankly not worth it unless you are a business with multiple users who must collaborate securely and handle sensitive information. For individuals, they need to be handling sensitive information regularly to justify the costs.</p><p>I had a breakthrough a few years ago when I realised that I had to protect just a small fraction of my documents. I was never going to encrypt all my photos for instance or the articles I have downloaded from the Internet. The truth is most direct users and small businesses need to protect a handful of documents.</p><p>I knew of GNU Privacy Guard which is a free and rather well-regarded tool for encrypting information with public-private keys, also called <em>asymmetric encryption</em>. The only problem with using it directly is that you must never forget to encrypt any changed files and upload them on Dropbox for instance. <strong>OK, so the encryption side is actually solved and free if you do it by yourself.</strong></p><p><strong>If only there were tools that can sync two folders…</strong> Well this problem has a solution as well. It is pretty common for web developers to use tools that monitor all the files they work on for changes. The tools would re-compile the website or app after every change and let the developer see the updated web pages. The point is that we have pretty good tools for monitoring folders and files for changes. <strong>Can we marry the two?</strong></p><p><strong>Enter </strong><a href="https://bitbucket.org/vnl2k/encryptsync/src/master/"><strong>Encrypt-Sync</strong></a><strong>!</strong></p><p>I have worked on it for the last two years on and (mostly) off. It is a Node.js app which:</p><ul><li>watches a particular folder for changes;</li><li>encrypts any modified file with GNU Privacy Guard (GPG) in memory;</li><li>and saves the scrambled version in a Dropbox or Google Drive folder (or anywhere else you like really).</li></ul><p>The app makes the most of GPG, cloud storage and a Node.js package called <a href="https://www.npmjs.com/package/chokidar">chokidar</a>!</p><p>The app was designed to use a minimal number of 3rd party packages and basically be as lightweight as possible. Normally simplicity affords good maintainability over time and decent performance.</p><p>Hence, the actual work in the early days focused on experimenting with different packages and finding one that:</p><ul><li>could detect changes to both folders and files;</li><li>is well-established;</li><li>and properly maintained.</li></ul><p><em>Chokidar</em> ticked all the boxes: has more than 16 million downloads per week from <em>NPM</em>, is actively maintained and forms a core part of <em>Webpack,</em> which is itself used nowadays for any web app development out there.</p><h3>Limitations</h3><p><strong>The metadata are still not protected</strong>, i.e. file names, modification dates, folder structure, etc. A lot can be worked out from this information but this is a problem for many secure systems, including apps like <em>Whatsapp</em> because Facebook cannot read the actual content of the messages but they know who you are talking to.</p><p><strong>It protects your info only in the cloud</strong>. If someone was to hack your computer they can easily find the unencrypted version of the files on your hard drive. On the other hand, if someone hacked your computer that’s probably your least problem.</p><p><strong>Encrypt-Sync can only encrypt files </strong>and cannot be used to reverse the process. The good news is that technically there is no problem to do it; I am just looking for the most elegant and user-friendly way to implement it. <strong>Interim solution:</strong> create a simple bash function to decrypt individual files, e.g.</p><pre>function decrypt() {<br> doc=$1 <br># assumes doc has this format `/path/to/file/filename.extention.<strong>gpg</strong><br> gpg --output ${doc:0:-4} --decrypt $doc<br>}</pre><p><strong>This app does require technical knowledge of sorts</strong>, e.g. how to generate GPG keys for the encryption step and therefore cannot be used easily by non-technical users. It cannot protect the whole world unfortunately.</p><h3>Conclusion</h3><p>One probably wonders why I am advertising it at all if it cannot eradicate poverty, make all you communications private and defeat cancer. Well, I actually found it very useful. I use it almost every day to back-up changes to a handful of files related to my business knowing that “nobody” can just hack my cloud account and read my business plans or pension plan or … In short, if I find it so useful, maybe other people will as well.</p><p>Regarding vendors of encrypted cloud file-storage I think they have a problem. There are probably not that many people and organisations willing to pay them top bucks for their services. Also creating something simple to suite your needs is actually not a problem these days and it is free. The entire code for the app is ca. 200 lines long. Almost anyone can maintain it. My company website is more complex than that!</p><h3>Acknowledgements</h3><p>The “simplicity” of Encrypt-Sync is illusory in a way because it is standing on the shoulders of giants like GPG and Node.js. Fortunately for me, I did not have to (re-)invent the wheel this time!</p><p><em>My name is Nik Vaklev and I am the founder of </em><a href="https://techccino.com/"><em>Techccino Ltd</em></a><em> | Data Visualisation Consulting and Software.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b4a61769cd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Four python frameworks for parallel processing]]></title>
            <link>https://nikolay-vaklev.medium.com/need-for-speed-in-python-d64f3da0fb7d?source=rss-71aa094abe4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d64f3da0fb7d</guid>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nik Vaklev]]></dc:creator>
            <pubDate>Sat, 25 Jan 2020 18:01:51 GMT</pubDate>
            <atom:updated>2021-09-14T13:48:32.323Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Ray, Numba, Dask and Vaex are a few of the Python libraries that can save you precious time when working with big data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhIPSFPd8V2y5SKGMKteDw.png" /></figure><p>Python is a standard tool for analysing and visualising data. The process looks generally as follows:</p><ol><li>loading the data from different sources, SQL databases, files, etc.;</li><li>reshaping the data, which may involve simple data cleansing, some calculations and checks on the raw data, etc.;</li><li>(building a predictive model;)</li><li>plotting the results.</li></ol><p>It all works until the dataset gets bigger or the calculations require more resources, e.g. RAM and CPUs. A source of frustration for analysts is waiting for the code to execute. If it takes long, iterating the code becomes a protracted and torturous process. Hence, we all try writing somewhat efficient code. Here I want to review a few libraries that can save you time when dealing with bigger datasets.</p><h4><a href="https://docs.dask.org/"><strong>Dask</strong></a></h4><p>If data frames are your preferred tool, <strong>Dask</strong> can be an easy way to speed up things.</p><blockquote><strong>“Big Data” collections</strong> like parallel arrays, dataframes, and lists extend common interfaces like <em>NumPy, Pandas, or Python iterators</em> to larger-than-memory or distributed environments.</blockquote><p>The idea is simple. The library offers APIs which mimic NumPy arrays or Pandas dataframes but the underlying implementation does the calculations in parallel. It also has an interface for the standard Python module <em>concurrent.futures </em>library. For example:</p><pre>import pandas as pd      <br>df = pd.read_csv(&#39;2015-01-01.csv&#39;)<br>df.groupby(df.user_id).value.mean()</pre><pre>import <strong>dask.dataframe</strong> as dd<br>df = dd.read_csv(&#39;2015-*-*.csv&#39;)<br>df.groupby(df.user_id).value.mean().<strong>compute</strong>()</pre><p>2. <a href="https://docs.vaex.io/en/latest/"><strong>Vaex.io</strong></a></p><blockquote>Vaex is a python library for lazy <strong>Out-of-Core DataFrames</strong> (similar to Pandas), to visualize and explore big tabular datasets. It can calculate <em>statistics</em> such as mean, sum, count, standard deviation etc, on an <em>N-dimensional grid</em> up to <strong>a billion</strong> objects/rows <strong>per second</strong>.</blockquote><p><strong>Vaex</strong> is similar to <strong>Dask</strong> as it offers another implementation for data frames. Vaex evaluates matrix operations lazily and also minimises any data copying. The latter becomes a real problem if you work with large datasets (&gt; 1GB). The library has additionally in-built support for a few visualisations, mostly stats related. They are great for exploring large datasets.</p><p>A sub-module of the library offers APIs for Apache Arrow, which is in-memory columnar store. Support for Arrow is a rather cool idea because it allows access to the same data using multiple languages. For instance, a Python process can load and crunch the data and store it in Arrow. A Java process can pick up the same data from memory without the need for serialisation/deserialisation.</p><p>3. <a href="http://numba.pydata.org/"><strong>Numba</strong></a></p><p>The big idea behind this library is speeding-up your code at run time with <strong>JIT</strong> (just-in-time) optimisations.</p><blockquote>Numba translates Python functions to optimized machine code at runtime using the industry-standard <a href="https://llvm.org/">LLVM</a> compiler library. Numba-compiled numerical algorithms in Python can approach the speeds of C or FORTRAN.</blockquote><p>The magic happens using decorators:</p><pre>from numba import jit, int32<br><br><strong>@jit(int32(int32, int32))</strong><br>def f(x, y):<br>    # A somewhat trivial example<br>    return x + y</pre><p>Through the decorator <em>@jit(int32(int32, int32))</em> the LLVM compiler knows that this function takes two 32-bit integers as inputs and returns a 32-bit integer. The compiler will optimise the memory allocation and function calls accordingly. The aim is to reduce the standard overhead in Python, where all variables, including number, string, etc., are actually complex objects in the computer memory. The decorators are unobtrusive and easy to add/remove. JITs are limited, though, to optimising simple numerical calculations.</p><p>4. <a href="https://github.com/ray-project/ray"><strong>Ray</strong></a></p><blockquote>Ray is a fast and simple framework for building and running distributed applications.</blockquote><p><em>Ray</em> is a real treat! It is a framework for distributed computing. Ray can span multiple nodes or simply help you make the most of you CPUs. The reason I liked it is that it allows direct control over the execution:</p><pre>import ray<br>ray.init()<br><br>@ray.remote<br>def f(x):<br>    return x * x<br><br>futures = [f.<strong>remote</strong>(i) for i in range(4)]<br>print(ray.get(futures))</pre><p>The call to <em>remote</em> triggers the asynchronous computation. The call to <em>get </em>forces the main thread to wait for all the “futures” to finish. I like this approach to parallel computing because it is closer to <strong>Scala </strong>futures and <strong>Akka</strong> actors. The beauty of distributed computing is that you can package any long-running process and wait for it to report back (or not!) without blocking the main thread.</p><p>Another cool feature of Ray is the use again of Apache Arrow to share data between process, which opens the door for integration with other languages.</p><p>I used Ray to optimise writing to disk in this <a href="https://github.com/vnl2k/datareducer/blob/master/examples/uber-nyc-data/main-stream-ray.py">example</a>. The code changes required in order to include Ray were minimal but the speedup was significant: from 270s down to 170s.</p><p>5.<strong> If you are really desperate nothing beats writing plain C</strong></p><p>Python is C lang under the hood. Well, lots of C code to be frank. But, if you have a really well-defined problem translating the routines into C and adding a thin wrapper to interface with Python is still the best answer.</p><h4>Conclusion</h4><p>As you can see here, there is no best solution. There are multiple solutions depending on the problem at hand.</p><p>I often find myself in a situation where I want to execute long-running computations in a non-blocking way. Hence, Ray is now my preferred choice in Python for parallel computing. Otherwise CPU bound jobs end-up running on a single core sequentially since Python is single-threaded by default due to the Global Interpreter Lock. <em>N.B.</em> There are modules in Python for running processes in parallel but they are often low-level which means extra work is needed every time to parallelise the tasks (with mixed results in my case).</p><p>Once, you are using all CPUs, optimising basic calculations can be done with Numba with JITs. The best approach, but the least safe one, is writing C modules, though. If you are brave, of course.</p><p>I personally do not think optimised data frames (Dask, Vaex, etc.) are a great option. If you are processing such large data volumes on your computer you should probably think of using PySpark data frames running on a remote cluster. Loading 8GB in memory on a normal machine, cannot ever possibly be fast.</p><p><em>My name is Nik Vaklev and I am the founder of </em><a href="https://techccino.com/?utm_source=medium.com&amp;utm_medium=tech-blog&amp;utm_content=python-par-processing"><em>Techccino Ltd</em></a><em> | Bespoke Business Apps.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d64f3da0fb7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>