<?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 Stuart McLean on Medium]]></title>
        <description><![CDATA[Stories by Stuart McLean on Medium]]></description>
        <link>https://medium.com/@stuart-mclean?source=rss-aa921bd25d8e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*--Exep1NNWzoih1HT7u05w.jpeg</url>
            <title>Stories by Stuart McLean on Medium</title>
            <link>https://medium.com/@stuart-mclean?source=rss-aa921bd25d8e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 00:15:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stuart-mclean/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[Using Typescript to generate a self-signed JWT token for use on GCP]]></title>
            <link>https://stuart-mclean.medium.com/using-typescript-to-generate-a-self-signed-jwt-token-for-use-on-gcp-a61e942c8afc?source=rss-aa921bd25d8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a61e942c8afc</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Stuart McLean]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 16:03:23 GMT</pubDate>
            <atom:updated>2023-04-02T16:03:23.826Z</atom:updated>
            <content:encoded><![CDATA[<p>Make it easy on yourself and still keep things secure.</p><figure><img alt="Casino tokens scattered on a gaming table." src="https://cdn-images-1.medium.com/max/1024/1*Zy6wb3zfTANbSdEStivBBw.jpeg" /><figcaption>Photo by Pavel Danilyuk: <a href="https://www.pexels.com/photo/casino-chips-scattered-on-gaming-table-7594225/">https://www.pexels.com/photo/casino-chips-scattered-on-gaming-table-7594225/</a></figcaption></figure><p>For an external application to access the Google Cloud Platform (GCP) it needs a service account and a way to authenticate itself.</p><p>GCP offers <a href="https://cloud.google.com/iam/docs/create-short-lived-credentials-direct">several ways to do this</a>, including OAuth 2.0 and OpenID Connect (OIDC). In this article, we’ll examine the self-signed JWT method.</p><p>It’s useful to allow external services like <a href="https://blog.cloudflare.com/introducing-cloudflare-workers/">Cloudflare Workers</a> access to GCP content. Since the process for generating a JWT is rather complex and, for now at least, Cloudflare only allows workers to be written in JavaScript, I thought it best to write in TypeScript.</p><h4>The Request Payload</h4><p>First, we need to create a payload in the format that GCP expects. This requires a service account (which looks like an email address) and a target audience, both of which are included in a <a href="https://cloud.google.com/iam/docs/creating-managing-service-account-keys">GCP service account key</a>. We can also specify a time to live (TTL) for the token, measured in seconds.</p><pre>function currentTimeInSeconds(): number {<br> return Math.floor(Date.now() / 1000);<br>}<br><br>class Payload {<br> iss: string;<br> sub: string;<br> email: string;<br> aud: string;<br> jti: string;<br> target_audience: string;<br> exp: number;<br> iat: number;<br><br> constructor(serviceAcct: string, targetAudience: string, ttlSeconds: number) {<br>  const time = currentTimeInSeconds();<br>  this.iss = serviceAcct;<br>  this.sub = serviceAcct;<br>  this.email = serviceAcct;<br>  this.aud = &quot;https://www.googleapis.com/oauth2/v4/token&quot;;<br>  this.exp = time + ttlSeconds;<br>  this.jti = &quot;jwt_nonce&quot;;<br>  this.iat = time;<br>  this.target_audience = targetAudience;<br> }<br>}</pre><h4>Signing our Token</h4><p>As outlined in the spec at <a href="https://jwt.io/introduction">jwt.io</a>, signatures an algorithm like this:</p><pre>HMACSHA256(<br>  base64UrlEncode(header) + &quot;.&quot; +<br>  base64UrlEncode(payload),<br>  secret)</pre><p>To help us, we can use the <a href="https://github.com/kjur/jsrsasign">jsrassign</a> library to help us sign our token, again</p><pre>const header = {<br> alg: &quot;RS256&quot;,<br> typ: &quot;JWT&quot;,<br> kid: serviceAcct,<br>};<br><br>const payload = new Payload(serviceAcct, targetAudience, ttlSeconds);<br><br>const jwt = KJUR.jws.JWS.sign(<br> header.alg,<br> JSON.stringify(header),<br> JSON.stringify(payload),  <br> privateKey<br>);</pre><h4>Fetching the Token</h4><p>GCP requires the body of the JWT request in the following format:</p><pre>&quot;grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&amp;assertion=&quot; + jwt;</pre><p>We can then include this in a request formatted:</p><pre><br>const newRequestInit = {<br>  method: &quot;POST&quot;,<br>  headers: {<br>  Authorization: `Bearer ${jwt}`,<br>    &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;,<br>    Accept: &quot;application/json&quot;,<br>  },<br>  body: &quot;grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&amp;assertion=&quot; + jwt,<br>};</pre><p>This will allow us to create a token using an existing Request like this:</p><pre>const url = new URL(&quot;https://www.googleapis.com/oauth2/v4/token&quot;);<br>const newRequest = new Request(request, newRequestInit);<br>const tokenRequest = new Request(url, newRequest);</pre><p>…and actually fetch the token like this:</p><pre>const token = await fetch(tokenRequest)<br>  .then(function (response: Response) {<br>    return JSON.parse(response.text()).id_token;<br>  });<br>}</pre><p>This token can then be used in the Authorization header of your request.</p><h4>Forwarding Existing Authorization Tokens</h4><p>Since GCP requires the Authorization header, you will need to forward any existing authorization headers to one of your downstream services with a different key.</p><p>And you should definitely use authorization in your downstream services.</p><p>I recommend moving the header to something like x-authorization-external and accessing that as your bearer token in the service.</p><pre>if (&quot;Authorization&quot; in request.headers) {<br>  headers[&quot;x-authorization-external&quot;] = request.headers.get(<br>    &quot;Authorization&quot;<br>  ) as string;<br>}</pre><h4>A Word of Warning</h4><p>Be careful about making it too easy for other people to trigger your functions. If your Cloudflare worker or GCP cloud functions run, you will be charged for them. However, as of this writing, <a href="https://cloud.google.com/functions/pricing">GCP charges</a> are based on both the number of executions and compute time, so authorize all calls from external sources and fail early if they don’t have correct credentials.</p><h4>Putting it all together</h4><figure><img alt="Key on a person’s palm." src="https://cdn-images-1.medium.com/max/1024/1*_dT1K4q_j9qttJi0lUM33w.jpeg" /><figcaption>Photo by Kindel Media: <a href="https://www.pexels.com/photo/key-on-a-person-s-palm-7579201/">https://www.pexels.com/photo/key-on-a-person-s-palm-7579201/</a></figcaption></figure><p>This <a href="https://gist.github.com/stuartmclean/942d488cac0d873d2c45c52850363ba9">gist</a> shows the full TokenProvider class along with its dependencies.</p><p>It can be called like this:</p><pre>const tokenProvider = new TokenProvider(serviceAcct, endpoint, privateKey);<br>const jwt = tokenProvider.getIdToken();</pre><p>I also added a private isExpired() method to ensure that we can call the getIdToken() method multiple times on a Token object and always be assured of an unexpired token.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/449325b71fbe657d3adf6c4c51468849/href">https://medium.com/media/449325b71fbe657d3adf6c4c51468849/href</a></iframe><p>I hope this makes it easier to generate your tokens and trigger your GCP services securely, but with ease.</p><p>Happy coding everybody! 😸</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a61e942c8afc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Finished Reading 50 Books in 2021]]></title>
            <link>https://stuart-mclean.medium.com/i-finished-reading-50-books-in-2021-d56db863a01c?source=rss-aa921bd25d8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d56db863a01c</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[reading-challenge-2021]]></category>
            <category><![CDATA[reading]]></category>
            <category><![CDATA[goals]]></category>
            <category><![CDATA[goal-setting]]></category>
            <dc:creator><![CDATA[Stuart McLean]]></dc:creator>
            <pubDate>Sat, 01 Jan 2022 21:52:35 GMT</pubDate>
            <atom:updated>2022-01-01T21:52:35.624Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s how I did it, even with a family and a full-time job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4Upm-cZjY_l7Gqxb" /><figcaption>Photo by <a href="https://unsplash.com/@ishaqrobin?utm_source=medium&amp;utm_medium=referral">Ishaq Robin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Contents</h4><p>∘ <a href="#5e12">Set a Specific but Attainable Goal</a><br> ∘ <a href="#e5bf">Make Every Word of Your Goal Count</a><br> ∘ <a href="#c61f">Break Down the Goal</a><br> ∘ <a href="#6722">Make Use of Different Media</a><br> ∘ <a href="#3737">The Numbers Aren’t Really Important</a><br> ∘ <a href="#6f9b">You Don’t Need to Complete Every Book You Start</a><br> ∘ <a href="#6c1a">Include Page-a-Day Books to Easily Boost Your Numbers</a><br> ∘ <a href="#6138">Track Your Progress</a><br> ∘ <a href="#655f">Give Yourself a Reward</a></p><h4>Set a Specific but Attainable Goal</h4><p>In 2018 I set my first reading goal. I’d received a lot of book recommendations and bought many of those books over the previous few years, but had actually finished very few of them. I had a full-time job, two young kids at home and a hobby of playing music one or two evenings a week. It felt like I had very little time to read and I wanted to make a priority of it.</p><p>I’d also noticed that I was spending too much time scrolling through social media and other news feeds. I wanted to encourage myself to spend my time on books instead.</p><h4>Make Every Word of Your Goal Count</h4><p>I decided to start with an attainable goal that would still be a bit of a challenge. With that in mind, I wrote this is my list of New Year&#39;s resolutions: “Finish 20 books in 2018.”</p><p>Note that I didn’t require myself to read the entirety of a book in the year for it to count, only that I finished reading it. I could have cheated by having a single chapter (or a single page) left in a book at the end of 2017, and just flipped the last leaf in 2018, but I didn’t actually do that. Still, there were a few books that I’d read half of but needed a bit of extra incentive to make completing them a priority.</p><h4>Break Down the Goal</h4><p>To finish reading 20 books in a year, I’d need to complete a little over 1.5 books per month, or a bit more than half a book per week. But how long is half a book?</p><p>According to a few articles I’ve looked at including <a href="https://manuscriptagency.com.au/word-count-by-genre-how-long-should-my-book-be/">this one</a> from the “Manuscript Appraisal Agency,” most novels are between 60,000 and 100,000 words. So we could say that the average would be around 80,000 words. Google, <a href="https://careerauthors.com/genre-book-length/">and this article</a>, say that a novel of 80,000 words would be about 320 pages. This seemed right to me as an average length, which would mean that I should read an average of 160 pages per week, or 23 pages a day.</p><p>I decided that if I needed to broaden my strategy if I was going to achieve this goal.</p><h4>Make Use of Different Media</h4><p>To maximise my available reading time I decided to allow audiobooks to count towards my goal. I realise this might not work for everyone.</p><p>For me, when reading non-fiction books that don’t feature charts and diagrams, as well as classic novels from the 19th century, I find I can make a lot more progress when listening to them than when sitting down to read them. I find it’s often good to get a print copy of the book as well. That way I can revisit particular passages that might be a bit more complex.</p><p>I also read a lot of e-books on my phone and on an e-ink reader. I find this custom reader particularly useful late at night when my partner is already asleep. At these times, I just want to crawl into bed and read a few more pages without any bright light shining in my eyes.</p><p>I keep the e-reader’s backlight at the lowest possible setting and often fall asleep while reading. Sometimes this means I need to backtrack a few pages when I start reading again, but it’s definitely not a waste of time.</p><p>Having a range of books on my phone means I always have something to read wherever I am.</p><h4>The Numbers Aren’t Really Important</h4><p>Many people will tell you that it’s better to focus on the quality of the books rather than the number of books you read. More importantly, focus on absorbing their message and taking action based on the knowledge and insights you gained.</p><p>I wholeheartedly agree with this, but a reading goal still helped me to prioritise completing books that interested me.</p><p>On completing a book, I try to take a few minutes to review it online, look back over my favourite quotes, re-read the introduction and make mention of it in my daily journal. Doing this helps me to remember the most important things I’ve learned from the work.</p><h4>You Don’t Need to Complete Every Book You Start</h4><p>I’ve started a lot more books than I’ve finished. I think it’s fine to stop when a book isn’t clicking with you, no matter how famous or well-regarded the work is. If you’re not enjoying a book you’re not going to be able to properly absorb its content. Sometimes I’ve put a book down for a month or a year or longer and then come back to find I was finally in the right place in my life to appreciate it.</p><p>Often, switching format helps me. There are quite a few books that I’ve alternately listened to and read passages from, depending on what felt best at the time.</p><p>But I’ve also had to accept that some books are, for me, never going to be worth the time it will take to read them.</p><h4>Include Page-a-Day Books to Easily Boost Your Numbers</h4><p>I’ve particularly enjoyed reading and re-reading Ryan Holiday’s “Daily Stoic” and Tolstoy’s “A Calendar of Wisdom.” Having these available in a reader app on my phone has given me something interesting to read and allowed me to make progress towards my goal when waiting for a train or when the kids are playing well together on the playground.</p><p>These moments when I used to turn to news websites or read click-bait articles can now contribute towards my yearly goal.</p><h4>Track Your Progress</h4><p>It’s easy to forget how many books you’ve started or completed in a year. I started out tracking my progress with a simple spreadsheet but soon switched to <a href="https://www.goodreads.com/">goodreads.com</a> to set and track progress towards my goals.</p><p>I didn’t share my progress with others (other than my partner) but that’s also easy to do on Goodreads and might help give some people incentive to keep on track towards their goal.</p><p>This is now the fourth year where I’ve given myself a reading challenge. In 2018 I actually surpassed my goal, finishing 27 books.</p><p>In 2019 I set the bar at 30 books and finished 37.</p><p>In 2020 I decided to try for 40 books and finished 41. Interestingly the average length, according to Goodreads was 404 pages, which means I was managing about 44 pages per day on average. And that feels good.</p><h4>Give Yourself a Reward</h4><p>Each year, after completing my goal, I bought and read two or three graphic novels that I’d had recommended to me by friends or articles. This has given me more incentive to finish my goal early and has allowed me to dive into some beautifully illustrated works while feeling like I’ve earned them.</p><p><a href="https://stuart-mclean.medium.com/altering-my-worldview-in-2021-afce592630db">Here’s a list</a> of the most worldview-changing books I read in 2021.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d56db863a01c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Altering my Worldview in 2021]]></title>
            <link>https://stuart-mclean.medium.com/altering-my-worldview-in-2021-afce592630db?source=rss-aa921bd25d8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/afce592630db</guid>
            <category><![CDATA[reading]]></category>
            <category><![CDATA[diversity]]></category>
            <category><![CDATA[multiculturalism]]></category>
            <category><![CDATA[inspiration]]></category>
            <category><![CDATA[empathy]]></category>
            <dc:creator><![CDATA[Stuart McLean]]></dc:creator>
            <pubDate>Sat, 01 Jan 2022 21:37:05 GMT</pubDate>
            <atom:updated>2022-01-01T21:53:19.039Z</atom:updated>
            <content:encoded><![CDATA[<p>A list of books that I think changed me for the better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hIZjNCE3-ZrkXlCE" /><figcaption>Photo by <a href="https://unsplash.com/@sevenshooterimage?utm_source=medium&amp;utm_medium=referral">Seven Shooter</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Contents</h4><p>∘ <a href="#74c4">“Girl, Woman, Other” by Bernardine Evaristo</a><br> ∘ <a href="#eb3c">“Nomadland: Surviving America in the 21st Century” by Jessica Bruder</a><br> ∘ <a href="#c68b">“End of the Rope: Mountains, Marriage, and Motherhood” by Jan Redford</a><br> ∘ <a href="#7cae">“In The End, It Was All About Love” by Musa Okwonga</a></p><h4>“Girl, Woman, Other” by Bernardine Evaristo</h4><p>Like many of the characters in this novel, I passed through London on my way to other places and was changed forever by the experience. The magic of this novel for me was Evaristo allowing me not just to sympathise but also identify with such a broad range of individuals who were so different from me.</p><p>Some favourite quotes:</p><blockquote>she explained that being a sistah was a response to how we’re seen as much as who we are, which actually defies simplistic reductionism, that who we are is partly a response to how we’re seen</blockquote><blockquote>Aaron says he’ll lose his core clientele if his staff look normal and are nice to people</blockquote><blockquote>she sinks back, watches their performances, quite content to be left to her own devices, nodding off, until people prod her to see if she’s all right, the equivalent of checking her pulse</blockquote><h4>“Nomadland: Surviving America in the 21st Century” by Jessica Bruder</h4><p>I saw the remarkable movie that’s loosely based on this book before I read it. I was happy to find the book left an even more open, ambiguous ending than the film. There is hope left in America but it’s shrinking. We need to band together and collectively pressure businesses and politicians to stand up for the majority of their respective customers and constituents. If only we cared enough about more than the next paycheck.</p><p>Some favourite quotes:</p><blockquote>Being human means yearning for more than subsistence. As much as food or shelter, we require hope.</blockquote><blockquote>Today the United States has the most unequal society of all developed nations.</blockquote><p>I also loved being reminded of this quote from Kurt Vonnegut’ “Slaughterhouse-Five,” first published in 1969:</p><blockquote>America is the wealthiest nation on Earth, but its people are mainly poor, and poor Americans are urged to hate themselves.</blockquote><h4>“End of the Rope: Mountains, Marriage, and Motherhood” by Jan Redford</h4><p>I’ve spent time around a few people who are true mountaineering types but I’m not a climber. I just like to walk up mountains, not hang precariously from overhangs.</p><p>I’ll never fully understand climbers, but this brook brought me closer to a comprehension of the desires, dreads and addictions of this sort of person than anything I’ve read by “celebrity” climbers. The struggles Redford goes through in her quest for an environment she can feel comfortable in, being a good partner and parent while using her talents in a fulfilling way, struck a chord with me.</p><p>Some favourite quotes:</p><blockquote>It was just me. Alone. On a steep rock face that didn’t give a shit if I could do the flex-arm hang.</blockquote><blockquote>I wanted to be able to touch the paper and know it was the same paper his hands had touched.</blockquote><blockquote>A shiny film covered the linoleum of my tiny kitchen. Sam had chucked his sippy cup of apple juice at the cupboard the other day and I’d wiped it up with a cloth, but our shoes still peeled off the floor like velcro.</blockquote><h4>“In The End, It Was All About Love” by Musa Okwonga</h4><p>Okwonga and I come from very different backgrounds but we’ve lived in two of the same cities, London and Berlin, partly attracted by their diversity. Okwonga’s experience of these cities has been very different from mine, and I was fascinated by the unexpected angles he highlights in his portraits of places that I thought I already knew well.</p><p>Some favourite quotes:</p><blockquote>It is not a bubble. A bubble is a carefully-sealed world whose occupants are oblivious to everything that happens beyond it. Berlin is something different. It is a refuge, an enclave, a safe haven.</blockquote><blockquote>That Nazi march was terrifying but the schnitzel here is nice.</blockquote><p>I also appreciated Okwonga’s reassuring philosophy, sprinkled throughout the book.</p><blockquote>I would only say that, whatever you do next — please remember that there will always be a next thing, another goal to reach. Another excuse not to like yourself until you have achieved some new ambition. But it’s okay to like yourself right now, though.</blockquote><p>Hopefully, this will encourage you to read some of these fascinating and inspiring books. For more on my approach to reading widely and often, see <a href="https://stuart-mclean.medium.com/i-finished-reading-50-books-in-2021-d56db863a01c">my article on finishing fifty books in a year</a> (while still keeping a family and a full-time job).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afce592630db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL Queries in Python]]></title>
            <link>https://python.plainenglish.io/graphql-queries-in-python-f658b74f29e9?source=rss-aa921bd25d8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f658b74f29e9</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[beginner-coding]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api-integration]]></category>
            <dc:creator><![CDATA[Stuart McLean]]></dc:creator>
            <pubDate>Fri, 30 Jul 2021 15:27:25 GMT</pubDate>
            <atom:updated>2022-11-08T11:05:19.435Z</atom:updated>
            <content:encoded><![CDATA[<h4>Taking a script from rough sketch to maintainable production code.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ir8caXpNz0epTJA1" /><figcaption>Photo by <a href="https://unsplash.com/@isaacmsmith?utm_source=medium&amp;utm_medium=referral">Isaac Smith</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I recently had the challenge of migrating images from one online platform to another. This became particularly interesting since the platform we needed to move the images to presented a GraphQL API (The “QL” stands for “Query Language” and “API” is short for Application Programming Interface).</p><p>Let’s dive into the world of GraphQL and how we can use it in Python.</p><h4>Contents</h4><p>· <a href="#1034">Getting Started</a><br>· <a href="#9151">Our First Graphql Query</a><br>· <a href="#12e9">Preparing Pagination</a><br>· <a href="#ef50">Extracting GraphQL Queries to Separate Files</a><br>· <a href="#6dee">Splitting up logic</a><br>· <a href="#db82">Handling Errors</a><br>· <a href="#383c">A Finished Product</a><br>· <a href="#2184">Conclusion and Next Steps</a></p><h3>Getting Started</h3><p>The images that need to be migrated are associated with particular products. But not all of the products are available on the destination platform. It makes sense then to start by asking the destination platform what products were available.</p><h3>Our First Graphql Query</h3><p>The SKU (Stock Keeping Unit) code of each product is common across both platforms, so we can start by querying the destination platform’s API for the SKUs of all products. The basic query looks like this:</p><pre>query {<br>   products {<br>    sku <br>  }<br>}</pre><p>One of the great things about GraphQL is how instantly readable the syntax is. We can easily see that this is a query to request the SKUs of all products.</p><h3>Querying in Python</h3><p>We can use a Python library to execute this query. Doing so requires a bit of setup. We can use pip to download the gql (short for Graph Query Language) and aiohttp libraries. To handle the configuration parameters required by the API, it would also be useful to have the python-dotenv library.</p><p>We can then create a simple script to instantiate the GraphQL client:</p><pre>from dotenv import dotenv_values<br>from gql import gql, Client<br>from gql.transport.aiohttp import AIOHTTPTransport</pre><pre>env = dotenv_values()<br>headers = {&quot;Authorization&quot;: f&quot;Bearer {env[&#39;DEST_TOKEN&#39;]}&quot;}<br>transport = AIOHTTPTransport(url=env[&#39;DEST_URL&#39;], headers=headers)<br>client = Client(transport=transport)</pre><p>Let’s walk through this quickly. We’re starting with the library for handling .env files, which are a great way of keeping configuration parameters such as passwords out of your code. Our .env file for this project looks something like this:</p><pre>DEST_URL=&quot;https://destination-api.example.com&quot;<br>DEST_TOKEN=&quot;super_secret_generated_token&quot;</pre><p>Our code can use these values to set up the header and http transport layer used by the gql client, which then makes queries for us like this:</p><pre>...</pre><pre>products_query = gql(&quot;&quot;&quot;<br>  query {<br>    products {<br>      sku <br>    }<br>  }<br>&quot;&quot;&quot;)</pre><pre>response = client.execute(products_query)</pre><pre>print(len(response[&#39;products&#39;]))</pre><p>The gql function prepares the query string. Then the client sends the query and parses the JSON (JavaScript Object Notation) response into a dictionary containing the key ‘products’, which should contain a list of dictionaries containing all the product parameters we’ve requested — in this case, SKUs. The response should look something like this:</p><pre>[{&#39;sku&#39;: &#39;12345&#39;}, {&#39;sku&#39;: &#39;23456&#39;}, {&#39;sku&#39;: &#39;34567&#39;}]</pre><p>But looking at the length of that list, and comparing it to the number of expected products (numbering in the thousands) it’s immediately clear that not all the products are being returned. What’s wrong?</p><h3>Preparing Pagination</h3><p>To avoid sending a lot of information all at once, which might overwhelm both the requesting and responding servers, many APIs will only provide a small portion of the entries available, for example, 100 records at a time. The documentation of this product API shows that it permits these parameters:</p><ul><li>“first” — allowing us to ask for the first n items.</li><li>“skip” — the number of records to skip over before providing a response.</li></ul><p>In GraphQL syntax we can pass these parameters like this:</p><pre>query {<br>   products(first: 100, skip: 100 {<br>    sku <br>  }<br>}</pre><p>This would return us 100 products, starting with the 101st product. In other words, it returns the second “page” of records. But how many records are there? Do we need to prepare a separate query for each set? That would get pretty messy. Fortunately, GraphQL allows us to pass parameters to our query and use them in place of previously hard-coded values like this:</p><pre>query ($first: Int!, $skip: Int!) {<br>  products(first: $first, skip: $skip) {<br>    sku <br>  }<br>}</pre><p>GraphQL parsers understand that any word following a “$” is now considered a variable. Adding the exclamation point to the parameter type (Int) makes these required parameters, which means we’ll get an error if we forget to include them.</p><p>We can now easily loop through all our products like this:</p><pre>...</pre><pre>products_query = gql(&quot;&quot;&quot;<br>  query ($first: Int!, $skip: Int!) {<br>    products(first: $first, skip: $skip) {<br>      sku <br>    }<br>  }<br>&quot;&quot;&quot;)</pre><pre>page_size = 100<br>skip = 0</pre><pre>while True:<br>    vars = {&quot;first&quot;: page_size, &quot;skip&quot;: skip}<br>    response = client.execute(products_query, variable_values=vars)<br>    skip += page_size</pre><pre>    if not response[&#39;products&#39;]:<br>        break</pre><pre>    &lt;fetch images and upload etc...&gt;</pre><p>Here we create an infinite loop and keep asking for more products, increasing the “skip” value by the page size on each iteration. When no products are returned, we break our loop.</p><h3>Extracting GraphQL Queries to Separate Files</h3><p>An obvious “code smell” is seeing code written in another language encapsulated in a string variable. We can easily extract our GraphQL query into its own file, naming it something like products_query.graphql and load it with a function:</p><pre>def load_query(path):<br>    with open(path) as f:<br>        return gql(f.read())</pre><pre>products_query = load_query(&#39;products_query.graphql&#39;)</pre><p>This reads much more nicely than having a multi-line string containing our query, especially when we need to add more properties to the query later on. If the query file isn’t available our script will crash, but that’s actually for the best. There’s no point in executing an empty query.</p><h3>Splitting up logic</h3><p>Our script is already getting pretty long. Let’s try encapsulating our GraphQL logic in its own class.</p><pre>from gql import gql, Client<br>from gql.transport.aiohttp import AIOHTTPTransport</pre><pre>class ProductProvider:<br>    def __init__(self, conf):<br>        url = conf[&#39;DEST_URL&#39;]<br>        headers = {&quot;Authorization&quot;: f&quot;Bearer {conf[&#39;DEST_TOKEN&#39;]}&quot;}<br>        transport = AIOHTTPTransport(url=url, headers=headers)<br>        self._client = Client(transport=transport)<br>        self._query = self._load_query(&#39;products_query.graphql&#39;)</pre><pre>    def get_products(self, page_size, skip):<br>        v = {&quot;first&quot;: page_size, &quot;skip&quot;: skip}<br>        return self._client.execute(self._query, variable_values=v)</pre><pre>    def _load_query(self, path):<br>        with open(path) as f:<br>            return gql(f.read())</pre><p>This is ok, but it still means our script will have to handle pagination. A much nicer technique would be to use Python’s yield keyword, making our function into a generator.</p><p><a href="https://wiki.python.org/moin/Generators">Generators - Python Wiki</a></p><p>We can then return products one by one and still handle pagination within our function.</p><pre>...</pre><pre>def get_products(self, page_size=100):<br>    skip = 0<br>    while True:<br>        v = {&quot;first&quot;: page_size, &quot;skip&quot;: skip}<br>        products = self._client.execute(<br>            self._query, <br>            variable_values=v<br>        )</pre><pre>        if not products[&#39;products&#39;]:<br>            return</pre><pre>        skip += page_size<br>        for product in products[&#39;products&#39;]:<br>            yield product<br>...</pre><p>Including the optional page_size variable makes it obvious that pagination is occurring and is handled within the function.</p><h3>Handling Errors</h3><p>One nice finishing touch is some query error handling. Looking at the gql library we can see that it returns errors with multiple messages.</p><p><a href="https://github.com/graphql-python/gql/blob/master/gql/transport/exceptions.py#L36">gql/exceptions.py at master · graphql-python/gql</a></p><p>After some experimentation we can see that we usually only care about the first error message from this class, so we could add a function that wraps the client.execute method and transforms that error into a custom exception.</p><pre>...<br>from gql.transport.exceptions import TransportQueryError</pre><pre><br>class ProductProviderError(Exception):    <br>    pass </pre><pre>class ProductProvider:<br>...<br>    def _execute(self, query, vars):<br>        try:            <br>            return self._client.execute(query, variable_values=vars)        <br>        except TransportQueryError as err:            <br>            raise ProductProviderError(err.errors[0][&#39;message&#39;])</pre><p>We can then easily catch and print exceptions like this:</p><pre>from product_provider import ProductProvider, ProductProviderError</pre><pre>...</pre><pre>try:<br>    for product in product_provider.get_products():<br>      print(product)<br>except ProductProviderError as err:<br>    print(err)</pre><h3>A Finished Product</h3><p>With the encapsulation of our GraphQL calls into a custom class, we have a very simple script to run.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fb455353fe406e2dfd696ad8d3a9733/href">https://medium.com/media/6fb455353fe406e2dfd696ad8d3a9733/href</a></iframe><p>Our ProductProvider class is a bit more complicated but encapsulates the API’s pagination and the gql library’s exceptions. It also provides the potential for reuse.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51e6b30e9435c2247a8d65f9ddfe6cc4/href">https://medium.com/media/51e6b30e9435c2247a8d65f9ddfe6cc4/href</a></iframe><p>Our query is in its own file for easy readability, updating and reusability.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d3f89b4ff3363cbbbe1a55e33afa2fe/href">https://medium.com/media/9d3f89b4ff3363cbbbe1a55e33afa2fe/href</a></iframe><p>Finally, for dependency management, our requirements.txt file should look something like this:</p><pre>gql~=3.0.0a6<br>aiohttp~=3.7<br>python-dotenv~=0.18</pre><p>To install them all at once, we can run pip3 install -r requirements.txt</p><h3>Conclusion</h3><p>Good development practices are usually iterative. We create a rough idea that works and then make it more readable, robust and reusable.</p><p>Our script started out very rough, but since we could quickly prove that the concepts worked, we could follow up with best practices and we were able to distribute responsibility and create a reusable component.</p><p>We’ll look at a way of handling image downloads and uploads for this project in a future post.</p><p>Want more Python tips?</p><p><a href="https://python.plainenglish.io/solving-a-respectable-codility-challenge-in-one-line-of-python-b560dacbac00">I Solved a Codility Challenge with One Line of Python</a></p><p>Some recommendations about useful tools:</p><p><a href="https://medium.com/star-gazers/tools-for-new-developers-part-1-266616f4dc8f">Tools for New Developers — Part 1</a></p><h4>Further Reading</h4><ul><li><a href="https://plainenglish.io/blog/how-to-build-a-graphql-ecommerce-app-from-scratch">How to Build a GraphQL eCommerce App from Scratch</a></li><li><a href="https://plainenglish.io/blog/how-to-compose-and-integrate-apis-together-as-if-you-were-using-npm-for-apis">How to Compose and Integrate APIs Together as if You Were Using NPM for APIs</a></li></ul><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>. Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f658b74f29e9" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/graphql-queries-in-python-f658b74f29e9">GraphQL Queries in Python</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>
        <item>
            <title><![CDATA[I Solved a Codility Challenge with One Line of Python]]></title>
            <link>https://python.plainenglish.io/solving-a-respectable-codility-challenge-in-one-line-of-python-b560dacbac00?source=rss-aa921bd25d8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b560dacbac00</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[codility]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Stuart McLean]]></dc:creator>
            <pubDate>Sat, 26 Jun 2021 09:12:17 GMT</pubDate>
            <atom:updated>2021-06-26T12:47:35.200Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solving a “Respectable” Codility Challenge in One Line of Python</h3><h4>Keeping things simple and efficient.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bzzfKcNFx7EwJ2Aj" /><figcaption>Photo by <a href="https://unsplash.com/@goshua13?utm_source=medium&amp;utm_medium=referral">Joshua Aragon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Contents</h4><p>∘ <a href="#ca1e">The Task</a><br> ∘ <a href="#a423">Understanding the Challenge</a><br> ∘ <a href="#7118">Iterating in Steps</a><br> ∘ <a href="#4853">A Set of Basic Mathematical Operations</a><br> ∘ <a href="#743f">Test Cases Used</a><br> ∘ <a href="#c27a">References</a></p><p>I really like Codility challenges. They’re a wonderful (and totally free) way to improve your problem-solving skills and programming language knowledge. They’re also a great way to “warm-up” your brain for technical interviews, especially since most of your solutions are evaluated on their ability to handle edge cases while remaining time-efficient.</p><p>Much of modern professional development consists of configuring and chaining libraries together, so it’s refreshing to get to sink into a task that’s purely logic and performance-based.</p><p>Over the past couple of years, I’ve been slowly working through their lessons and challenges on weekends and holidays and it’s helped me to retain a mindset of looking for “greedy algorithm” solutions and considering both performance and readability.</p><p>One particular lesson took me by surprise. Codility tasks are rated, in order of difficulty, as “Painless,” “Respectable,” or “Ambitious.” This task was rated “Respectable” but it is efficiently solvable with a single line of code.</p><h4>The Task</h4><p>Codility lessons are comprised of reading material in a PDF and a set of “tasks.” The first task in the “Prefix Sums” lesson is called “Count Div.” The instructions are:</p><blockquote>Write a function … that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K</blockquote><p>We are guaranteed that A ≤ B.</p><h4>Understanding the Challenge</h4><p>To gain a more complete view of a problem, I sometimes find it useful to sketch it out without worrying at all about efficiency.</p><p>An obvious brute-force solution would be to iterate through all the integers between A and B checking if they are divisible by K using modulo (%).</p><p>To be safe we also need to check that B != 0:</p><pre>def solution(a, b, k):<br>  if b == 0:<br>    return 0<br><br>  count = 0<br>  for ii in range(a, b + 1):<br>    if ii % k == 0:<br>      count += 1<br><br>  return count</pre><p>Or, much more concisely, using the ternary operator in a list comprehension to give us a count (len) of all numbers that fit our criteria:</p><pre>def solution(a, b, k):<br>  return 0 if b == 0 else len([ii for ii in range(a, b + 1) if ii % k == 0])</pre><p>This will run in linear time — O(n)— which is less than ideal if A is 0 and B is the test’s possible maximum value of 2 billion.</p><h4>Iterating in Steps</h4><p>Similarly, as in the example below, finding the smallest and largest multiple of k in the range of A to B and iterating in steps equal to K should still leave us with O(n)— particularly inefficient if K is 1.</p><pre>def solution(a, b, k):<br>  if b == 0:<br>    return 0<br><br>  first_divisible = a if a % k == 0 else a + (k - a % k)<br>  last_divisible = b - b % k<br><br>  return len(range(first_divisible, last_divisible + 1, k))</pre><p>But some python magic comes into play here, with the language efficiently knowing the len of the range, even with the step value. This works.</p><p>But this also shows a more readable, concise and efficient solution. We can now see that all we need to see is how many times multiples of K occur between A and B.</p><h4>A Set of Basic Mathematical Operations</h4><p>Let’s use the original example from Codility, a = 6, b = 11, k = 2</p><ul><li>11 / 2 = 5.5 — which we can round down to 5 to give the total number of ways that 2 goes evenly into 11</li><li>(6 - 1) / 2 = 2.5 — which we can round down to 2 for the number of ways ints <strong>less than</strong> 6 are evenly divisible by 2. We can subtract these from the total above.</li><li>5 - 2 = 3 — subtract the excluded count from the total to get our result.</li></ul><p>In the floor division operator ( // ) will automatically round down the quotient, returning a float value that we can cast to an integer for consistency. This makes our solution both tidy and efficient, running in O(1) constant time.</p><pre>def solution(a, b, k):<br>  return 0 if b == 0 else int(b // k - (a - 1) // k)</pre><p>We still need to handle the edge case where B is zero, but again the ternary operator keeps the code short and easy to read.</p><h4>Either of these last two examples will still get a 100% result on Codility.</h4><p>Please let me know if anything here doesn’t make sense or if you can think of an even more concise way to achieve this result.</p><h4>Test Cases Used</h4><p>I thought it might be useful to include the test cases I worked with in creating these examples.</p><pre>cases = [<br>    [4, 10, 3, 2],<br>    [10, 10, 5, 1],<br>    [10, 10, 7, 0],<br>    [10, 10, 20, 0],<br>    [0, 0, 10, 0],<br>    [5, 100, 6, 16],<br>    [5, 100, 5, 20],<br>    [5, 102, 6, 17],<br>    [0, 2, 2, 2],<br>    [0, 5, 5, 2],<br>    [0, 5, 1, 6],<br>    [1, 5, 1, 5],<br>    [0, 2000000000, 1, 2000000001],<br>    [0, 2000000000, 2, 1000000001],<br>]</pre><p>These were prepared with the syntax: [a, b, k, expected] so that they could be included in a loop test such as:</p><pre>def test_solution(self):<br>  for case in self.cases:<br>    with self.subTest(case):<br>      self.assertEqual(solution(case[0], case[1], case[2]), case[3])</pre><h4>References</h4><ul><li><a href="https://app.codility.com/programmers/lessons/5-prefix_sums/">5. Prefix Sums lesson - Learn to Code - Codility</a></li><li><a href="https://python-reference.readthedocs.io/en/latest/docs/operators/floor_division.html">// floor division - Python Reference (The Right Way) 0.1 documentation</a></li></ul><p><a href="https://medium.com/geekculture/solving-a-respectable-codility-challenge-in-one-line-of-code-6c331deff8bb"><em>Note: This article was previously published with code examples in Ruby.</em></a></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b560dacbac00" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/solving-a-respectable-codility-challenge-in-one-line-of-python-b560dacbac00">I Solved a Codility Challenge with One Line of Python</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>
        <item>
            <title><![CDATA[Solving a “Respectable” Codility Challenge in One Line of Code]]></title>
            <link>https://medium.com/geekculture/solving-a-respectable-codility-challenge-in-one-line-of-code-6c331deff8bb?source=rss-aa921bd25d8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c331deff8bb</guid>
            <category><![CDATA[brain-training]]></category>
            <category><![CDATA[codility]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Stuart McLean]]></dc:creator>
            <pubDate>Wed, 16 Jun 2021 04:42:58 GMT</pubDate>
            <atom:updated>2021-06-26T09:10:36.654Z</atom:updated>
            <content:encoded><![CDATA[<p>Keeping things simple and efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bzzfKcNFx7EwJ2Aj" /><figcaption>Photo by <a href="https://unsplash.com/@goshua13?utm_source=medium&amp;utm_medium=referral">Joshua Aragon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Contents</h4><p>∘ <a href="#ca1e">The Task</a><br> ∘ <a href="#a423">Understanding the Challenge</a><br> ∘ <a href="#7118">Iterating in Steps</a><br> ∘ <a href="#4853">A Set of Basic Mathematical Operations</a><br> ∘ <a href="#f528">Porting to Python</a><br> ∘ <a href="#c27a">References</a></p><p>I really like Codility challenges. They’re a wonderful (and totally free) way to improve your problem-solving skills and programming language knowledge. They’re also a great way to “warm-up” your brain for technical interviews, especially since most of your solutions are evaluated on their ability to handle edge cases while remaining time-efficient.</p><p>Much of modern professional development consists of configuring and chaining libraries together, so it’s refreshing to get to sink into a task that’s purely logic and performance-based.</p><p>Over the past couple of years, I’ve been slowly working through their lessons and challenges on weekends and holidays and it’s helped me to retain a mindset of looking for “greedy algorithm” solutions and considering both performance and readability.</p><p>One particular lesson took me by surprise. Codility tasks are rated, in order of difficulty, as “Painless,” “Respectable,” or “Ambitious.” This task was rated “Respectable” but it is efficiently solvable with a single line of code.</p><h4>The Task</h4><p>Codility lessons are comprised of reading material in a PDF and a set of “tasks.” The first task in the “Prefix Sums” lesson is called “Count Div.” The instructions are:</p><blockquote>Write a function … that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K</blockquote><p>We are guaranteed that A ≤ B.</p><h4>Understanding the Challenge</h4><p>To gain a more complete view of a problem, I sometimes find it useful to sketch it out without worrying at all about efficiency.</p><p>An obvious brute-force solution would be to iterate through all the integers between A and B checking if they are divisible by K using modulo (%).</p><p>To be safe we also need to check that B != 0. In ruby:</p><pre>def solution(a, b, k)<br>  return 0 if b == 0</pre><pre>  count = 0<br>  (a..b).each do |ii| <br>    count += 1 if ii % k == 0<br>  end</pre><pre>  count<br>end</pre><p>Or, much more concisely, using the ternary operator and filterto give us a count (size) of all numbers that fit our criteria:</p><pre>def solution(a, b, k)<br>  b == 0 ? 0 : (a..b).filter{ |ii| ii % k == 0 }.size<br>end</pre><p>This will run in linear time — O(n)— which is less than ideal if A is 0 and B is the test’s possible maximum value of 2 billion.</p><h4>Iterating in Steps</h4><p>Similarly, as in the example below, finding the smallest and largest multiple of k in the range of A to B and iterating in steps equal to K still leaves us with O(n)— particularly inefficient if K is 1.</p><pre>def solution(a, b, k)<br>  return 0 if b == 0 || k &gt; b</pre><pre>  first_divisible = a % k == 0 ? a : a + (k - a % k)<br>  last_divisible = b - b % k<br>  (first_divisible..last_divisible).step(k).size<br>end</pre><p>But we’re close to an efficient solution. We can now see that all we need to see is how many times multiples of K occur between A and B.</p><h4>A Set of Basic Mathematical Operations</h4><p>Let’s use the original example from Codility, a = 6, b = 11, k = 2</p><ul><li>11 / 2 = 5.5 — which we can round down to 5 to give the total number of ways that 2 goes evenly into 11</li><li>(6 - 1) / 2 = 2.5 — which we can round down to 2 for the number of ways ints <strong>less than</strong> 6 are evenly divisible by 2. We can subtract these from the total above.</li><li>5 - 2 = 3 — subtract the excluded count from the total to get our result.</li></ul><p>In ruby, dividing one integer by another will automatically round down the quotient, returning an integer result. This makes our solution both tidy and efficient, running in O(1) constant time.</p><pre>def solution(a, b, k)<br>  b / k - (a - 1) / k<br>end</pre><p>The edge cases where A and/or B are zero are also neatly handled by the rounded-down division.</p><h4>Porting to Python</h4><p>Python’s floor division (“//” operator) can also handle this operation for us, although we still need to check if B is 0.</p><pre>def solution(a, b, k):<br>    return 0 if b == 0 else int(b // k - (a - 1) // k)</pre><p>Either of these last two examples will still get a 100% result on Codility.</p><p>Please let me know if anything here doesn’t make sense or if you can think of an even more concise way to achieve this result.</p><h4>References</h4><ul><li><a href="https://app.codility.com/programmers/lessons/5-prefix_sums/">5. Prefix Sums lesson - Learn to Code - Codility</a></li><li><a href="https://python-reference.readthedocs.io/en/latest/docs/operators/floor_division.html">// floor division - Python Reference (The Right Way) 0.1 documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c331deff8bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/solving-a-respectable-codility-challenge-in-one-line-of-code-6c331deff8bb">Solving a “Respectable” Codility Challenge in One Line of Code</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[Automating Git Deployment]]></title>
            <link>https://medium.com/star-gazers/automating-git-deployment-93678bd4c8b?source=rss-aa921bd25d8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/93678bd4c8b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Stuart McLean]]></dc:creator>
            <pubDate>Mon, 31 May 2021 13:53:27 GMT</pubDate>
            <atom:updated>2021-06-09T18:50:41.081Z</atom:updated>
            <content:encoded><![CDATA[<p>Tips and tricks and a script…</p><h4>Disclaimer</h4><p>This post assumes a basic understanding of git version control. If you don’t know about it, I recommend reading <a href="https://git-scm.com/book/en/v2/Git-Basics-Getting-a-Git-Repository">chapter two of the free git book</a>.</p><h4>Contents</h4><p>∘ <a href="#5204">A Clear Case for Automation</a><br> ∘ <a href="#3a06">Checking Out</a><br> ∘ <a href="#c6cd">Merging the Branches</a><br> ∘ <a href="#96fe">Logging and Pushing</a><br> ∘ <a href="#dafc">Confirmation</a><br> ∘ <a href="#7588">Adding Variables</a><br> ∘ <a href="#ee49">Getting Back to Work</a><br> ∘ <a href="#3722">Putting Everything Together</a><br> ∘ <a href="#e631">Was it Worth Taking the Time to Automate?</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G9kDNnIPZPkj-wC9" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych?utm_source=medium&amp;utm_medium=referral">Roman Synkevych</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>A Clear Case for Automation</h4><p>Several companies I’ve worked for have deployed using the concept of a “trunk” branch, used for development branching and a “main” branch in line with what is actually deployed.</p><p>Deployment then involves pulling down the latest versions of both branches, merging “trunk” into “main” and then pushing “main” back to the origin git repo, where the automated CI/CD (Continuous Integration / Continuous Delivery) process will run tests and builds. If these processes succeed it will deploy the built artifacts or Docker containers to production servers.</p><p>This local pulling, merging and pushing process involves only a few steps but it still takes time and has room for error. So it seems like the perfect opportunity for a script, and in this case, since git commands work beautifully on the command line, a bash script felt just right to me.</p><h4>Checking Out</h4><p>We first need to ensure we’re on our “trunk” branch and pull down the latest approved changes to be sent to production. Then we need to switch to our “main” branch and fetch the latest changes there. This already sounds repetitive. Why not add a function:</p><pre>function checkoutpull {    <br>    git checkout &quot;$1&quot;    <br>    git pull<br>}</pre><pre>checkoutpull trunk<br>checkoutpull main</pre><p>There’s a slightly safer and more elegant way of doing this which should avoid any unnecessary merge commits. It starts by getting the latest changes for our origin repository with git remote update —doing this once covers both branches — and then, rather than calling git pull, merging each branch with its associated upstream branch using git merge --ff-only @{u} .</p><pre>function checkoutpull {    <br>    git checkout &quot;$1&quot;    <br>    git merge --ff-only @{u}<br>}</pre><pre>git remote update<br>checkoutpull trunk<br>checkoutpull main</pre><h4>Merging the Branches</h4><p>Now let’s merge “trunk” into our “main” branch. Once again, we’ll use the ff-only strategy.</p><pre>...<br>checkoutpull trunk<br>checkoutpull main<br>git merge $STAGING_BRANCH --ff-only</pre><h4>Logging and Pushing</h4><p>Then there’s just one more thing to do, right? Push the branch and we’re done. But as responsible developers, we should have a quick peek at git’s log file to ensure we’re really deploying what we intend to. It’s possible that someone else accidentally merged in an unintended change just before we updated our “trunk” branch. Stranger things have happened.</p><p>Se we add:</p><pre>git log<br>git push</pre><p>git log will open the commit log file in the configured viewer, which is “less” by default. When we press q less will exit and the script will push to master.</p><p>Done.</p><p>Except…</p><p>What if we don’t like what we see in git log? We want to avoid pushing to prod then.</p><h4>Confirmation</h4><p>Like most languages, bash has the ability to ask a user for input, so let’s use it! To be extra safe, let’s make ourselves type the word “yes” to execute a deployment. Typing anything else will exit the script without deploying.</p><pre>git log<br>read -p &quot;Deploy? yes/[n]: &quot; SHOULD_DEPLOY    <br>if [ &quot;$SHOULD_DEPLOY&quot; == &quot;yes&quot; ]; then        <br>    git push       <br>fi</pre><p>This also gives us a chance to automatically roll back our local “main” branch when we decide not to deploy.</p><pre>if [ &quot;$SHOULD_DEPLOY&quot; == &quot;yes&quot; ]; then        <br>    git push    <br>else        <br>    git reset --hard &quot;origin/main&quot;    <br>fi</pre><h4>Adding Variables</h4><p>To make our script more reusable, we want to allow for different branch names. Why not allow optional arguments to override our default “main” and “trunk” branch names? Easily done, and while we’re at it, let’s wrap our code in a “main” function for tidiness.</p><pre>...</pre><pre>function main {    <br>    local DEPLOY_BRANCH=${1:-main}    <br>    local STAGING_BRANCH=${2:-trunk}<br>    <br>    git remote update    <br>    checkoutpull &quot;$STAGING_BRANCH&quot; <br>    ...<br>}</pre><pre>main &quot;$@&quot;</pre><p>Now we just need to find the uses of branch name “main” (not function “main”) and replace them with “$DEPLOY_BRANCH” and replace “trunk” with “$STAGING_BRANCH” and we’ve got a nicely reusable script that’s still quick to call when we are using default values.</p><h4>Getting Back to Work</h4><p>One more nice optimization springs to mind. When we’re finished deploying we don’t want to keep working from our “main” branch. Instead, we’ll want to go back to where we were when we started the deployment process, be that the “trunk” branch or another feature branch. We can easily memoize that branch name at the beginning of the process and have our script return us there at the end.</p><pre>...</pre><pre>function main {    <br>    local CURRENT_BRANCH=$(git branch --show-current)<br>    ... <br>    git checkout &quot;$CURRENT_BRANCH&quot;<br>}</pre><h4>Putting Everything Together</h4><p>Here’s a full version of this script, with some extra lines of logging added in for clarity. I made another function, called printemphasized (print emphasized) to make the script’s logging lines more noticeable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e38a0888b1fc6f8c3219974deac6bec0/href">https://medium.com/media/e38a0888b1fc6f8c3219974deac6bec0/href</a></iframe><h4>Was it Worth Taking the Time to Automate?</h4><p>As with any automation, it’s always worth taking the time to consider whether the total outlay of time to develop the solution was more than we’d ever spend on doing the task manually. More importantly, does the end solution decrease the chances of errors and the amount of repetitive toil in our regular work?</p><p>Judging by any of these metrics, I personally consider this script a success, although I’m also curious to hear about any improvements other developers would make to it.</p><p>In any case, I hope this script helps to speed up and eliminate potential errors in your deployment workflow and get you back to developing cool and useful software as quickly as possible.</p><p>If you liked this article, you might be interested in my medium series about <a href="https://medium.com/star-gazers/tools-for-new-developers-part-1-266616f4dc8f">tools for new developers</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93678bd4c8b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/star-gazers/automating-git-deployment-93678bd4c8b">Automating Git Deployment</a> was originally published in <a href="https://medium.com/star-gazers">Star Gazers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I Learned By Keeping a Journal for 1000 Days Straight]]></title>
            <link>https://stuart-mclean.medium.com/what-i-learned-by-keeping-a-journal-for-1000-days-straight-64e4e6614849?source=rss-aa921bd25d8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/64e4e6614849</guid>
            <category><![CDATA[family]]></category>
            <category><![CDATA[journaling]]></category>
            <category><![CDATA[diary-writing]]></category>
            <category><![CDATA[memories]]></category>
            <category><![CDATA[journaling-benefits]]></category>
            <dc:creator><![CDATA[Stuart McLean]]></dc:creator>
            <pubDate>Sat, 15 May 2021 19:35:47 GMT</pubDate>
            <atom:updated>2021-05-15T19:35:47.856Z</atom:updated>
            <content:encoded><![CDATA[<h3>What I Learned by Keeping a Journal for 1000 Days Straight</h3><figure><img alt="An antique typewriter and a cup of coffee on a wooden desk." src="https://cdn-images-1.medium.com/max/1024/1*DyPfukwrlSvxnTf1rlaVhA.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@minan1398?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Min An</a> from <a href="https://www.pexels.com/photo/brown-and-white-table-lamp-on-wooden-table-near-window-1638502/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>A few weeks ago, I got a notification from the Daylio app on my phone that I had submitted a journal entry for each day in the last 1000. Here’s how I got there and what I learned in the process.</p><h4>Contents</h4><p>∘ <a href="#ceeb">It can be a tricky habit to form</a><br> ∘ <a href="#8e13">Entries can be meaningful even when they’re short</a><br> ∘ <a href="#d49c">Don’t make too many rules</a><br> ∘ <a href="#b25a">Use whatever technology is available</a><br> ∘ <a href="#076f">Get reminders</a><br> ∘ <a href="#414d">A personal record is more than worth the time you put in</a><br> ∘ <a href="#5ccf">Work backwards when you get behind</a><br> ∘ <a href="#06d7">References</a></p><h4>It can be a tricky habit to form</h4><p>This was far from my first foray into journaling.</p><p>I started writing longhand, stream-of-consciousness “morning pages” when I was 16. Inspired by Julia Cameron’s “The Artists Way.” I have often returned to this practice whenever I had something resembling a regular schedule, admittedly more often writing a single page rather than the recommended three.</p><p>But it was only about four years ago, around the time my older child was turning three that I decided to try to make a habit of writing a journal in the evening about what had happened that day.</p><p>I’d tried doing this a few times before but always stopped after a few days. I was hoping that a place to record, wonder at and complain about the developments and antics of my kids would keep me going.</p><p>It didn’t work at first. I wrote faithfully every evening for about a week, then dropped down to every other day and soon was only writing an entry around every week. This was certainly better than nothing but not what I wanted to have.</p><figure><img alt="A child making a snow angel on a concrete basketball court." src="https://cdn-images-1.medium.com/max/1024/1*4Nc_zCr8E4EYZwYwy_yqPg.jpeg" /><figcaption>Feb 27, 2021: Last day of our winter “staycation.” Cold and snowy. Kids made snow-angels on the nearby basketball court</figcaption></figure><h4>Entries can be meaningful even when they’re short</h4><p>I started my current streak while on holiday. It was July 17, 2018, and my family and I were about to fly to Canada to visit my parents. My first entry was simple and not very memorable. It’s obvious that we were understandably busy that day. But it was a start.</p><blockquote>July 17, 2018: Last day in Berlin before flying to Canada</blockquote><p>I kept going, making short daily entries, that sometimes grew longer. With no pressure to write more than a sentence, the streak of entries started to build up.</p><figure><img alt="Three children looking down at a valley from a mountain lookout." src="https://cdn-images-1.medium.com/max/1024/1*mEJf6yZ2dyPm4aG7lG1kVw.jpeg" /><figcaption>July 26, 2019: Rode the Sulphur Mountain gondola. Ate dinner at a restaurant with family and friends.</figcaption></figure><h4>Don’t make too many rules</h4><p>When I feel guilty that I can only manage to write a short entry for a day, I try to remind myself why I’m doing this. It’s for me, not for anybody else. OK, sometimes I look back and reminisce with my partner about some particular milestone in the growth of our kids — can you believe it’s been two years since he lost his first tooth? But mostly it’s for me. So I can do what I want.</p><p>Some people might strive for a consistent style in writing. Personally, I haven’t felt the need for this. Sometimes it feels most appropriate to use half the journal entry to talk about five minutes in a day while skimming over the rest. When I’m feeling like I want to write a historical document, or explain the day in bullet points or include a sarcastic rant, I do that.</p><p>Since I’m making the rules myself, I dropped the requirements for entries to be of any particular length. They could be just enough to trigger a memory.</p><blockquote>May 11 2019: Took the rubber dinghy out into a lake with the boys in the afternoon. Went to a concert in the evening.</blockquote><p>The important thing is to keep writing.</p><figure><img alt="A large machine demolishing a building." src="https://cdn-images-1.medium.com/max/1024/1*6Qn48253IRU40Zg-F1fNjA.jpeg" /><figcaption>October 11, 2018: Busy day at the office. Lots of noise from a building being demolished nearby. Kids stuffed a duvet cover with every soft thing they could find and took turns jumping on it.</figcaption></figure><h4>Use whatever technology is available</h4><p>We’re lucky to live in an age with many options for creating and preserving our journal entries. Purpose-built apps on phones, emails to yourself, auto-transcribed dictation — many tools are available for cheap or for free.</p><p>Almost a year before I started my current streak of entries I tried using a service called “Trailmix.” For a small monthly fee, Trailmix sends you daily emails with the subject: “How was your day?” When you reply to the email, Trailmix stores the reply on its servers with the date that it sent the email to you. That way you can catch up if you fall behind. Trailmix also allows you to attach a photo, so you can build up an image journal at the same time.</p><p>I usually write my journal on my phone, either typing on the screen or, if I feel like writing a longer entry, with an external keyboard. I rarely open my laptop to journal because I tend to write last thing before bed.</p><p>Writing a journal electronically also allows you the opportunity to back it up in multiple places so that fire, flood or hard drive failure won’t destroy it.</p><figure><img alt="A table with wrapped gifts, balloons and a cake. A banner above reads “Happy Birthday.”" src="https://cdn-images-1.medium.com/max/1024/1*iBWq3t84Zf2OuUz5tpdizQ.jpeg" /><figcaption>Sept 15, 2019: Tina came for coffee. Kids had swimming lessons then went for ice cream. Prepared for tomorrow’s birthday party. The big present is from Grandma.</figcaption></figure><h4>Get reminders</h4><p>Emails from Trailmix also function as a reminder to write journal entries. As a bonus, they also send out the text and photo from a previous, randomly selected entry, giving you something to reminisce about and maybe a realization about how your life has developed in recent times.</p><p>But of course, most apps can also send you notification reminders, and if you’d rather journal on paper you could set an alarm for “journal time.”</p><p>I started my current streak when I switched to journaling in an app called “Daylio.” I’m certainly not the only Medium blogger who enjoys Daylio, and there is even a subreddit dedicated to it.</p><figure><img alt="A grown-up and a child riding on horses through some woods." src="https://cdn-images-1.medium.com/max/1024/1*PEuQfo9KxJ32HOp-v1oQSA.jpeg" /><figcaption>April 2, 2019: Took the boys horseback riding. Visited the same restaurant as yesterday, and retrieved a toy that the kids left behind.</figcaption></figure><h4>A personal record is more than worth the time you put in</h4><p>Daylio has some advantages over Trailmix, including the option to track your mood and activities. It also allows you to make multiple entries in a day. Daylio recently added the option to include a photo with your entry.</p><p>Using the mood tracker gives a nice chart of your overall mental state and the activity tracker allows you to see daily or weekly streaks in other habits. For me though, the most important thing is having somewhere to record and revisit the adventures and misadventures of our growing family.</p><p>My kids will never be this age again. We’ll all be lucky to get more than 29,000 days in our lives. It’s wonderful to have some notes to help you revisit some of the good and challenging times along the way. Getting to look back on what happened one or two years ago in the life of a young child is quite priceless already. To borrow the name of one of my favourite parenting podcasts, for our family this is “The Longest Shortest Time” and it will never repeat.</p><p>In terms of personal development, being able to look back at what you were doing a year ago (or longer) helps you to gain perspective on how far you’ve come. Penn Jillette, of the famous magician duo “Penn &amp; Teller” is an advocate of daily journaling. Part of his daily routine is to look back at what he was doing one year, 10 years and 20 years ago. I would love to have that ability too.</p><figure><img alt="A cat looking lazy with its head rolled upside-down, lying on a chair." src="https://cdn-images-1.medium.com/max/1024/1*uylwg938B-uQBOb90DNMtw.jpeg" /><figcaption>October 12, 2019: Lazy day. In the evening we took the kids to see an animated projection on a nearby building. They were more impressed by seeing the full moon and the big dipper.</figcaption></figure><h4>Work backwards when you get behind</h4><p>There have been times when I’ve fallen behind in my practice. When this happens, I try to start writing early in the evening, before I get too tired. When I feel like I can’t remember many details of previous days, I start with the current day and work backwards.</p><p>This has quite easily allowed me to fill in blanks when I’ve gotten behind. So far I’ve managed to avoid getting behind by more than five days at a stretch. The biggest reason for this is, now that I’m used to regular journaling, I really miss it when I don’t find the time.</p><figure><img alt="Two children sitting by a river near to two bridges." src="https://cdn-images-1.medium.com/max/1024/1*NuNHZwMVCp5iFCdMvT7HMg.jpeg" /><figcaption>March 27, 2021: Got up early and made bread with the kids. Went for a walk along the river.</figcaption></figure><p>I hope this helps you in creating your own personal record, whether for posterity, to help trigger memories or just to give you a good place to rant.</p><h4>References</h4><ul><li><a href="https://medium.com/@helpfuldad/what-i-learned-about-myself-after-1-000-days-of-using-the-daylio-micro-diary-mood-tracker-app-bd10cd84580f">What I learned about myself after 1,000 days of using the DAYLIO Micro Diary Mood Tracker app</a></li><li><a href="https://www.trailmix.life/">Trailmix</a></li><li><a href="https://constancevork.com/2020/02/06/a-perspective-on-journaling-from-penn-jillette/">A perspective on journaling from Penn Jillette - Constance Vork</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64e4e6614849" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tools for New Developers — Part 4]]></title>
            <link>https://medium.com/star-gazers/tools-for-new-developers-part-4-f23561ba0bfe?source=rss-aa921bd25d8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f23561ba0bfe</guid>
            <category><![CDATA[tools-and-resources]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[career-change]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[beginner-coding]]></category>
            <dc:creator><![CDATA[Stuart McLean]]></dc:creator>
            <pubDate>Fri, 30 Apr 2021 21:25:19 GMT</pubDate>
            <atom:updated>2021-05-01T09:50:51.501Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tools for New Developers-Part 4</h3><p>A broad range of knowledge will help you shine as a team member.</p><p>Part 1 of this series is <a href="https://stuart-mclean.medium.com/tools-for-new-developers-part-1-266616f4dc8f">here</a>. Part 2 is <a href="https://medium.com/star-gazers/tools-for-new-developers-part-2-503e1d2bdcb9">here</a>. Part 3 is <a href="https://medium.com/star-gazers/tools-for-new-developers-part-3-8cde56206b75">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KU4Mk9hIML4VY7wp" /><figcaption>Photo by <a href="https://unsplash.com/@carlevarino?utm_source=medium&amp;utm_medium=referral">Cesar Carlevarino Aragon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Very few software developers work completely alone. Most spend their time working as part of a team. Even if you’re a freelancer, you will need to work with clients. Understanding the software development industry’s standards and methodologies will help you to collaborate comfortably with your fellow developers and clients alike.</p><p>Here are some tools that will help you to become a better and more useful team player.</p><h4>Tool 14: Terminal Editors</h4><figure><img alt="A man waiting in an airport terminal" src="https://cdn-images-1.medium.com/max/1024/0*O8LG-aDb3DXHm_8H" /><figcaption>Photo by <a href="https://unsplash.com/@marcolopez95?utm_source=medium&amp;utm_medium=referral">Marco López</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In <a href="https://medium.com/star-gazers/tools-for-new-developers-part-3-8cde56206b75">part 3</a> of this series, I wrote about how important it is to be familiar with the command line. Here’s another good reason why.</p><p>Even in an increasingly containerised and serverless world, at some point, you will probably need to remotely access a machine via SSH (Secure Shell Protocol). This is by far the easiest way to connect to and perform commands on an external server. While there you might very well need to edit configuration files or code directly. If you’re used to clicking around files with your mouse, you’re in for a surprise.</p><p>Of course, it is possible to download files, modify them and upload them again, but that usually takes a lot more time than editing them in place.</p><p>That’s what terminal editors were made for. Tracing their roots to the early days of mainframe computing, editors like Vim and Emacs provide a multitude of ways to efficiently navigate and edit text files using only your keyboard.</p><p>Overall, it’s a great idea to learn a terminal editor. Believe it or not, once you get familiar with one of these you might want to use it for everything. Honestly, the first time someone showed me how Vim key commands worked, I felt like it made things harder than they needed to be. Now that I’m familiar with them I’d rather not write anything without them.</p><p><a href="https://spin.atomicobject.com/2016/04/19/vim-commands-cheat-sheet/">The 30 Basic Vim Commands You&#39;ll Use Every Day</a></p><p>With the right configuration and plugins, Vim or Emacs can do most things that expensive IDE (Integrated Development Environment) apps do. They’re free, and they’re available in almost any environment you find yourself in, be it Windows, Mac, or even a remote Linux server sitting on the other side of the world.</p><p>Familiarity with a terminal app provides freedom and power to write and edit high-quality code fast. And if you still want to use an IDE, all the major players have plugins that allow you to navigate your files using Vim or Emacs commands.</p><p>And, of course, you’ll look like a cool hacker as you seamlessly reformat a document without touching your mouse.</p><h4>Tool 15: Debuggers</h4><figure><img alt="A page from the Harvard Mark II electromechanical computer’s log, featuring a dead moth that was removed from the device." src="https://cdn-images-1.medium.com/max/740/1*80Mn0HKZwsk17cIUHKG5YA.jpeg" /><figcaption>The first software bug, found in 1947. By Courtesy of the Naval Surface Warfare Center, Dahlgren, VA., 1988. — U.S. Naval Historical Center Online Library — <a href="https://en.wikipedia.org/wiki/Software_bug">Wikipedia article</a></figcaption></figure><p>We’ve all written temporary lines of code that print the current state of variables, helping us to figure out what’s happening inside our attempts at logic.</p><p>Wouldn’t it speed things up if there was a way to get your program to pause in the middle of execution? Then you could poke around inside, see what each variable is set to at different times and even try calling functions directly.</p><p>Fortunately, we’re not the first people to think of that. Debuggers can provide a huge productivity boost to developers. And understanding just a few commands will give you a solid familiarity with most debuggers.</p><p><a href="https://www.cprogramming.com/gdb.html">GDB, The GNU Debugger, By Example - Cprogramming.com</a></p><p>Many IDEs have built-in debuggers, where you can place a breakpoint with a single click in the margin. When you run the program in debug mode it will pause right where you want it to stop, showing you a nice GUI (Graphical User Interface) with a list of the currently available variables and their values.</p><p>Some languages have special commands, supported natively or through plugins, that can be inserted into the code. For example debugger in javascript or byebug in ruby.</p><p>Learning to step around and into functions allows you to dig deep into the code and libraries you’re working with and figure out where errors are occurring.</p><p>Save yourself time and headaches by getting comfortable with a debugger.</p><h4>Tool 16: Markdown (MD)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jvr97w8bLWoXy0tF" /><figcaption>Photo by <a href="https://unsplash.com/@richygreat?utm_source=medium&amp;utm_medium=referral">Richy Great</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is probably one of the easiest items on this list and it comes in handy for me almost every day. Markdown is a standardised form of “text markup. ” This means that adding special characters such as ‘#’, ‘*’ and sets of brackets to plain text modifies its appearance, easily creating things like headers, weblinks and basic text styling such as bold type and bullet points.</p><p><a href="https://www.markdownguide.org/basic-syntax/">Basic Syntax | Markdown Guide</a></p><p>Joplin, mentioned in <a href="https://medium.com/star-gazers/tools-for-new-developers-part-1-266616f4dc8f">part 1</a> of this series, allows users to write in Markdown, making note styling easy. The <a href="https://gist.github.com/stuartmclean/b1d1c41266e2b68299f81bf499e7d2b0">gist</a> that I’ve been writing notes for this article on is also written in Markdown. Github “README.md” files (the quick-start guides you see on the front pages of git repositories) are also written in Markdown, as are github wikis. Another popular wiki tool, Atlassian’s “Confluence” takes Markdown as input (although unfortunately, you can’t yet edit Markdown in Confluence).</p><p>In short, Markdown is very useful for developers. It saves you time and makes your documentation look good.</p><p>Once you get used to writing documentation like this, you’ll never want to go without it. It speeds up your note-taking and makes your notes easily presentable and shareable with others.</p><p>The best part is that you can learn most of the basics of Markdown in about five minutes, and with a little practice, using it will come naturally.</p><h4>Tool 17: Tools for Project Management Processes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IBtXry9lhWzRwPCd" /><figcaption>Photo by <a href="https://unsplash.com/@myleon?utm_source=medium&amp;utm_medium=referral">Leon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Some might say I’ve saved the most important tools for last. When good developers work together, software can be built faster, run more reliably and be easier to understand.</p><p>When not managed properly, team-developed software projects can also become a horrible, intractable, unmodifiable mess.</p><p>Naturally, there has been a lot of well-funded research to try and figure out how developers, project managers, designers and end clients can work well together in creating and modifying complicated software.</p><p>Here are a few concepts that it’s important to know about.</p><p><strong>Tickets:</strong> a way of keeping track of a unit of work that is still to do, in progress or done. Large and complicated tickets are often broken down into a set of sub-tasks, each of which is also considered a ticket. These are often used in…</p><p><strong>Kanban:</strong> a system developed by Toyota for <a href="https://en.wikipedia.org/wiki/Lean_manufacturing">lean manufacturing</a> and just-in-time production on their assembly lines. This concept is frequently used by software development teams.</p><p><a href="https://en.wikipedia.org/wiki/Kanban">Kanban - Wikipedia</a></p><p>Kanban is a “pull” approach to work. Developers assign themselves to the first available task (usually prioritised by a manager or the team members themselves) and work on it until it’s finished.</p><p>The results of that task are then pushed to a “waiting” position where another team member can pull it to complete the next part of the work, such as reviewing or testing code.</p><p>This is usually tracked by moving tickets to separate “lanes” (kind of like spreadsheet columns) on a physical or online board. These boards also give an at-a-glance overview of the progress of the whole project that a team is working on.</p><p>There are many apps that make it easy to set up a Kanban board to organise tasks for individuals and teams. Some currently popular examples are <a href="https://kanbantool.com/online-kanban-board">kanban-tool</a> <a href="https://www.atlassian.com/software/jira">Jira</a>, <a href="https://asana.com/">Asana</a> and <a href="https://trello.com/">Trello</a>.</p><p><strong>Scrum:</strong> a methodology that wraps the kanban “task pulling” approach into “sprints.” At the beginning of each sprint a team commits to completing a certain amount of work (a set of tickets) within a period of time. Sprints typically last two weeks.</p><p><a href="https://www.scrum.org/resources/what-is-scrum">What is Scrum?</a></p><p>At the end of the sprint, the team presents the results of their work, does a retrospective about what went right and wrong and plans the next sprint. Personally, retrospectives are my favourite kind of meeting as they allow opportunities for a team to sort out productivity issues and continually improve the way they work together.</p><p>Familiarity with these concepts and the tools that facilitate them will improve your chances when job hunting. Once you’ve got your head around how they work, don’t be afraid to put them on your CV and mention them in interviews when it feels appropriate.</p><p>The world needs more developers. With the right toolset, it’s possible to become a productive professional developer through a will to learn and the desire to keep trying new strategies and asking questions until a problem is solved.</p><p>I hope you’ve found some useful tools and tips from this series that can aid you in your work (or play) as a software developer. I’m looking forward to seeing what you create and reading blog posts you write to share your own experiences with me and the next generation of developers.</p><p>Now go write some software that’s cool and makes the world a better place.</p><p>You can handle it. :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f23561ba0bfe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/star-gazers/tools-for-new-developers-part-4-f23561ba0bfe">Tools for New Developers — Part 4</a> was originally published in <a href="https://medium.com/star-gazers">Star Gazers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tools for New Developers — Part 3]]></title>
            <link>https://medium.com/star-gazers/tools-for-new-developers-part-3-8cde56206b75?source=rss-aa921bd25d8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cde56206b75</guid>
            <category><![CDATA[beginner-coding]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[career-change]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[tools-and-resources]]></category>
            <dc:creator><![CDATA[Stuart McLean]]></dc:creator>
            <pubDate>Wed, 07 Apr 2021 10:16:46 GMT</pubDate>
            <atom:updated>2021-05-01T09:53:03.517Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tools for New Developers-Part 3</h3><p>“First we shape our tools, thereafter they shape us” ~ Marshall McLuhan</p><p>Part 1 of this series is <a href="https://stuart-mclean.medium.com/tools-for-new-developers-part-1-266616f4dc8f">here</a>. Part 2 is <a href="https://medium.com/star-gazers/tools-for-new-developers-part-2-503e1d2bdcb9">here</a>.</p><figure><img alt="Assorted Color Paint Brush and Drawing Tool Set" src="https://cdn-images-1.medium.com/max/1024/1*tq31stJnoqNkvLdOfFafMw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@cottonbro?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">cottonbro</a> from <a href="https://www.pexels.com/photo/assorted-color-paint-brush-set-3777876/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Compared to many other fields, software development is a new discipline. Still, brilliant developers have spent years working on our field’s biggest challenges and have often created free tools to solve them. One of the benefits of working with software is that we can build on top of others’ hard-won wisdom and life’s work without having to understand all of it.</p><p>Here are some tools that speed up the way we write, edit and debug code.</p><h4>Tool 10: Version Control</h4><figure><img alt="Woman using a laptop adorned with stickers of variation on the github logo." src="https://cdn-images-1.medium.com/max/1024/1*X74fUE3-ZFKPwzY-nosnuw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@divinetechygirl?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Christina Morillo</a> from <a href="https://www.pexels.com/photo/woman-using-macbook-1181288/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Have you ever found yourself saving many versions of the same document or even folders of documents, adding a suffix like “version_2,” “final” and even “final_final_final”?</p><p>Have you ever forgotten which copy held an important bit of information that was removed in later iterations?</p><p>Did you ever make changes to a shared document at the same time as someone else and then have trouble merging the changes?</p><p>Do you worry about losing your work if a hard drive fails?</p><p>If you answered “yes” to any of these questions, then version control is for you. Honestly, I think it’s for everyone, but it’s especially useful for software developers.</p><p>As developers, we often work collaboratively with many other people on large, complex projects. Sometimes we create and release multiple versions of a piece of software in a single day.</p><p>The centre-point of most modern software collaboration and release tracking is a technology called “<a href="https://git-scm.com/book/en/v2/Getting-Started-About-Version-Control">git</a>.”</p><p>If you’re only going to take away one piece of advice from this article, do yourself and your soon-to-be-flourishing career a favour and <a href="https://git-scm.com/book/en/v2/Git-Basics-Getting-a-Git-Repository">read at least chapter 2</a> of the free “git book.” A solid understanding of this technology will make you much more attractive to potential employers.</p><p><a href="https://git-scm.com/book/en/v2/Git-Basics-Getting-a-Git-Repository">Git - Getting a Git Repository</a></p><p>The next step is to create your own <a href="https://github.com/">github</a> account and get used to pushing your work there (I recommend creating private repositories at first).</p><p>Then:</p><pre>git add .<br>git commit -m &quot;improvements to my amazing new feature&quot;<br>git push</pre><p>As important as all the other advantages mentioned here, github is the world’s top site for developers collaborating on open-source software.</p><p>Contributing to well-regarded and frequently-used open-source software is one of the best things you can have on your resumé.</p><h4>Tool 11: A Framework (or a few)</h4><figure><img alt="Stainless steel framework of a modern bridge on a partly cloudy day" src="https://cdn-images-1.medium.com/max/1024/1*JZ9qyUx-CAjXotNIMFuScA.jpeg" /><figcaption>Frameworks provide the structure — fill in the blanks with your logic. Photo by <a href="https://www.pexels.com/@orlovamaria?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Maria Orlova</a> from <a href="https://www.pexels.com/photo/stainless-steel-framework-of-modern-bridge-in-city-on-partly-cloudy-day-4946920/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>How do experienced developers create great software fast? They certainly don’t do everything themselves. They stand on the shoulders of giants, building on cleverly written and (hopefully) secure code.</p><p>At most software companies, developers make frequent use of many externally-developed “software libraries.” Developers use software libraries to take care of common but complex tasks that they don’t have time to properly implement from scratch.</p><p>A framework is like a set of libraries that all work together to provide the tools needed for building a complete application. This usually includes elements such as:</p><ul><li>database connection and query helpers</li><li>user interface builders</li><li>logging and metrics handling</li><li>a “developer mode” that speeds up debugging</li></ul><p>You’ll have a better chance of being hired by a software company if you have experience with a framework that they use.</p><p>For instance, if you’re a python developer you should probably be familiar with the <a href="https://www.djangoproject.com/start/">Django framework</a>. If you’re a frontend developer you should dive deep into at least one of the top javascript frameworks (at the moment, <a href="https://angularjs.org/">angular</a>, <a href="https://reactjs.org/">react</a>, <a href="https://emberjs.com/">ember</a> and <a href="https://vuejs.org/">vue</a> but this list could very well change next week).</p><p>Some people might tell you that libraries and frameworks aren’t always reliable and that it’s better to build everything yourself. Keep in mind that (unless you’re writing machine code) the very programming languages we use are a kind of framework built on top of lower-level software.</p><p>All around the world, developers are constantly relying on the efforts of those who got here before us, looked around and said something like “I think what this place needs is an easier way to serve HTML.”</p><h4>Tool 12: An Integrated Development Environment (IDE)</h4><figure><img alt="A software developer’s computer screens showing the Visual Studio Code Integrated Development app." src="https://cdn-images-1.medium.com/max/1024/0*AUOrFCNCOUaJ_6Qq" /><figcaption>Photo by <a href="https://unsplash.com/@ffstop?utm_source=medium&amp;utm_medium=referral">Fotis Fotopoulos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I mentioned in part 1 of this series how important it is to have a good text editor to work in. IDEs are text editors taken to the next level, adding in tools for common developer activities such as:</p><ul><li>working seamlessly with libraries and databases</li><li>running tests</li><li>deploying code</li></ul><p>…all in a single application.</p><p>You don’t strictly need to use an IDE for development, and some great developers don’t. But at least as many great developers <em>do</em> use IDEs as huge productivity boosters that can even aid in collaboration.</p><p>The world’s most popular IDE at the time of writing is Visual Studio Code. It’s a free application developed by Microsoft but much of its power comes from open-source plugins developed by 3rd-party developers.</p><p><a href="https://code.visualstudio.com/">Visual Studio Code - Build what comes next</a></p><p>There are many other language-specific IDEs like <a href="https://developer.apple.com/xcode/">Xcode</a> for native Mac and iOS apps and <a href="https://www.eclipse.org/ide/">Eclipse</a> for Java (although it works for many other languages too). <a href="https://www.jetbrains.com/">JetBrains</a> has an IDE for almost every popular programming language, including <a href="https://kotlinlang.org/">Kotlin</a>, a language created by JetBrains developers. Jetbrains’ “<a href="https://www.jetbrains.com/idea/download/">IntelliJ IDEA Ultimate</a>” is relatively expensive, but by adding plugins you can make it work with just about every programming language out there.</p><p>A well-configured IDE will allow you to navigate a complex codebase with ease, finding the definition and usages of functions and classes. They’re also great at doing refactoring, allowing you to quickly and reliably rename files and functions without breaking your code.</p><p>Becoming familiar with the features of your chosen IDE (and its keyboard shortcuts) can significantly speed up your development process. Find one that fits your language, your style and your budget, then use it to streamline your workflow.</p><h4>Tool 13: A Terminal (shell) Application</h4><figure><img alt="White HTML text on a black background blurred as if rushing away from the camera." src="https://cdn-images-1.medium.com/max/1024/1*saACMkg4lU6d6DNMDunEFQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@negativespace">Negative Space</a> on <a href="https://www.pexels.com/">Pexels</a></figcaption></figure><p>Terminal applications are based on the <a href="https://en.wikipedia.org/wiki/Unix_shell">Unix shell</a>, one of the oldest ways of interacting with a computer. These use plain text input and output to interact with your computer, its programs and the wider internet as well.</p><p>Using the CLI (Command-LIne) might seem limited, daunting and even scary at first, but put a little time into becoming comfortable working in this environment and you’ll find yourself able to accomplish some amazing things in a few keystrokes.</p><p>Even better, you’ll start taking advantage of the full power of your computer without being limited by a GUI (Graphical User Interface). For example, while there are GUI apps that wrap “git” calls, some of the most powerful functions are only available from the command-line.</p><p>Macs come with an app called Terminal, but <a href="https://iterm2.com/">iTerm2</a> is better (and free). Windows users can install <a href="https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/install/installing-windows-powershell">PowerShell</a>, and I highly recommend adding the <a href="https://itsfoss.com/install-bash-on-windows/">Linux bash shell</a>.</p><p>Most IDEs also have a terminal window built-in.</p><p><a href="https://medium.com/@jasonrigden/a-brief-tutorial-of-the-absolute-basics-of-bash-9a379c49f7a8">A Brief Tutorial of the Absolute Basics of Bash</a></p><p>Once you get used to a few commands you can easily write your own shell scripts, smoothly sending data from one utility to another and automating repetitive tasks.</p><p>Your terminal also provides many ways of customising your own workflow, including printing useful information in the command-line prompt.</p><p>And you can still become a brilliant programmer if you prefer your terminal to print black text on a white background. I promise I won’t judge you.</p><p>As we build exciting and useful software, let’s remember that lots of people have faced the same challenges we’re facing. Many of these challenges can now be easily solved with a well-developed toolset that’s available for free.</p><p>If you find these toolsets lacking in any way, please consider contributing to open-source libraries.</p><p>Your own contributions could end up running on millions of computers around the world, making life a bit easier for millions of people. Let’s go make the world a better place with our code.</p><p>A summary of these points (and more) is available in a “github gist” <a href="https://gist.github.com/stuartmclean/b1d1c41266e2b68299f81bf499e7d2b0">here</a>.</p><p>Part 4 of this article is <a href="https://medium.com/star-gazers/tools-for-new-developers-part-4-f23561ba0bfe">here</a>.</p><p>You can handle it. :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cde56206b75" width="1" height="1" alt=""><hr><p><a href="https://medium.com/star-gazers/tools-for-new-developers-part-3-8cde56206b75">Tools for New Developers — Part 3</a> was originally published in <a href="https://medium.com/star-gazers">Star Gazers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>