<?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 Scott Ralph on Medium]]></title>
        <description><![CDATA[Stories by Scott Ralph on Medium]]></description>
        <link>https://medium.com/@scott-ralph?source=rss-bf071925590d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6AkimH5eUBZVZWAzj56Thg.jpeg</url>
            <title>Stories by Scott Ralph on Medium</title>
            <link>https://medium.com/@scott-ralph?source=rss-bf071925590d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:46:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@scott-ralph/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[Canada Amateur Radio Advanced Exam (Part 2)]]></title>
            <link>https://scott-ralph.medium.com/canada-amateur-radio-advanced-exam-part-2-7b7cde53bbda?source=rss-bf071925590d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b7cde53bbda</guid>
            <category><![CDATA[exam-preparation]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[amateur-radio]]></category>
            <dc:creator><![CDATA[Scott Ralph]]></dc:creator>
            <pubDate>Fri, 11 Feb 2022 18:13:38 GMT</pubDate>
            <atom:updated>2022-02-11T19:05:52.183Z</atom:updated>
            <content:encoded><![CDATA[<p>Electrostatic- and Electromagnetic-Field, &amp; Skin Effect, and Resonance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*HC0NWoREAU5cO3b1.jpeg" /></figure><h3>Electromagnetic Field</h3><ul><li>When electrons flow through a wire, a magnetic field, proportional to the electron flow, is formed around the wire.</li><li>The direction of the magnetic field is determined by the left-hand-rule.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*31xl-cZY3DCqldZL5oZQfg.png" /></figure><ul><li>Place your left hand on a wire, wrap your fingers around the wire with the thumb pointing in the direction of electron flow (from neg. to pos.). The magnetic field is in the direction of your fingers around the wire</li><li>Energy stored in the electromagnetic field is called <strong>inductance, </strong>measured with units of <strong>Henrys</strong>.</li><li>The amount of inductance in a coil is determined by:<br>It’s diameter<br>Spacing of the coils<br>Number of coils<br>The material of the center</li></ul><h3>Electrostatic Field</h3><p>Electric charge (current) stored in an electrostatic field is termed <strong>capacitance, </strong>measured in units called farads. The stored energy is <strong>potential energy</strong>. Capacitors typically consist of small plates that hold the charge, separated by an insulator. The amount of capacitance is determined by:</p><ul><li>The area of the plates</li><li>The amount of separation</li><li>Material of the dialectic</li></ul><h3>Skin Effect</h3><ul><li>The an applied DC current, the charge carriers are evenly distributed thought the cross-section of the conductor.</li><li>With AC current, strong magnetic fields start to form in the center of the conductor, causing the charge carriers to move towards the outside, or “skin” of the conductor, where there is less resistance.</li><li>The skin-effect becomes more and <strong>more pronounced</strong> as the frequency of the applied AC <strong>increases</strong>.</li></ul><h3>Series Resonance</h3><p>The two types or resonance are given below. For the purposes of the exam, however, quantitative questions are limited to the <strong>Series Resonant</strong> circuits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*sXI7rdo87rN5hgZtMQJ_hg.png" /></figure><p>Resonance in a circuit occurs when the <strong>inductive reactance,</strong> (X subscript L) is equal but of opposite sign to the <strong>capacitive reactance</strong> (X subscript C).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*3lYBTfMJ0f8FlJMSUoZalA.png" /></figure><p>It goes without saying that resonance can only occur in AC. The frequency at which this circuit will be said to be at resonance is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*trF2DCsAtjz3vT0Islooqw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b7cde53bbda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Canada Amateur Radio Advanced Exam (Part 1)]]></title>
            <link>https://scott-ralph.medium.com/canada-amateur-radio-advanced-exam-part-1-504d4af961a8?source=rss-bf071925590d------2</link>
            <guid isPermaLink="false">https://medium.com/p/504d4af961a8</guid>
            <category><![CDATA[ham-radio]]></category>
            <category><![CDATA[exam-preparation]]></category>
            <category><![CDATA[electronics]]></category>
            <dc:creator><![CDATA[Scott Ralph]]></dc:creator>
            <pubDate>Fri, 11 Feb 2022 15:14:45 GMT</pubDate>
            <atom:updated>2022-02-11T18:16:10.579Z</atom:updated>
            <content:encoded><![CDATA[<h4>RC Circuits — Time Constance for Capacitive and Inductive Circuits</h4><p>For Part 2, follow this <a href="https://scott-ralph.medium.com/canada-amateur-radio-advanced-exam-part-2-7b7cde53bbda">link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*tMj-am2_5ZWg1xU-ZfTGIg.jpeg" /></figure><p>This article summarizes questions that are on the Canadian Radio Amateur Advanced Exam. See the section found at this <a href="https://www.ic.gc.ca/eic/site/025.nsf/eng/h_00040.html">link</a>. Sections will be added as I study for this exam.</p><p>Given the following circuit (see <a href="https://crcit.net/c/de5417429eae4f4b8d7302ca75557664">link</a>):</p><figure><img alt="RC Circuit" src="https://cdn-images-1.medium.com/max/200/1*cErb4YhHA96rcXT8d0ktvA.png" /></figure><p>the charging of the capacitor, when the switch is closed, is related to the time constant, τ, which is purely a function of the resistance, R, measured in ohms, and the capacitance, C, measured in Farads. Voltage as a function of time is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*L_dj2SMe6RzdqmM-G5E-QQ.png" /></figure><p>The <strong>time constant, </strong>τ, is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*l8kWcdWjFLXI79e9xKDdfg.png" /></figure><p>The time constant τ expresses the time at which the circuit will (dis)charge to a simple expression involving <strong>e.</strong></p><p>Simulating this in Python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40f1717c924a4da64ee9dca009c787e9/href">https://medium.com/media/40f1717c924a4da64ee9dca009c787e9/href</a></iframe><p>We get the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*pvsIJ7Gg-olL9Vdyj1dvdQ.png" /><figcaption>Time Constant tau</figcaption></figure><p>Discharging is similar, and follow the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/117/1*nVmc7HN4xBt7mX2a-vG9Pw.png" /></figure><p>The graph is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*Cr_hGxxsJFjDbu4547DHUA.png" /></figure><p>After one time constant, the capacitor will charge to 63.2% of the input voltage, and 86.5% of the maximum after 2 time constants. Likewise the discharge will be to 36.8% of the initial voltage after one time constant, and 13.5% of the initial after two time constants.</p><p>When the circuit is closed, and the EMF (electromotive force) is applied to the circuit, a counter voltage that opposes the applied EMF occurs. This is called the <strong>back EMF.</strong></p><p>Some questions from the question bank are given below:</p><h3>A-001–001–001 (Answer: 1)</h3><p>What is the meaning of the term “time constant” in an RL circuit?</p><ol><li>The time required for the current in the circuit to build up to 63.2% of the maximum value</li><li>The time required for the current in the circuit to build up to 36.8% of the maximum value</li><li>The time required for the voltage in the circuit to build up to 63.2% of the maximum value</li><li>The time required for the voltage in the circuit to build up to 36.8% of the maximum value</li></ol><h3><strong>A-001–001–002 (Answer: 2)</strong></h3><p>What is the term for the time required for the capacitor in an RC circuit to be charged to 63.2% of the supply voltage?</p><ol><li>One exponential period</li><li>One time constant</li><li>An exponential rate of one</li><li>A time factor of one</li></ol><h3>A-001–001–003 (Answer: 4)</h3><p>What is the term for the time required for the current in an RL circuit to build up to 63.2% of the maximum value?</p><ol><li>An exponential period of one</li><li>A time factor of one</li><li>One exponential rate</li><li>One time constant</li></ol><h3>A-001–001–004 (Answer: 4)</h3><p>What is the term for the time it takes for a charged capacitor in an RC circuit to discharge to 36.8% of its initial value of stored charge?</p><ol><li>A discharge factor of one</li><li>An exponential discharge of one</li><li>One discharge period</li><li>One time constant</li></ol><h3>A-001–001–005 (Answer: 4)</h3><p>What is meant by “back EMF”?</p><ol><li>A current that opposes the applied EMF</li><li>An opposing EMF equal to R times C percent of the applied EMF</li><li>A current equal to the applied EMF</li><li>A voltage that opposes the applied EMF</li></ol><h3>A-001–001–006 (Answer: 3)</h3><p>After two time constants, the capacitor in an RC circuit is charged to what percentage of the supply voltage?</p><ol><li>95%</li><li>36.8%</li><li>86.5%</li><li>63.2%</li></ol><h3>A-001–001–007 (Answer: 1)</h3><p>After two time constants, the capacitor in an RC circuit is discharged to what percentage of the starting voltage?</p><ol><li>13.5%</li><li>36.8%</li><li>86.5%</li><li>63.2%</li></ol><h3>A-001–001–008 (Answer: 3)</h3><p>What is the time constant of a circuit having a 100 microfarad capacitor in series with a 470 kilohm resistor?</p><ol><li>470 seconds</li><li>0.47 seconds</li><li>47 seconds</li><li>4700 seconds</li></ol><h3>A-001–001–009 (Answer: 1)</h3><p>What is the time constant of a circuit having a 470 microfarad capacitor in series with a 470 kilohm resistor?</p><ol><li>221 seconds</li><li>221 000 seconds</li><li>47 000 seconds</li><li>470 seconds</li></ol><h3>A-001–001–010 (Answer: 1)</h3><p>What is the time constant of a circuit having a 220 microfarad capacitor in series with a 470 kilohm resistor?</p><ol><li>103 seconds</li><li>470 000 seconds</li><li>470 seconds</li><li>220 seconds</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=504d4af961a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collatz Conjecture Counter-Example Search Using Scala]]></title>
            <link>https://scott-ralph.medium.com/collatz-conjecture-counter-example-search-using-scala-50a3ed2e890e?source=rss-bf071925590d------2</link>
            <guid isPermaLink="false">https://medium.com/p/50a3ed2e890e</guid>
            <category><![CDATA[math]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Scott Ralph]]></dc:creator>
            <pubDate>Fri, 01 Oct 2021 00:24:05 GMT</pubDate>
            <atom:updated>2021-10-01T00:24:05.119Z</atom:updated>
            <content:encoded><![CDATA[<p>As a lover of mathematics, Collatz’s conjecture is fascinating to me. Simple to define, easy to compute, but a beast to (dis)prove.</p><p>Put simply, for positive integers, <em>n&gt;1:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/0*MrLM73yI8uHSYi91" /></figure><p>We can then generate a sequence of these numbers, starting at an initial value <em>n, </em>by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/0*yxJWw-i58LgUAYKQ" /></figure><p>Collatz’s Conjecture is simply, that these sequences, for all positive integer values, <em>n</em>, will <strong>eventually</strong> reach one. It may bounce around a lot, increasing well beyond the initial value, go back lower, perhaps spiking again, over-and-over, until eventually, it reaches one. For a lovely discussion of Collatz’s Conjecture see:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F094y1Z2wpJg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D094y1Z2wpJg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F094y1Z2wpJg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/457a72a81aee796476bc9da895b78778/href">https://medium.com/media/457a72a81aee796476bc9da895b78778/href</a></iframe><p>The <strong>stopping-time</strong> is defined as the number of iterations, <em>i</em>, required before reaching one.</p><p>Lots of effort has been done to prove, for increasing values of, <em>N, </em>that all <em>n≤N </em>satisfy the conjecture. That is not my goal, because:</p><ul><li>It’s really hard to do with limited resources</li><li>I would have to compete with people who have a <strong>lot</strong> more resources, and probably a better insight into (dis)proving the conjecture</li><li>Paul Erdős, is quoted to have said of this problem: “Mathematics is not ripe enough for such questions”</li></ul><p>Okay, great, so what is my goal?</p><h3>Goals</h3><ul><li>To write a simple Scala program that can find the stopping number for very very large integers</li><li>Run it on a Raspberry Pi, which can run noiselessly looking for a counter-example</li><li>With P(success) &gt; 0, I will find a counter-example, become famous, and wealthy, allowing me to read novels and drink coffee with my cats until my last days</li></ul><h3>Scala Code</h3><p>You can find this in GitHub at: (<a href="https://github.com/scottralph/collatz">https://github.com/scottralph/collatz</a>). I hope to clean up the code further but make no hard promises. The only challenging part of the coding is to deal with arbitrarily large integers and do basic arithmetic operators on them. I could have used off-the-shelf libraries for this, but I wanted to keep it simple, and a little fun, so I did it myself.</p><p>The interesting class is called <strong>Digits</strong>, and uses an array of bytes as its main focus of attention. I wanted to be able to deal with numbers whose digits would be up to a million digits long. Such a number is still computable in an hour or so on a weak processor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a9f30a13ed07b5e02a2e147e6e400f0/href">https://medium.com/media/2a9f30a13ed07b5e02a2e147e6e400f0/href</a></iframe><ul><li>The <strong>toString()</strong> method on lines 9–22 simply outputs the digits in groups of 100</li><li>Line 25, <strong>asHashString()</strong> is a helper-function that creates a string-verion of the number, for purposes of efficiently hashing in a set</li><li>The method <strong>addOne(), </strong>on lines 28–50, is straightforward. The only trick is to deal with the carry, and also expand the size of the result when all of the digits are <strong>9.</strong></li><li>The method <strong>multiplyDigit, </strong>on lines 52–67, multiplies the values by a given scalar</li><li>Likewise <strong>half(), </strong>69–82, halves the number</li><li>The method <strong>next(), </strong>on lines 84–89, just takes the current number and computes the next one of the sequence</li><li><strong>stoppingTime()</strong> computes the number of steps to reach 1</li><li>The object companion object method <strong>apply() </strong>takes an integer for the length and generates a random integer of the specified length</li></ul><p>If I find a counter-example, you can read about me in the news, otherwise I will be here working for a living.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50a3ed2e890e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GCP Cloud Functions in Java]]></title>
            <link>https://scott-ralph.medium.com/gcp-cloud-functions-in-java-e218b9c325f?source=rss-bf071925590d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e218b9c325f</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[intellij]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[cloud-functions]]></category>
            <dc:creator><![CDATA[Scott Ralph]]></dc:creator>
            <pubDate>Fri, 11 Jun 2021 01:25:34 GMT</pubDate>
            <atom:updated>2021-06-11T01:30:54.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Bpv6bY3YEpRnPA7U_i0ZhA.png" /></figure><h4>Debugging locally (with IntelliJ and Postman), and deploying to GCP</h4><p>Functions as a service (FaaS) is a great way to architect event-driven systems, whether it is in response to a RESTful HTTP event, responding to an external event, such as a content changes to a storage bucket, or a Pub/Sub message.</p><p>Cloud functions can be written in a myriad of languages, Java, Python, NodeJS to name just some, however I have chosen Java as it was a client’s first-choice in languages, and IntelliJ provides a nice debugging experience. Also I have focused on using a HTTP(S) type of trigger, though the request object that is passed for Pub/Sub or Google Cloud Storage event types are very similar, differing only in payload, and so can still be developed and debugged using the same technique.</p><h3>Getting Started</h3><p>The pom.xml file to provide the structure can be found <a href="https://cloud.google.com/functions/docs/first-java">here</a>.</p><p>In this example, we are going to implement the interface <em>HttpFunction</em> com.EXAMPLE.PriceService which is mentioned in the functionTarget which is mentioned in the <em>functionTarget</em> element of of the <strong>pom.xml</strong>.</p><p>The interesting bits are shown below:</p><pre>&lt;dependencies&gt;<br>        &lt;!-- Required for Function primitives --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;com.google.cloud.functions&lt;/groupId&gt;<br>            &lt;artifactId&gt;functions-framework-api&lt;/artifactId&gt;<br>            &lt;version&gt;1.0.4&lt;/version&gt;<br>            &lt;scope&gt;provided&lt;/scope&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;junit&lt;/groupId&gt;<br>            &lt;artifactId&gt;junit&lt;/artifactId&gt;<br>            &lt;version&gt;${junit.version}&lt;/version&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;com.google.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;google-cloud-spanner&lt;/artifactId&gt;<br>            &lt;version&gt;2.0.2&lt;/version&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;com.google.cloud.functions&lt;/groupId&gt;<br>            &lt;artifactId&gt;functions-framework-api&lt;/artifactId&gt;<br>            &lt;version&gt;1.0.1&lt;/version&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br><br>    &lt;build&gt;<br>        &lt;plugins&gt;<br>            &lt;plugin&gt;<br>                &lt;!--<br>                  Google Cloud Functions Framework Maven plugin<br>                  This plugin allows you to run Cloud Functions Java<br>                  code locally. <br>                  Use the following terminal command to run a<br>                  given function locally:<br><br>                  mvn function:run -Drun.functionTarget= <br>                  your.package.yourFunction<br>                --&gt;<br>                &lt;groupId&gt;com.google.cloud.functions&lt;/groupId&gt;<br>                &lt;artifactId&gt;function-maven-plugin&lt;/artifactId&gt;<br>                &lt;version&gt;0.9.7&lt;/version&gt;<br>                &lt;configuration&gt;<br>                         &lt;functionTarget&gt; com.EXAMPLE.PriceService<br>                          &lt;/functionTarget&gt;<br>                &lt;/configuration&gt;<br>            &lt;/plugin&gt;<br>        &lt;/plugins&gt;<br>    &lt;/build&gt;<br>&lt;/project&gt;</pre><h3>Implementing the HTTP Function</h3><p>The function is defined simply below:</p><pre>package com.EXAMPLE;<br>import com.fasterxml.jackson.core.JsonParseException;<br>import com.google.cloud.functions.HttpFunction;<br>import com.google.cloud.functions.HttpRequest;<br>import com.google.cloud.functions.HttpResponse;<br>import com.google.gson.Gson;<br>import com.google.gson.JsonElement;<br>import com.google.gson.JsonObject;<br>import com.google.gson.JsonParser;<br><br>public class PriceService implements HttpFunction {<br>    private static final Gson gson = new Gson();<br><br>    @Override<br>    public void service(HttpRequest request,<br>                        HttpResponse response) throws Exception {<br>    try {<br>      JsonElement parsedRequest = <br>            gson.fromJson(request.getReader(),<br>                          JsonElement.class);<br>      if (parsedRequest == null) {<br>        response.setStatusCode(400);<br>        writer.write(&quot;Bad JSON format&quot;);<br>        return;<br>      }<br>      if (parsedRequest != null &amp;&amp; parsedRequest.isJsonObject()) {<br>        JsonObject jsonObject = parsedRequest.getAsJsonObject();<br><br>        String response = handleReqeust(jsonObject);<br>        writer.write(response);<br>      } else {<br>        writer.write(&quot;Bad request.&quot;)<br>      }<br>    } catch (JsonParseException ex) {<br>        response.setStatusCode(400);<br>    }    writer.write(&quot;Parse Exception&quot;);<br>}</pre><p>The <strong><em>service</em></strong> method takes a request and produces the <strong>response</strong>. To make things easier, Google has defined some useful JSON parsing methods in the package <strong>com.google.gson</strong> that helps in the mundane efforts of parsing JSON for you.</p><p>Nothing complex going on in this code, and I have omitted the part where you do something interesting in the method <strong>handleRequest</strong>.</p><h3>Debugging in IntelliJ</h3><p>As indicated in the <strong>pom.xml</strong>comments, running your Cloud Function locally is quite easy using Maven, by specifying the target:</p><pre>mvn function:run -Drun.functionTarget=com.EXAMPLE.PriceService \<br>    -Drun.port=8888</pre><p>Here I specify the port, as the commonly used 8080 is invariably taken for some other service.</p><p>To run this in debugging-mode in IntelliJ, you simply use the <strong>Edit Copnfigurations…</strong> menu item, and create a new <strong>maven</strong> target, filling in the parameters, as shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*Ch2dHHqsL1FVPvqLFGDH2w.png" /></figure><p>Now just put a break-point anywhere you want, prior to triggering the execution.</p><h3>Triggering the function locally with Postman/Curl</h3><p>To trigger the locally running cloud function, you can use Postman or Curl to author the HTTP request as:</p><pre>curl --location --request GET &#39;http://localhost:8888&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--data-raw &#39;{ &quot;customer_pin&quot;: &quot;452670&quot;, &quot;item_id&quot;: &quot;1009715&quot;}&#39;</pre><p>This will allow unauthenticated requests. If you want to switch this to require authentication, then you also have to add additional header information with an identity-token (e.g. <strong>gcloud auth print-identity-token</strong>).</p><p>Once deployed, you can test the cloud function from the google console, that has a rudimentary testing framework.</p><p>I find this a much better way to debug Cloud Functions than the deploy-and-read-the-log-exceptions method.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e218b9c325f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an Apache Spark Cluster with Raspberry Pi Workers]]></title>
            <link>https://medium.com/swlh/creating-an-apache-spark-cluster-with-raspberry-pi-workers-472c2c9a19ce?source=rss-bf071925590d------2</link>
            <guid isPermaLink="false">https://medium.com/p/472c2c9a19ce</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[cluster-computing]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Scott Ralph]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 02:28:18 GMT</pubDate>
            <atom:updated>2021-12-29T16:50:48.099Z</atom:updated>
            <content:encoded><![CDATA[<p>For this experiment I wanted to assess how difficult it would be to create a small Apache Spark cluster using an Ubuntu Desktop machine as a master, and a single Raspberry Pi as one of the worker nodes. The desktop instance also hosts a worker node as well. The plan is to eventually expand the number of Raspberry Pi nodes over time, since they are quite inexpensive — less than USD $100.00 for a Raspberry Pi 4.</p><h3>The Hardware</h3><ul><li>Ubuntu Desktop running Ubuntu 20.04.2 LTS. This is my main work machine, and will be the Master node.</li><li>A cheap network switch from<a href="https://www.amazon.ca/gp/product/B07S98YLHM/ref=as_li_tl?ie=UTF8&amp;tag=scottralph-20&amp;camp=15121&amp;creative=330641&amp;linkCode=as2&amp;creativeASIN=B07S98YLHM&amp;linkId=e02b793aaef0c9fbbddfe27444b75df5"> </a><a href="https://www.amazon.ca/gp/product/B07S98YLHM/ref=as_li_tl?ie=UTF8&amp;tag=scottralph-20&amp;camp=15121&amp;creative=330641&amp;linkCode=as2&amp;creativeASIN=B07S98YLHM&amp;linkId=e02b793aaef0c9fbbddfe27444b75df5">Amazon</a>. I probably should have got a nice managed network switch, but for now this will do. If you have a lot of ports on your internet box, you can skip this, but I wanted to have all the compute-nodes all in one place with minimal wiring.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*F6TjCQl3GhpSmirhL2m5EQ.png" /></figure><ul><li>Raspberry Pi 4 Model B, with 8 GB of memory. I purchased this from a <a href="https://www.buyapi.ca/product/raspberry-pi-4-model-b-8gb/?src=raspberrypi">Canadian supplier.</a> I got the “Desktop Kit”, which comes with a keyboard, mouse, and some micro HDMI cables as I thought they might come in handy some day, but for this project they were actually unnecessary. As part of the kit, a nice enclosure for the Pi is also included.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*tR32mSpYqUIadvUo89Yutg.jpeg" /></figure><p>The Raspberry Pi 4 runs off of a Micro-SD card, and the kit came with a SD-Micro-SD adapter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*VYhvfD-_zBysC_aBavfhJw.jpeg" /></figure><h3>Creating the Raspberry Pi Image</h3><p>To install the Raspberry Pi Imager software, that creates the image on the Micro-SD card, download the <strong>deb</strong> file from: <a href="https://www.raspberrypi.org/software/">their site</a>. And installing it with:</p><pre>% sudo dpkg -i imager_1.5_amd64.deb</pre><p>Launching Raspberry Pi Imager you get the simple three step process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*jyiXQs3-61jitdB3zIm03w.png" /></figure><p>Among the options in the “Choose OS” under “Other General Purpose OS” is the <strong>64-bit Ubuntu Server 20.04.2.LTS </strong>option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*9PVIrAiAnU5RMd0S99RYdg.png" /></figure><p>You then select the SD card, and hit the <strong>write</strong> button. This will then prompt you for your system password (since the SD card is a mounted drive), and then it will write, and verify the image. Then it is finished, and ready to insert into the Raspberry Pi.</p><h3>Setting up the Raspberry Pi</h3><p>For me, this involved navigating to my local router’s administrative web-interface, and listing the current devices on the network. The freshly-installed Raspberry Pi Ubuntu Server will have a name of “ubuntu”.</p><p>While I was in the administration web page, I also went into the DHCP settings, and configured it to assign as static known IP address for both the ubuntu desktop master node computer, as well as the Raspberry Pi machine.</p><p>Connecting with ssh is done with username “ubuntu” and password “ubuntu”, once you connect via ssh from the master machine:</p><pre>% ssh ubuntu@192.168.1.55</pre><p>You are prompted to create a new password. Once logged in, I did some housecleaning activities, such as re-naming the machine name (in my case to <strong>rpi-ubuntu</strong>)</p><pre>% sudo vi /etc/hostname</pre><p>and also set up the default shell to be <strong>bash</strong> and not <strong>sh</strong>.</p><pre>% sudo vi /etc/passwd<br>... change /bin/sh to /bin/bash</pre><p>Before we set up Spark, we need to put Java and Scala on the Raspberry Pi.</p><pre>% sudo apt install -y default-jre</pre><p>At the time of writing this gives me the version 11.</p><pre>% java -version <br>openjdk version &quot;11.0.7&quot; 2020-04-14<br>OpenJDK Runtime Environment (build 11.0.7+10-post-Ubuntu-2ubuntu218.04)<br>OpenJDK 64-Bit Server VM (build 11.0.7+10-post-Ubuntu-2ubuntu218.04, mixed mode, sharing)</pre><p>Then install the JDK</p><pre>% sudo apt install -y default-jdk</pre><p>I already had Java 11 on my Ubuntu Desktop, but you may need to do this there as well.</p><p>Installing Scala is simple:</p><pre>% sudo apt install -y scala <br>% scala<br>Welcome to Scala 2.11.12 (OpenJDK 64-Bit Server VM, Java 11.0.9.1).<br>Type in expressions for evaluation. Or try :help.</pre><pre>scala&gt;</pre><p>The good news is that the latest Spark now works with Java 11, so there is none of the irritation of having to install Java 8.</p><p>To install Spark, I navigated to the Spark download page: <a href="https://spark.apache.org/downloads.html">here</a>. I chose to download <strong>Spark version 3.0.1</strong> with the option <strong>“</strong>pre-built for Hadoop 3.2”. I installed it by extracting the <strong>tar</strong> file and moving it to a more standard place.</p><pre>% tar vxf ~/Downloads/spark-3.0.1-bin-hadoop3.2.tgz<br>% sudo mv spark-3.0.1-bin-hadoop3.2 /usr/local</pre><p>On the <strong>master</strong>, set up the system environment variable <strong>path</strong> to pick up the two directories in:</p><pre>export PATH=&quot;$PATH:/usr/local/spark-3.0.1-bin-hadoop3.2/bin&quot; <br>export PATH=&quot;$PATH:/usr/local/spark-3.0.1-bin-hadoop3.2/sbin&quot;</pre><p>Copy the Spark distribution to the Raspberry Pi:</p><pre>scp ~/Downloads/Downloads/spark-3.0.1-bin-hadoop3.2.tgz ubuntu@192.168.1.101:/tmp</pre><p>replacing the I.P. address with the correct one. This will place the Spark distribution in <strong>/tmp. </strong>Go through the same Spark set-up as above on the Raspberry Pi.</p><h3>Checking Spark Runs Locally</h3><p>On <strong>both</strong> the desktop and the Raspberry Pi, run the Spark-shell:</p><pre>% spark-shell<br>Setting default log level to &quot;WARN&quot;.<br>To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).<br>21/02/07 01:35:41 WARN SparkContext: Please ensure that the number of slots available on your executors is limited by the number of cores to task cpus and not another custom resource. If cores is not the limiting resource then dynamic allocation will not work properly!<br>Spark context Web UI available at <a href="http://rpi-ubuntu:4040/">http://rpi-ubuntu:4040</a><br>Spark context available as &#39;sc&#39; (master = spark://192.168.1.100:7077, app id = app-20210206203542-0003).<br>Spark session available as &#39;spark&#39;.<br>Welcome to<br>      ____              __<br>     / __/__  ___ _____/ /__<br>    _\ \/ _ \/ _ `/ __/  &#39;_/<br>   /___/ .__/\_,_/_/ /_/\_\   version 3.0.1<br>      /_/<br>         <br>Using Scala version 2.12.10 (OpenJDK 64-Bit Server VM, Java 11.0.9.1)<br>Type in expressions to have them evaluated.<br>Type :help for more information.</pre><pre>scala&gt;</pre><p>At this point you should be able to see the Spark UI (given as <a href="http://rpi-ubuntu:4040/">http://rpi-ubuntu:4040</a>), since I changed the host name of the Raspberry Pi.</p><p>If that all checks out, then we can move on to make sure that Spark is configured to work in a cluster.</p><h3>SSH Access for Master and Slave</h3><p>Spark requires password-less login between both the Master and the Slave. To do this we need to create a SSH key on <strong>both</strong> of the machines.</p><p>To create it:</p><pre>% ssh-keygen -o -a 100 -t ed25519 -f ~/.ssh/id_ed25519 -C &quot;<a href="/service/mailto:scott@scottralph.org">y</a>our_email@something.com&quot;</pre><p>On the other computer, you can copy this key via:</p><pre>ssh-copy-id user@hostname.example.com</pre><p>which copies the default identity, or you can specify the identify-file using the “-i” option.</p><p>Once this is done you should be able to SSH from the master:</p><pre>% ssh ubuntu@192.168.1.101</pre><p>making the relevant changes, and you should not require a password. If it does, this needs to be solved first.</p><h3>Spark User</h3><p>Depending on your preferences, some people like to run their spark jobs as the user “spark”. Just to make sure things were easy with authentication, I made a user name on the Raspberry Pi that was <strong>the same</strong> as on my Desktop. This may have helped with some of the configuration of Spark with respect to authentication, I am not entirely sure. A user name of “ubuntu” is awfully clinical and cold anyway!</p><p><strong>Checking OpenSSH on Master</strong></p><p>Depending on your Desktop environment, this may not be necessary, but I found that until I did the following steps I got “<strong>connection refused”</strong> when I attempted to ssh to localhost:</p><pre>% ssh user@localhost<br>Connection Refused.</pre><p>To solve this:</p><pre>% sudo apt install -y openssh-server<br>% sudo systemctl enable ssh<br>% sudo systemctl start ssh</pre><h3>Configuring Spark to Run as a Cluster</h3><p>In the spark “conf” directory there is a file “spark-env.sh-template”. Copy this file to be “spark-env.sh” in that same directory. Add the line:</p><pre>export SPARK_MASTER_HOST=&quot;192.168.1.100&quot;</pre><p>adjusting whatever the master I.P. address is. Also, copy the file “slaves.template” to “slaves”. In it I added the lines:</p><pre># A Spark Worker will be started on each of the machines listed below.<br>localhost<br>rpi</pre><p>Note that for convenience I have mapped the name “rpi” to the I.P. address in my “/etc/hosts” file.</p><pre>192.168.1.101 rpi</pre><p>By default, the web-UI for Spark tries port 8080. I had a conflict on this port, and so I wanted to set it to something I could remember, so in my “.bashrc” I set the environment variable:</p><pre>export SPARK_MASTER_WEBUI_PORT=”9999&quot;</pre><h3>Starting the Spark Cluster</h3><p>To start the cluster, in the command line type:</p><pre>% start-all.sh</pre><p>This will start up one master, one local slave, and one remote (on the Raspberry Pi). While it starts up, it will tell you the local and remote log files that it is writing to (located in the “logs” sub-directory of Spark). If something is mis-configured, then this will give you the error messages to diagnose.</p><h3>Testing the Cluster</h3><p>To test the cluster, I started a spark-shell, with the additional arguments:</p><pre>spark-shell --master spark://192.168.1.100:7077</pre><p>Here I use the I.P. address of the master. I do not recall if you can use a symbolic name.</p><p>Once started, I navigated to “<a href="http://192.168.1.100:9999/">http://192.168.1.100:9999</a>”, though “localhost” would also work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q1Vx-vDHWg_i-yquMEs-VQ.png" /></figure><p>From the U.I. you can see two worker nodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iKahZ53rrrKxaXeo4qe62g.png" /></figure><p>I hope that this helps you avoid most, if not all, of the snags in setting up a local Spark cluster!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=472c2c9a19ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/creating-an-apache-spark-cluster-with-raspberry-pi-workers-472c2c9a19ce">Creating an Apache Spark Cluster with Raspberry Pi Workers</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[Inverting Matrices Safely: Singular Value Decomposition and the Moore- Penrose Pseudoinverse]]></title>
            <link>https://scott-ralph.medium.com/inverting-matrices-safely-singular-value-decomposition-and-the-moore-penrose-pseudoinverse-d081c0babe70?source=rss-bf071925590d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d081c0babe70</guid>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[matrix]]></category>
            <category><![CDATA[linear-regression-python]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Scott Ralph]]></dc:creator>
            <pubDate>Tue, 19 Jan 2021 01:28:29 GMT</pubDate>
            <atom:updated>2021-01-19T01:28:29.678Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*2lDzAHBhQPt4-d4hxXfwqw.jpeg" /><figcaption>Gilbert Strang, a great professor of Mathematics at M.I.T. His excellent book “Linear Algebra and Its Applications (third edition)” is a great book, and he has a number of excellent YouTube lectures.</figcaption></figure><h3>Computing the Inverse in NumPy</h3><p>Suppose we are given a matrix <em>M</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*8sX4ekW4Rs4UyZ01JqivJA.png" /></figure><p>If we had this matrix when solving a set of linear equations, <em>M x = b</em>, where <em>b</em> is a known vector, and we wish to solve for <em>x</em>, then solving for <em>x</em> is simply:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/79/1*IrSUJs0nimYoEgLsjnQt-A.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/35/1*5DKAlPtHPYc6hKluKqSQsQ.png" /></figure><p>is the inverse of <em>M</em>. Using NumPy, we can easily compute the inverse:</p><pre>import numpy as np<br>import scipy<br>import scipy.linalg<br>m1 = np.array([[0.,-3.,-2.],[1.,-4.,-2],[-3.,4.,1.]])<br>print(f&#39;m1 is {m1}&#39;)<br>m1_inv = np.linalg.inv(m1)<br>print(f&#39;m1 inverse is {m1_inv}&#39;)</pre><p>with the answer given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*B_jEn4HpBq7SOh396W2rvg.png" /></figure><p>Easy! In fact, if we take random values for the matrix <em>M</em>, it would work almost every time (e.g. you wouldn’t live long enough to witness one fail). The pathological case, called a <strong>singular matrix</strong>, and I will go into more detail of how to detect and potentially remediate the situation shortly. Before I talk about this failure case, let me point out that there are two broad classes of problems where you take the inverse of a matrix to get a solution:</p><ul><li>The class of problem where you hope for the best, if it is singular, you want to detect and report the error, but there’s no obvious fall-back strategy for getting a ‘good but not perfect’ solution, and</li><li>The class of problems where you can still compute a reasonable value for your matrix; something that behaves <strong>like</strong> an inverse, but is well-behaved.</li></ul><h3>Singular Matrices</h3><p>An example of a singular matrix, constructed specifically to make it easy to describe, is given as <em>M</em>ₛ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/1*n44rU9mqVAHInfajIn2gww.png" /></figure><p>You can see that it is singular, by multiplying the first row by 2, and subtracting the second row. This gives the third row. The last row, therefore, gives us no more additional information about the relative combinations of vectors and how they span the 3-dimensional space. In a 3x3 matrix, each of the column vectors define a plane. Inverting the matrix is analogous to taking the intersection point of three planes to find the point of intersection. In the singular case above, we take the intersection of two planes to find a line, but the third plane lies in this plane, so the intersection is still a line. In this case our matrix has a <strong>rank</strong> of 2, meaning that there are only two independent rows in the matrix.</p><p>If we attempt to compute the inverse using NumPy, as above, it will throw an exception of the type:</p><pre>LinAlgError(&quot;Singular matrix&quot;)</pre><h3>Singular Value Decomposition</h3><p>Computing the Singular Value of a matrix gives a <strong>lot</strong> of insight about the structure of a matrix.</p><p>The <strong>singular value decomposition</strong> of a matrix <em>A</em>, is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/88/0*ghyrXYMbLexKyZZt.png" /></figure><p>where the columns of <em>U</em> and <em>V</em> are called the <strong>left singular vectors</strong> and <strong>right singular vectors</strong> respectively, and the diagonal matrix <em>S</em> is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*E8CmgimZLqVgsUWGQrTBLQ.png" /></figure><p>Computing the singular values in NumPy is easy:</p><pre>u,s,vt = np.linalg.svd(m1, full_matrices=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/0*1LjUGg2a8-QHzDsP.png" /></figure><p>All singular values <em>s</em>ᵢ ≥ 0, and by convention <em>s</em>₁ ≥ <em>s</em>₂ ≥ … ≥ <em>s</em>ₙ.</p><h3>Aside: Interpreting Singular Values as Incremental Approximation</h3><p>Considering the column vectors <em>u</em>ᵢ of <em>U</em>, and the row vectors <em>v</em>ᵢ of <em>V</em>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*FL2z1hdQouNVAzjt.png" /></figure><p>then we can see the decomposition as a sum of matrices, by taking the outer-product of the columns of <em>U</em> and rows of <em>V</em>ᵗ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/0*9B91exJHxm1_tG7y.png" /></figure><p>If we take <em>n</em>=3 then we get an exact reconstruction. The magnitude of the singular values indicates the relative importance of each term.</p><p>For example, if we consider <em>n</em>=1, taking only the first term, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/0*nHOECCdJClV8fUD0.png" /></figure><p>We can see that this is a fairly good approximation to the original matrix <em>M</em>. And using the first two terms, it is even closer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/0*-DVI2Glvmej9xHY8.png" /></figure><p>The value here is that if we want to just keep a subset of the vectors, we can still get a good approximation, and the singular values gives us an indication of the relative importance.</p><h3>Computing the Inverse with Singular Values</h3><p>One of the interesting properties of the decomposition is that both <em>U</em> and <em>V</em>ᵗ are <a href="https://en.wikipedia.org/wiki/Orthogonal_matrix"><strong>orthogonal</strong></a>, meaning that its inverse is equal to it’s transpose.</p><p>This means that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/0*YSv2NXVGkdfur4U8.png" /></figure><p>We can compute the <strong>pseudoinverse</strong>, denoted <em>M</em>⁺, by determining minimum thresholding criteria, of <em>s</em>ₙ that substitutes zero for sufficiently small values of 1/sₙ. Taking only the first <em>k</em> terms, the pseudoinverse is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/0*Z2rGlfc5MZl0wGbv.png" /></figure><p>In our singular case, given by <em>M</em>s, the singular values, as computed by NumPy are:</p><pre>6.99811874e+00 <br>3.32059242e+00<br>5.73361908e-17</pre><p>The last singular value is essentially zero. Taking only the first two terms we get a pseudoinverse of the matrix. How does this help us, since it is not an actual inverse? As I will show below, for many problems, using the pseudoinverse will give you a well-behaved least-squares solution for over-determined systems.</p><p>Given the above, it is very straightforward to construct a python function that will give you a safe pseudo-inverse:</p><pre>def pseudo_inverse(m, singular_value_minimum):<br>    # filter Si and take inverse<br>    ...<br>    inv_value = np.matmul(np.matmul(u, one_over_s), v_transpose)</pre><pre>    return rank,inv_value</pre><h3>Least Squares using Pseudo Inverse</h3><p>In the simple case of fitting a line in the plane to a set of data points, we seek parameters <em>m</em> and <em>b</em>, such that the line, <em>y = mx + b</em>, is the least squares solution.</p><p>Suppose the three points are (0,0), (2,1), and (3,3). Forming the matrix-form of the solution we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/0*joimP8gc30Cmy7Ty.png" /></figure><p>Solving this set of constraints using the pseudoinverse allows us to avoid the situation in which the matrix inversion would otherwise lose full rank. This might include a repetition of a point etc.</p><p>Solving this we get <em>m</em> = 0.92857, b = -0.21428.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/0*Xfm-F4T-oQU4su6R.png" /></figure><p>Of course linear least squares is trivial, but bear in mind that we can extend this to fit tens of thousands of points in hundreds of dimensions. If any of these dimensions are degenerate, they will be omitted inversion. As long as the computed rank is greater than the number of unknowns, the solution should be accurate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d081c0babe70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple RESTful BigQuery Storage with Python and Cloud Functions]]></title>
            <link>https://python.plainenglish.io/simple-restful-bigquery-storage-with-python-and-cloud-functions-66c5c4480bbe?source=rss-bf071925590d------2</link>
            <guid isPermaLink="false">https://medium.com/p/66c5c4480bbe</guid>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Scott Ralph]]></dc:creator>
            <pubDate>Fri, 15 Jan 2021 16:27:08 GMT</pubDate>
            <atom:updated>2021-01-19T18:04:42.998Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simple RESTful API to Manage BigQuery Data using Python and Cloud Functions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5fo5YVoIZhO1ZOwmONN0g.png" /></figure><h3>Motivation</h3><p>My goal was to add a user-commenting capabilities to a blog, without having to pay monthly fees like <a href="https://disqus.com/">Disqus</a>. I also wanted to keep things as inexpensive as possible, so where possible no dedicated servers or traditional databases. Lastly, I wanted to do it all on Google Cloud Platform — I have had a good experience with deploying infrequently-used containerized applications using Cloud Run. Like Cloud Run, both BigQuery and Cloud Functions have a free-tier:</p><ul><li><strong>BigQuery</strong> has 10 GB of free storage, plus 1 TB of queries free per month</li><li><strong>Cloud Functions </strong>has 2 million invocations per month, 400,000 GB-seconds memory, 200,000 GHz-seconds of compute time, 5 GB network egress per month</li></ul><h3>Configuring Access</h3><p>To make things easy, I created a <strong>service-account </strong>specific to this micro-service. In the BigQuery console, I created a new data-set and tables, and selected the “Share Data Set” option, adding the service-account as an editor.</p><h3>Accessing the Table in Python</h3><p>To test your Python code locally, you can authenticate as the service-account locally by downloading a key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*pD4gkWeKHhAJk4kExDHWyg.png" /></figure><p>Adding a new key allows you to download the credentials as a JSON file. The Google Cloud Python libraries will use this JSON file if you set the environment variable:</p><pre>export GOOGLE_APPLICATION_CREDENTIALS=PATH_TO_YOUR_KEY.json</pre><p>This can also be set up nicely in PyCharm.</p><p>The python code for accessing the table is very straightforward, the excerpt below gives you an idea:</p><pre>from google.cloud import bigquery<br>from google.cloud.bigquery import DatasetReference</pre><pre>gcp_project=&quot;YOUR_GCP_PROJECT&quot;<br>dataset_id=&quot;blog&quot;<br>table_name=&quot;comments&quot;</pre><pre>client = bigquery.Client(project=gcp_project)<br>dataset_ref = DatasetReference(dataset_id=dataset_id,\<br>   project = gcp_project)<br>table_ref = dataset_ref.table(table_name)<br>table = client.get_table(table_ref)<br>query = f&quot;select * from `{gcp_project}.{dataset_id}.{table_name}` limit 10&quot;<br>job = client.query(query)<br>result = job.result()<br>for row in result:    <br>   print(row)</pre><p>Running this script ensures that BigQuery is set up correctly, and the service-account can access it. Now we need to package this code in a Cloud Function.</p><h3>Creating the Cloud Function</h3><p>In the GCP console, navigate to Cloud Functions, and select the “create-function”, giving you the options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*UEHMqvcQePsH0fFW4PP2ag.png" /></figure><p>These options are straightforward — I chose to allow unauthenticated invocations, but that’s up to you. After you save, there are some more options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*_r5x1XkfDl7fzNz0CBDavw.png" /></figure><p>Here you can specify the memory, timeout, and maximum number of instances. The important bit here is that by default the options for <strong>Service Account</strong> is “App Engine default service account”. You want to change this to be the service account you created to give permissions to the Big Query data set.</p><p>On the next pane, you now specify the Python code for the Cloud Function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*xo4fOBQVlYQjL7yN6cieng.png" /></figure><p>You specify that you want the runtime environment to be Python 3.x, and give the name of the function that will field the request, in this case “hello_world”. For many Cloud Functions we might get away with using the <strong>inline editor</strong> option, and just specifying the code. In our case, unfortunately, we have to specify the source from a ZIP owing to the fact that the Google Cloud BigQuery library is not pre-loaded on the platform, and we must package it ourselves.</p><p>For this we have to create a ZIP file with the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*q2uVKM-TSvaa3kXWTXNR0Q.png" /></figure><p>where our “hello_world” function is assumed to be in the “main.py” file. All library files are expected to be in their own directory that is a sibling of the main script.</p><p>The only library dependency we have to worry about is <strong>google-cloud-bigquery</strong>. To get this library in a local file, create a new directory for staging the artifacts, as well as the <strong>main.py.</strong></p><pre>% mkdir staging <br>% pip install google-cloud-bigquery <strong>-t staging<br></strong>% cd staging<br>% cp main.py .<br>% zip cloud-function.zip *</pre><p>The “<strong>-t</strong>” option ensures that the libraries are placed in the directory specified. Note that the staging directory contains a lot of files, since it also brings in all of the libraries on which google-cloud-bigquery depends.</p><h3>Deploying the ZIP File</h3><p>From the drop-down list in the cloud function console you can choose:</p><ul><li>To upload the ZIP file directly, also specifying a Google Storage Bucket as a staging location. This requires the extra step of creating your own staging storage bucket beforehand, or</li><li>To directly reference a ZIP file from a staging storage bucket</li></ul><h3>Testing</h3><p>For my testing, I used <a href="https://www.postman.com/">Postman</a> and authored a GET HTTP Request. You can directly author the JSON arguments to the request, submit the request, and then see the JSON response.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66c5c4480bbe" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/simple-restful-bigquery-storage-with-python-and-cloud-functions-66c5c4480bbe">Simple RESTful BigQuery Storage with Python and Cloud Functions</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>