<?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 Duncan Lew on Medium]]></title>
        <description><![CDATA[Stories by Duncan Lew on Medium]]></description>
        <link>https://medium.com/@duncanlew?source=rss-da8fe21e0b75------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*METWmTlLFfPCJyHtHRXXrw.jpeg</url>
            <title>Stories by Duncan Lew on Medium</title>
            <link>https://medium.com/@duncanlew?source=rss-da8fe21e0b75------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:11:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@duncanlew/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[From 30 minutes to 90 seconds: Why I switched from Zip to Zstandard]]></title>
            <link>https://duncanlew.medium.com/from-30-minutes-to-90-seconds-why-i-switched-from-zip-to-zstandard-4130efeec002?source=rss-da8fe21e0b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/4130efeec002</guid>
            <dc:creator><![CDATA[Duncan Lew]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 20:17:27 GMT</pubDate>
            <atom:updated>2025-11-23T20:17:27.013Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBrwBd1WXr7coF925Hp1FA.png" /></figure><p>I had a directory containing around 53 GB of pictures that I wanted to transfer more efficiently into cold storage. When I tried to zip this directory on my macOS machine, the progress bar showed me it would take 30 minutes to finish. I still had another directory of 250GB which I also wanted to compress. At this rate, I would be sitting around for hours. Surely there had to be a better way.</p><p>For years, zip has been the default choice for file compression, making it reliable and universally supported. Of course compression technology hasn’t stool still. Enter Zstandard, or std: a modern compression algorithm developed by Facebook and released as open-source in 2016. It delivers comparable or better compression ratios than zip while operating significantly faster. Since its release, it has become integrated into the core architecture of systems everywhere: from Linux kernels to modern web browsers.</p><p>When I switched to zstd for my photo archive, what would have taken hours with zip finished in just a few minutes. In this post, I’ll walk you through how to use zstd to compress directories on macOS, and why it might be worth making it your go-to compression tool.</p><p>Prerequisites:</p><ul><li>Brew</li><li>Basic knowledge of using the Terminal</li></ul><h3>Instructions</h3><h3>Step 1: Install Zstandard</h3><p>Run the following command to install Zstandard</p><pre>brew install zstd</pre><h3>Step 2: Compress with Zstandard</h3><p>We’re going to use the tar command to create a compressed tar archive using Zstandard.</p><p>Let’s say you have a directory called project that you want to compress. The following command will create an archive called project.tar.zst :</p><pre>tar --zstd -cf project.tar.zst project/</pre><p>This creates (-c) a compressed archive file (-f ) named project.tar.zst containing everything in the project/ directory.</p><h3>Step 3: Decompress with Zstandard</h3><p>When you want to extract the contents of your archived file, you can run the following command:</p><pre>tar --zstd -xf project.tar.zst</pre><p>This will extract (-x) the contents from the archived file (-f) into a project/ directory.</p><h3>Timing comparison for 53 GB</h3><p>When using the zip compression on macOS, Finder estimated the process would take around 30 minutes to finish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*wgtHLl_gxZYMAd2ZQUYq1Q.png" /><figcaption>Finder estimating the compression of 53GB file at about 30 minutes</figcaption></figure><p>To measure the timing of Zstandard compression we can prefix the compression command with time .</p><pre>time tar --zstd -cf takeout.tar.zst Takeout/</pre><p>The same directory took 1 minute and 24 seconds to compress:</p><pre>55.02s user 45.62s system 118% cpu 1:24.87 total</pre><p>This is about 20 times faster than zip. I saved myself around 29 minutes. The resulting compressed file was around 52.8 GB, achieving similar compression compared to Zip, but in a fraction of the time.</p><h3>Takeaway</h3><p>Discovering Zstandard as an alternative compression algorithm shows me that modern tools can improve your everyday tasks. What started as a frustrating 30 minutes wait turned into a solution that finished in just over a minute. By leveraging the tar command using the --zstd flag, you can transform a tedious compression task into something quick and efficient. The next time you find yourself watching a progress bar slowly crawl across your screen, remember there might be a better way! Happy compressing! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4130efeec002" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a SpeedtestTracker with Raspberry PI and AWS Lambda]]></title>
            <link>https://duncanlew.medium.com/how-i-built-a-speedtesttracker-with-raspberry-pi-and-aws-lambda-19ccaf60607c?source=rss-da8fe21e0b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/19ccaf60607c</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Duncan Lew]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 21:56:07 GMT</pubDate>
            <atom:updated>2025-02-07T21:56:07.732Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*anJn-gXazaWcvFfEd6Pf8g.png" /></figure><p>Our daily lives, whether we’re gaming, streaming or working from home, revolve around the internet and all the digital services that it provides. A pillar of this connection is the reliability of the download and upload speeds that your ISP can deliver. When you sign up for a service that promises certain speeds, you want to validate that you get what you pay for. This need inspired me to create SpeedtestTracker: a system that performs daily speed tests, stores the result in a database and even sends out an alert via a Telegram bot. This blog post will walk you through the steps I took to bring this idea to life.</p><h3>1. Designing the system</h3><p>SpeedtestTracker is set up as a two part system:</p><ul><li>the client for running speedtests, extracting and saving the results</li><li>the server for processing, storing and sending alerts of the data</li></ul><p>The Raspberry Pi, as the title already reveals, will act as the client and the server will be made of an AWS Lambda function. To streamline the development, I consolidated both the client-side and server-side components into a single TypeScript project. This approach enabled interface sharing, simplifying the communication between the two components.</p><p>The following dependencies played an important role in the implementation:</p><ul><li><a href="https://nodejs.org/en">Node.js v22</a></li><li><a href="https://axios-http.com/docs/intro">Axios</a> for sending data to the server-side</li><li><a href="https://esbuild.github.io/">esbuild</a> for bunding both the client and server separately</li><li><a href="https://github.com/motdotla/dotenv?tab=readme-ov-file#readme">dotenv</a> for loading environment variables</li><li><a href="https://github.com/node-cron/node-cron">node-cron</a> for scheduling daily speedtests on the client</li><li><a href="https://getpino.io/#/">Pino</a> for structured logging</li><li><a href="https://telegraf.js.org/">Telegraf</a> as a library for interacting with Telegram bots</li><li><a href="https://ajv.js.org/">AJV</a> for validating JSON responses from the speedtest cli</li></ul><p>If this sounds like something that you would like to try out or improve, check out the souce code on GitHub [add link here].</p><h3>2. Hardware setup with the Raspberry Pi as the client</h3><p>The backbone of the project starts with the Raspberry Pi. A very small, yet powerful and energy efficient computer that can run speedtests according to a schedule. Running frequent speedtests the whole day could congest your network, so I opted for a daily schedule instead. For my use-case, I don’t need to see deviations in my speed throughout the day. Having my Pi run a speedtest once a day fits my needs to collect data for statistical analysis over time.</p><h4>2.1 Speedtest-cli</h4><p>The Pi is going to run a shell script that executes the <a href="https://www.speedtest.net/apps/cli">Speedtest-cli</a> tool to capture the Internet speed results. Here’s the command it uses:</p><pre>speedtest --format=json</pre><p>To automate the process, I wrote a TypeScript function that executes the shell command with error handling and parsing of the JSON result. Here’s the implementation:</p><pre>export function runSpeedtest(): Promise&lt;any&gt; {<br>  const command = &quot;speedtest --format=json&quot;;<br><br>  return new Promise((resolve, reject) =&gt; {<br>      exec(command, (error, stdout, stderr) =&gt; {<br>        if (error) {<br>          reject(`Error executing command: ${error.message}`);<br>        }<br>        if (stderr) {<br>          reject(`Standard Error: ${stderr}`);<br>        }<br>        try {<br>          const result = JSON.parse(stdout);<br>          resolve(result);<br>        } catch (parseError) {<br>          reject(`Failed to parse JSON output: ${parseError}`);<br>        }<br>      });<br>    });<br>  }</pre><h4>2.2 Sending data to the endpoint</h4><p>After the JSON result is retrieved, we can send this data to an endpoint. This endpoint URL is protected by an API key and triggers an AWS Lambda when it’s called. I’m using the address in the input argument as a location identifier. Here’s the function for sending the data via a POST request:</p><pre>export const saveSpeedTestResult = async (<br>  speedtestResult: SpeedtestResultDto,<br>  url: string,<br>  apiKey: string,<br>  address: string,<br>) =&gt; {<br>  const headers = {<br>    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    &quot;x-api-key&quot;: apiKey,<br>  };<br><br>  const payload: SpeedtestTrackerPayload = {<br>      pk: address,<br>      result: speedtestResult,<br>    };<br>    const response = await axios.post(url, payload, { headers });<br> };</pre><h4>2.3 Scheduling a cron job</h4><p>With these methods in place, we can schedule the speedtest to run once a day at a specific time with node-cron. This is what the cron job looks like:</p><pre>cron.schedule(&quot;0 13 * * *&quot;, async (result) =&gt; {<br>  const url = process.env.URL as string;<br>  const apiKey = process.env.API_KEY as string;<br>  const address = process.env.ADDRESS as string;<br><br>  try {<br>      const speedtestResult = await runSpeedtest();<br>      await saveSpeedTestResult(speedtestResult, url, apiKey, address);<br>    } catch (error) {<br>      logger.error({ error }, &quot;Error in running the cron job&quot;);<br>    }<br>});</pre><h4>2.4 Managing the node process with PM2</h4><p>When running this script on the Raspberry Pi we want to keep the cron job alive. If you start the node process for the cron job via an SSH session, the process will terminate when you terminate the SSH session. This is where PM2 comes in. PM2 is a process manager that can run node processes in the background indefinitely.</p><p>While PM2 can run TypeScript directly, it’s not recommended in production due to inefficiency. To overcome this, we will first transpile TypeScript into JavaScript with esbuild:</p><pre>esbuild lib/speedtest-cli/index.ts --bundle --platform=node --sourcemap --target=node22 --legal-comments=none --outfile=build/speedtest-cli/index.js</pre><p>Run the transpiled JavaScript with PM2:</p><pre>pm2 start build/speedtest-cli/index.js</pre><p>For convenience, these commands can be added to the package.json. As long as your Raspberry Pi remains powered on, this node process will run in the background indefinitely.</p><h3>3. AWS Lambda as the server</h3><p>On the server side, I use an AWS Lambda function to process and store the results. For the infrastructure, project setup and the deployment, I rely on AWS CDK.</p><h4>3.1 AWS CDK and project setup</h4><p>The AWS Cloud Development Kit, or AWS CDK, allows me to define the cloud infrastructure using a familiar programming language instead of managing a big YAML or JSON file that is required by AWS CloudFormation. In my situation I’m using TypeScript to define my resources.</p><p>To initialize a CDK project, I ran the following command in my SpeedtestTracker project:</p><pre>cdk init app --language typescript</pre><p>Next, I installed the esbuild dependency that will be used by the CDK to compile my TypeScript code:</p><pre>npm install --save-dev esbuild</pre><p>Inside the lib directory, CDK generates a file called speedtest-tracker-stack.ts . This acts as the scaffolding where you can define your resources.</p><h4>3.2 Adding an AWS Lambda resource</h4><p>For my Lambda resource I added the following code:</p><pre>const fn = new NodejsFunction(this, &quot;SaveSpeedtestFunction&quot;, {<br>  entry: path.resolve(__dirname, &quot;lambda-handler/index.ts&quot;),<br>  runtime: lambda.Runtime.NODEJS_LATEST,<br>  handler: &quot;handler&quot;,<br>  bundling: {<br>    sourceMap: true,<br>  },<br>  environment: {<br>    NODE_OPTIONS: &quot;--enable-source-maps&quot;,<br>    BOT_TOKEN: process.env.BOT_TOKEN!,<br>    CHAT_ID: process.env.CHAT_ID!,<br>  },<br>});</pre><p>The lambda handler according to this snippet will be located in the lambda-handler directory and I’ve included the required environment variables that should be included for the lambda to run correctly.</p><h4>3.3 Adding a DynamoDB resource for data storage</h4><p>To store the results, I’ve set up a DynamoDB table. The following code snippet creates a table with the partitionKey and sortKey and grants read/write rights to the Lambda function:</p><pre>const table = new dynamodb.TableV2(this, &quot;Table&quot;, {<br>  partitionKey: { name: &quot;pk&quot;, type: dynamodb.AttributeType.STRING },<br>  sortKey: { name: &quot;epochTime&quot;, type: dynamodb.AttributeType.NUMBER },<br>  tableName: &quot;speedtest-tracker&quot;,<br>});<br>table.grantReadWriteData(fn);</pre><h4>3.4 Creating an securing the API Gateway</h4><p>An API Gateway serves as the interface between the client and the server. To secure the API, I added an API key and linked it to a usage plan. The usage plan limits request rates, ensuring that the API stays performant. Here’s the code:</p><pre>const api = new apigw.LambdaRestApi(this, `ApiGwEndpoint`, {<br>  handler: fn,<br>  restApiName: `SpeedtestTrackerApi`,<br>  deployOptions: {<br>    stageName: &quot;prod&quot;,<br>  },<br>  defaultMethodOptions: {<br>    apiKeyRequired: true,<br>  },<br>});<br><br>const plan = api.addUsagePlan(&quot;UsagePlan&quot;, {<br>  name: &quot;SpeedtestTrackerUsagePlan&quot;,<br>  throttle: {<br>    rateLimit: 10,<br>    burstLimit: 2,<br>  },<br>});<br><br>const apiKey = api.addApiKey(&quot;ApiKey&quot;, {<br>  apiKeyName: &quot;SpeedtestTrackerApiKey&quot;,<br>});<br>plan.addApiKey(apiKey);<br>plan.addApiStage({<br>  stage: api.deploymentStage,<br>});</pre><h4>3.5 Deploy the defined resources</h4><p>With all the resources defined, they can be synthesized and deployed with the following commands:</p><pre>cdk synth<br>cdk deploy</pre><h4>3.6 Lambda handler</h4><p>The lambda handler will act as the server-side part, that will process the incoming speedtest result from the Raspberry Pi, validates it using the AJV schema validation and then stores it in DynamoDB. At the end we will also send a success/failure message via Telegram using Telegraf.</p><p>The core lambda handler looks like this:</p><pre>export const handler: APIGatewayProxyHandler = async (<br>  event: APIGatewayProxyEvent,<br>  context: Context,<br>): Promise&lt;APIGatewayProxyResult&gt; =&gt; {<br>  try {<br>    withRequest(event, context);<br>    logger.info({ data: event }, &quot;Received event&quot;);<br><br>    const payload = extractPayload(event);<br>    const { pk: primaryKey, result: speedtestResultDto } = payload;<br>    const speedtestResult = getSpeedtestResult(speedtestResultDto);<br>    const telegramMessage = constructSuccessMessage(<br>      primaryKey,<br>      speedtestResult,<br>    );<br>    const putResponse = await putItem(primaryKey, speedtestResult);<br>    await sendTelegramMessage(telegramMessage);<br>    return successResponse(JSON.stringify(putResponse, null, 2));<br>  } catch (error) {<br>    logger.error(&quot;Error in the lambda handler&quot;);<br>    let statusCode: number;<br>    let message: string;<br>    switch (true) {<br>      case error instanceof SpeedtestTrackerValidationError:<br>        statusCode = 400;<br>        message = (error as SpeedtestTrackerValidationError).message;<br>        break;<br>      case error instanceof SyntaxError:<br>        statusCode = 400;<br>        message = (error as SyntaxError).message;<br>        break;<br>      default:<br>        statusCode = 500;<br>        message = `Unknown error occurred: ${error}`;<br>        break;<br>    }<br>    const stringifiedMessage = JSON.stringify(message, null, 2);<br>    const telegramMessage = constructFailureMessage(stringifiedMessage);<br>    await sendTelegramMessage(telegramMessage);<br>    return errorResponse(statusCode, stringifiedMessage);<br>  }<br>};</pre><h4>3.7 JSON validation</h4><p>In the lambda handler, we’re using an extractPayload function that parses and validates the incoming JSON against a predefined schema. If there are missing fields in the payload, an error SpeedtestTrackerValidationError will be thrown to prevent incorrect data from being stored into the DynamoDB.</p><pre>extractPayload = (event: APIGatewayProxyEvent) =&gt; {<br>  if (event.body === null) {<br>    throw new SpeedtestTrackerValidationError(&quot;Payload may not be empty&quot;);<br>  }<br><br>  const parsedBody = JSON.parse(event.body);<br>  const isValid = validate(parsedBody)<br>  if (!isValid) {<br>    throw new SpeedtestTrackerValidationError(`JSON validation failed with error: ${JSON.stringify(validate.errors)}`);<br>  }<br>  return parsedBody as SpeedtestTrackerPayload;<br>}</pre><p>The setup for the validate function can be found over here in <a href="https://github.com/duncanlew/SpeedtestTracker/blob/main/lib/lambda-handler/schema.ts">the project</a>.</p><h4>3.8 Save result in DynamoDB</h4><p>The lambda handler will persist the speedtest result in DynamoDB using the putItem utility function. It will structure the speedtest result for querying and analysis. Each entry requires a primary key (pk) and a sort key. The pk will store the address of the home for which I’m tracking the speedtest results. The sort key will store the epoch time in seconds. Using this composite key of pk and sort key, you will be able query for all the speedtest results of a range.</p><pre>export const putItem = async (<br>  primaryKey: string,<br>  speedtestResult: SpeedtestResult,<br>) =&gt; {<br>  const now = new Date();<br><br>  const command = new PutCommand({<br>      TableName: TABLE_NAME,<br>      Item: {<br>        pk: primaryKey,<br>        epochTime: toEpochSeconds(now.getTime()),<br>        date: now.toISOString(),<br>        payload: speedtestResult,<br>        downloadMbps: speedtestResult.downloadMbps,<br>        uploadMbps: speedtestResult.uploadMbps,<br>        pingMs: speedtestResult.pingMs,<br>      },<br>    });<br>    return await docClient.send(command);<br>};</pre><h4>3.9 Send Telegram message</h4><p>For the telegram integration, I made use of the Telegraf dependency which requires two variables:</p><ul><li>CHAT_ID</li><li>BOT_TOKEN</li></ul><p>To get the BOT_TOKEN, you will first have to create a specialized chatbot via the Telegram app. During the creation of your chatbot, a token will unique and private token will be generated. The CHAT_ID is the specific chat session for which you want the chatbot to send a message.</p><p>These env variables will be handled in the .env file which can be loaded with the dotenv dependency.</p><pre>import { Telegraf } from &quot;telegraf&quot;;<br>import * as dotenv from &quot;dotenv&quot;;<br><br>const chatId = process.env.CHAT_ID!;<br>const botToken = process.env.BOT_TOKEN!;<br>const bot = new Telegraf(botToken);<br><br>export const sendTelegramMessage = async (message: string): Promise&lt;void&gt; =&gt; {<br>  await bot.telegram.sendMessage(chatId, message);<br>};</pre><h3>4. Takeaway</h3><p>Building a SpeedtestTracker with a Raspberry Pi demonstrates how to turn a simple IoT device into a monitoring tool for your internet performance. We also leveraged AWS native tools like AWS CDK, AWS Lambda, and DynamoDB to process, store, and send alerts for the daily speedtest results. This project serves as an important learning tool to apply your knowledge of how to develop and utilize both cloud and hardware resources to achieve your goal. There are many small but valuable challenges that you’ll encounter like setting up deployments, validating JSON for data storage and configuring Telegram alerts. No matter whether you’re looking into learning about network monitoring or wanting to expand your skills in serverless architecture, this project is an ideal starting point. Happy coding! 🚀</p><p>The complete source code can be found in this <a href="https://github.com/duncanlew/SpeedtestTracker">GitHub project</a>.</p><p>If the content was helpful, feel free to support me <a href="https://www.buymeacoffee.com/duncanlew">here</a>:</p><figure><a href="https://www.buymeacoffee.com/duncanlew"><img alt="" src="https://cdn-images-1.medium.com/max/170/0*x2VPAGV3dIIOo_1P.png" /></a><figcaption>Buy me a coffee link for Duncan Lew</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19ccaf60607c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Parsing CSV Files in Go]]></title>
            <link>https://duncanlew.medium.com/a-guide-to-parsing-csv-files-in-go-992b1636f139?source=rss-da8fe21e0b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/992b1636f139</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[go-language]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[csv-file]]></category>
            <dc:creator><![CDATA[Duncan Lew]]></dc:creator>
            <pubDate>Tue, 02 Apr 2024 20:17:40 GMT</pubDate>
            <atom:updated>2024-04-02T20:22:42.035Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nfnRZG6kJwH9LKJIqsE7Yw.png" /></figure><p>Among all the programming languages available, Go, or Golang, has become more popular in the past years. In 2023 Go re-entered the top 10 spot of most popular languages, according to <a href="https://www.infoworld.com/article/3689949/golang-returns-to-the-top-10.html">InfoWorld</a>. This language has garnered so much clout because of its simplicity, efficiency and ability to compile directly to machine code, offering many speed benefits.</p><p>As someone new to Go, I would like to dive deeper into this language to find out its potential. The best way to learn something new is by doing it. So that is why I started on a project to not only hone my Go skills, but also solve a common task: CSV parsing and data manipulation. Through this blog post I will illustrate how to parse a CSV file containing rows of articles. These articles need to be filtered based on a property and then written to a new CSV file. The accompanying source code to this project can be found on <a href="https://github.com/duncanlew/demo-go-csv-parser/tree/main">GitHub</a>.</p><h4>Prerequisites</h4><p>To get started with the project, you will need the following:</p><ul><li><a href="https://go.dev/doc/install">Go version 1.22.1</a> or later</li><li>IDE of choice (e.g. <a href="https://code.visualstudio.com/">Visual Studio Code</a>)</li></ul><h3>1. Initialize the project</h3><p>The first step in creating our Go project involves setting up a new directory called `demo-go-csv-parser`. Then navigate into this directory.</p><pre>mkdir demo-go-csv-parser<br>cd demo-go-csv-parser</pre><p>The next step is to initialize a Go module called demo-go-csv-parser</p><pre>go mod init demo-go-csv-parser</pre><p>A go.mod file will be created inside your directory. This module file is used to organize and manage dependencies, similar to the package.json of the Node.js ecosystem.</p><h3>2. Install the CSV dependency</h3><p>The dependency that we’re going to use is called <a href="https://github.com/gocarina/gocsv">gocsv</a>. This package provides a variety of built-in functions for parsing CSVs using Go structs. To include the dependency in your project, run the following command:</p><pre>go get github.com/gocarina/gocsv</pre><h3>3. Write the code</h3><p>It’s time to dive into the coding aspect of the project to get a taste of how the Go programming language works. To maintain clarity, we’re going to break down the coding process into the following sections:</p><ul><li>Create main file</li><li>CSV file setup</li><li>Read file</li><li>Filter articles</li><li>Write file</li></ul><p>By decomposing the whole project into bite-size chunks, we can tackle each part with more attention.</p><h4><strong>Create main file</strong></h4><p>In the root folder of the demo-go-csv-parser project, create a file called main.go.<br>Populate the file with the following:</p><pre>package main<br><br>import (<br> &quot;github.com/gocarina/gocsv&quot;<br> &quot;os&quot;<br>)</pre><p>The first line indicates the package name for the file. Every Go file needs to start with a package declaration. The second part of the file consists of the import block with two dependencies:</p><ul><li>gocsv: the external package that we’ve previously installed</li><li>os: this built-in Go dependency will be used for I/O functionalities to read and write CSV files.</li></ul><h4><strong>CSV File</strong></h4><p>For this project, we’re going to use a sample CSV file that you can find at this <a href="https://github.com/duncanlew/demo-go-csv-parser/blob/main/example.csv">GitHub link</a>. Feel free to download and include this sample file in your project. Most CSV files are structured and have a header to denominate what each column will be used for. In Go, we can map each of CSV row into a custom data structure called struct. This struct will contain fields corresponding to a CSV column.</p><p>In our CSV file, the first two columns in this CSV file are named Title and URL. Mapping these two into a Go struct called `Article` would look like this:</p><pre>type Article struct {<br> Title string <br> URL string<br>}</pre><p>The gocsv dependency supports the usage of tags to indicate what the column name is in the CSV file. This is a handy feature in cases where you would have spaces in the column name or if the column name deviates from the actual field name we would like to use in the Go struct.</p><p>Considering all the columns of our CSV file, we can add all the columns with the csv tags to the final Article struct which should look like this:</p><pre>type Article struct {<br> Title           string `csv:&quot;Title&quot;`<br> URL             string `csv:&quot;URL&quot;`<br> DocumentTags    string `csv:&quot;Document tags&quot;`<br> SavedDate       string `csv:&quot;Saved date&quot;`<br> ReadingProgress string `csv:&quot;Reading progress&quot;`<br> Location        string `csv:&quot;Location&quot;`<br> Seen            string `csv:&quot;Seen&quot;`<br>}</pre><h4><strong>Read file</strong></h4><p>We are going to get to the crux of the project. We need to be able to read a CSV file called example.csv located in the root directory. To achieve this, we’re going to write a separate ReadCsv() function to achieve this:</p><pre>func ReadCsv() []*Article {<br> // Try to open the example.csv file in read-write mode.<br> csvFile, csvFileError := os.OpenFile(&quot;example.csv&quot;, os.O_RDWR, os.ModePerm)<br> // If an error occurs during os.OpenFIle, panic and halt execution.<br> if csvFileError != nil {<br>  panic(csvFileError)<br> }<br> // Ensure the file is closed once the function returns<br> defer csvFile.Close()<br><br> var articles []*Article<br> // Parse the CSV data into the articles slice. If an error occurs, panic.<br> if unmarshalError := gocsv.UnmarshalFile(csvFile, &amp;articles); unmarshalError != nil {<br>  panic(unmarshalError)<br> }<br><br> return articles<br>}</pre><p>The function ReadCsv can be broken down into the following parts:</p><ul><li>The function returns an slice of pointers to the elements of type Article.</li><li>We use os.OpenFile() to open example.csv with specific flags in read-write mode. The flag os.ModePerm indicates a the file mode for creating new files if necessary. This openFile() either returns a file handle (csvFile) or an error (csvFileError).</li><li>Immediately in the next step, we check for errors. The nil is Go’s equivalent to null or empty. If an error was stored in the variable, we exit the function and report the error.</li><li>The defer csvFile.Close() makes sure that the opened csvFile is always closed regardless of when the function return happens. This is best practice for file resource management.</li><li>With the file open and error handling in place, we’re going to proceed to parse the CSV content. The gocsv.UnmarshalFile() function is provided with the file handle and the reference articles slice. It reads the CSV rows and populates the slice with Article instances.</li><li>If the parsing of the csvFile completes without errors, the articles variable will be returned correctly.</li></ul><h4><strong>Filter articles</strong></h4><p>After successfully parsing the CSV file and storing its contents into an articles slice, the next step is to filter this slice. We want to only retain the articles whose location is set to inbox. We’re going to create a function called GetInboxArticles to achieve this:</p><pre>func GetInboxArticles(articles []*Article) []*Article {<br> // Initialize an empty slice to store inbox articles<br> var inboxArticles []*Article<br><br> // Iterate through each article in the provided slice.<br> for _, article := range articles {<br>  // Check if the article&#39;s Location is equal to inbox<br>  if article.Location == &quot;inbox&quot; {<br>   // If the article&#39;s location is inbox, add it to the inboxArticles slice<br>   inboxArticles = append(inboxArticles, article)<br>  }<br> }<br><br> return inboxArticles<br>}</pre><p>Let’s closely examine this function:</p><ul><li>This function accepts a slice of pointers to the Article struct and returns a slice of the same type.</li><li>We create an empty slice called inboxArticles that will store the articles that meet the inbox criteria.</li><li>We create a for loop that’s going to iterate through each element of the articles slice. If the location property of the article is equal to inbox, we append this element to the inboxArticles slice.</li><li>After the loop has finished, we return the slice inboxArticles.</li></ul><h4><strong>Write file</strong></h4><p>Now that we’ve extracted the inbox articles, we want to persist this data into a new CSV file. Writing contents to a CSV file will be similar to reading the contents as in the previous steps. We’re going to create a function WriteCsv that looks like this:</p><pre>func WriteCsv(articles []*Article) {<br> // Open result.csv for writing; create it if it doesn&#39;t exist, or overwrite it if it already exists.<br> resultFile, resultFileError := os.OpenFile(&quot;result.csv&quot;, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)<br><br> // Check for errors when opening or creating the file. If there&#39;s an error, panic.<br> if resultFileError != nil {<br>  panic(resultFileError)<br> }<br> defer resultFile.Close()<br><br> // Marshal the articles into the CSV format and write them to the result.csv file<br> if marshalFileError := gocsv.MarshalFile(&amp;articles, resultFile); marshalFileError != nil {<br>  panic(marshalFileError)<br> }<br>}</pre><p>Let’s go through this piece of code step by step:</p><ul><li>We create a function WriteCSV that accepts an input argument of Article slice.</li><li>We use os.OpenFile() to create or open the file results.csv. The flags passed into the function ensure that the file is write-only, will be created if it doesn’t exist, and overwritten if it already exists.</li><li>After trying to open the file result.csv, we check if the variable resultFileError contains an error. If it does contain an error, we exit the function with the panic operator.</li><li>For good I/O hygiene we ensure that the resultFile is closed whenever the function exits with the defer.</li><li>Finally, we are going to write the contents of the articles to the resultFile with gocsv.MarshalFile(). The MarshlFile function expects to arguments: reference to the slice, and the CSV file to which it should write the contents. If there was an error during the marshaling process, the function will panic.</li></ul><h4><strong>Putting it all together</strong></h4><p>We’ve written three helper functions: Reading a CSV file, writing to a CSV file and filtering articles. We’re going to combine all of these three into a main function like this:</p><pre>func main() {<br> articles := ReadCsv()<br> filteredArticles := GetInboxArticles(articles)<br> WriteCsv(filteredArticles)<br>}</pre><h4>Run 🚀</h4><p>With all the Go code in place, it’s time to run it! This can be done with the following command:</p><pre>go run main.go</pre><p>If done correctly, your project will have a new file named result.csv. Congratulations, you have just run your first Go project! 🎉</p><h3>Takeaway</h3><p>For our everyday task of processing a CSV file, we can see that Go’s simplicity, efficiency and easy-to-learn syntax shine brightly. This makes it easy for new learners to pick up this powerful language and rich ecosystem of packages and utilities. Keeping an eye on new tools and languages like Go can expand your skills toolset and offer you a different vantage point to think and solve problems. Of course the best tool for the job will depend on your project’s requirements. Perhaps you will consider integrating Go for your next software project. Happy coding! 🧑‍💻</p><p>The complete source code can be found in this <a href="https://github.com/duncanlew/demo-go-csv-parser/tree/main">GitHub project</a>.</p><p>If the content was helpful, feel free to support me <a href="https://www.buymeacoffee.com/duncanlew">here</a>:</p><figure><a href="https://www.buymeacoffee.com/duncanlew"><img alt="" src="https://cdn-images-1.medium.com/max/170/0*x2VPAGV3dIIOo_1P.png" /></a><figcaption>Buy me a coffee link for Duncan Lew</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=992b1636f139" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrate your data from Readwise Reader to Omnivore]]></title>
            <link>https://duncanlew.medium.com/migrate-your-data-from-readwise-reader-to-omnivore-e473dd7c3dcb?source=rss-da8fe21e0b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/e473dd7c3dcb</guid>
            <category><![CDATA[readwise]]></category>
            <category><![CDATA[omnivore]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Duncan Lew]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 21:16:48 GMT</pubDate>
            <atom:updated>2024-01-10T21:16:48.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNqcvdVWywG4gDc-aTYFJQ.png" /></figure><p>Readwise Reader and Omnivore are both great read-later services. Each offers unique features and experiences. Although I was an avid user of Readwise Reader, I didn’t use all of its features to their fullest. Omnivore, with its open-sourced nature, catered more closely to my needs. In situations where your needs change, migrating your saved content from Readwise Reader to Omnivore could become a necessity. Facing this issue myself, I decided to write my own tool to facilitate this process.</p><p>I had two main reasons for developing this tool. Firstly, I wanted to address this need that I have to seamlessly transfer my content between these two services. Fortunately, Omnivore provides a very extensive API to achieve this. Secondly, this project served as an opportunity for me to learn Rust, a programming language popular for its performance and memory safety.</p><p>This blog post will describe the steps you need to perform to import your data into Omnivore. The GitHub project with the source code can be found <a href="https://github.com/duncanlew/Readwise-to-Omnivore-Importer">here</a>.</p><h3>Prerequisites</h3><p>To get started with the data migration tool, you will need the following:</p><ul><li>Exported CSV file from Readwise Reader using the web interface. Check Readwise’s <a href="https://blog.readwise.io/p/f8c0f71c-fe5f-4025-af57-f9f65c53fed7/#howdoigenerateacsvofallmysaveddocuments">FAQ</a> for the steps</li><li><a href="https://docs.omnivore.app/integrations/api.html#getting-an-api-token">API key</a> from Omnivore</li></ul><h3>Running the importer tool</h3><p>There are two ways to run the importer tool. The easiest way without requiring to install Rust is by using the binary. For those who would like to explore the repository or make changes to the source code, it’s also possible to run the tool with the Rust build tools.</p><h4>Running it with the binary</h4><p>A compiled binary is available for download in the project <a href="https://github.com/duncanlew/readwise-to-omnivore-importer/releases">GitHub Releases</a> of this project.</p><ol><li>Download the binary<br>Navigate to the <a href="https://github.com/duncanlew/readwise-to-omnivore-importer/releases">Release</a> page and download the latest version for your operating system</li><li>Run the binary<br>Open a terminal and navigate to the directory where you downloaded the binary. Add your CSV file in that directory and then run the following command with the two parameters replaced</li></ol><pre>./readwise_to_omnivore_importer --key YOUR_API_KEY --file-path PATH_TO_CSV</pre><h4>Running it locally</h4><p>To run the project locally, make sure to first install <a href="https://www.rust-lang.org/tools/install">Rust</a> on your local machine. This should only take a few minutes. When that is done, open up a terminal and follow these steps:</p><ol><li>Clone the repository</li></ol><pre>git clone git@github.com:duncanlew/readwise-to-omnivore-importer.git   <br>cd readwise-to-omnivore-importer  </pre><p>2. Add your CSV file<br>Add your exported CSV file from Readwise Reader into the directory called <strong>readwise-to-omnivore-importer</strong>.</p><p>3. Run the importer<br>In the following command replace <strong>YOUR_API_KEY</strong> and <strong>PATH_TO_CSV</strong> with your api key and file path to your CSV, respectively.</p><pre>cargo run -- --key YOUR_API_KEY --file-path PATH_TO_CSV </pre><h3>Takeaway</h3><p>Transitioning your reading list from Readwise Reader to Omnivore is a streamlined process thanks to their easy export and import tools and APIs. Moreover, creating your own tool using an unfamiliar tech can be both rewarding and educational. I hope this guide, along with the provided source code in <a href="https://github.com/duncanlew/Readwise-to-Omnivore-Importer">the GitHub project</a> inspires you to embark on your own journey of continuous learning. Happy coding! 😎</p><p>If the content was helpful, feel free to support me <a href="https://www.buymeacoffee.com/duncanlew">here</a>:</p><figure><a href="https://www.buymeacoffee.com/duncanlew"><img alt="" src="https://cdn-images-1.medium.com/max/170/0*x2VPAGV3dIIOo_1P.png" /></a><figcaption>Buy me a coffee link for Duncan Lew</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e473dd7c3dcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Your First Chatbot using ChatGPT with TypeScript in NodeJS]]></title>
            <link>https://duncanlew.medium.com/building-your-first-chatbot-using-chatgpt-with-typescript-in-nodejs-af9ebdf374c9?source=rss-da8fe21e0b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/af9ebdf374c9</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Duncan Lew]]></dc:creator>
            <pubDate>Sun, 07 May 2023 17:38:02 GMT</pubDate>
            <atom:updated>2023-05-07T19:03:36.259Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hvwc0rWDsSLLqLJaZu9MdA.jpeg" /><figcaption>Friendly robot looking into the camera (<a href="https://www.pexels.com/photo/high-angle-photo-of-robot-2599244/">Source</a>)</figcaption></figure><p>Artificial intelligence (AI) is rapidly becoming one of the most promising technologies, particularly with the introduction of generative AI chatbots. OpenAI launched its first AI chatbot in November 2022 and within a short couple of months, it has become <a href="https://www.reuters.com/technology/chatgpt-sets-record-fastest-growing-user-base-analyst-note-2023-02-01/">the fastest-growing app in history</a>. Who would have known that one of the most transformative technologies to be introduced in 2022 would be a simple text box to chat with a computer program that can give you an answer to almost any question that you ask it? Many industries have shifted their strategies to incorporate and adopt more AI technologies into their core services and products.</p><p>It can be difficult to wrap your head around the rapid developments happening in the AI space, and many questions arise about how to best use AI to improve services. In this blog post, we’ll explore the building blocks of how to build a simple NodeJS application to chat with ChatGPT using TypeScript. This is going to be a command-line interface to interact with the chatbot.</p><p>What you will need to get started:</p><ul><li><a href="https://nodejs.org/en">Node.js</a> version 18 or newer</li><li>IDE of choice (e.g. Visual Studio Code)</li></ul><h3>1. Retrieve your API key from OpenAI</h3><p>In order to get started, you will need to create an API key to use ChatGPT from your Node.js application. Navigate to <a href="https://platform.openai.com/">https://platform.openai.com</a>. If you’ve used ChatGPT before, you will have already created an OpenAI account and can log in immediately. If not, create your account first to get started.</p><p>Once you’re signed in, click on the top right corner of your profile page to open up a dropdown menu. Select the option “View API keys”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*4TpXYAf8S938xDxdkA3vEQ.png" /><figcaption>Menu for selecting viewing API keys</figcaption></figure><p>A settings page will be shown in which you can generate a new secret key. Clicking on this button will trigger a modal to pop up displaying your new API key. Make sure to copy this value and store it in a safe place. This will be needed for the Node.js application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABJLScOHSJoxXqmia-MX2A.png" /><figcaption>Page for creating API keys</figcaption></figure><h4>Are there costs for using the API?</h4><p>Generating an API key, which is required to access the OpenAI API, can be done for free. As of the writing of this article, OpenAI provides users with a $5 credit that can be used to test their API without incurring any extra costs. If you wish to continue using the API after your free credits have been used up, you will need to enter your billing information. It’s important to keep in mind that OpenAI offers different pricing plans based on usage. Ensure your usage stays within budget if you decide to pay for a pricing plan.</p><h3>2. Set up a project with the required dependencies</h3><p>For our Node.js application, we’re going to create a directory to get started. We’re going to call this directory chatgpt-typescript:</p><pre>mkdir chatgpt-typescript</pre><p>Now we can navigate into the newly created directory to create the src directory to store our source code and initialize an npm project:</p><pre>cd chatgpt-typescript<br>mkdir src<br>npm init -y</pre><p>The flag -y means that we’re going to accept the defaults for creating the npm project.</p><p>Now we need to install the production and development dependencies of our project:</p><pre>npm install openai dotenv chalk<br>npm install -D typescript @types/node ts-node</pre><p>The dependency openai is package that provides wrapper methods to access the OpenAI API directly. Dotenv is a package that we use to easily load in environment variables. Finally, chalk is a package that we use to add beautifully colored styling to the terminal.</p><h3>3. Set up the TypeScript compiler</h3><p>To get started with TypeScript in our project, we need to initialize a TypeScript configuration file. We can do this with the following command:</p><pre>npx tsc --init</pre><p>The TypeScript compiler will create a tsconfig.json file with some default values. Replace the contents of that file with the following:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;es2017&quot;,<br>    &quot;module&quot;: &quot;ESNext&quot;,<br>    &quot;moduleResolution&quot;: &quot;nodenext&quot;,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true,<br>    &quot;strict&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;rootDir&quot;: &quot;./src&quot;,<br>    &quot;outDir&quot;: &quot;./build&quot;,<br>  }<br>}</pre><p>This is the file that we’ll be using for this blog post. We’ve defined that we will be using the modern ESM modules and that our root directory is inside ./src .</p><p>Inside our TypeScript files, we want to be able to use the import syntax. To do that, we need to instruct the compiler to use JavaScript modules. We are also going to add a build script and a start script to the package.json file. This will be useful when we want to play with our command-line interface. Add the following lines to your package.json file:</p><pre>{<br>  ...<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;tsc&quot;,<br>    &quot;start&quot;: &quot;npm run build &amp;&amp; node build/index.js&quot;<br>  },<br>  ...<br>}</pre><h3>4. Add your API key to the .env file</h3><p>The dependency dotenv that we installed allows Node to load environment variables from the .env file into its global variable called process.env. The API key that we generated, needs to be loaded into our Node.js application. We don’t add this API key directly into our TypeScript file, but place this inside .env file.</p><p>Create a .env file inside your root directory and add the following line to it:</p><pre>OPENAI_API_KEY=&lt;&lt;replace-with-your-openai-api-key&gt;&gt;</pre><p>Make sure to replace the placeholder with the contents of your API key.</p><h3>5. Write your first Chatbot in TypeScript</h3><p>Now it’s time to write our code to make an API call. Create an index.ts in the src directory.</p><p>The first thing that we’re going to do is add the following import lines for the required packages:</p><pre>import { Configuration, OpenAIApi, ChatCompletionRequestMessage } from &#39;openai&#39;;<br>import * as readline from &#39;readline&#39;;<br>import * as dotenv from &#39;dotenv&#39;;<br>import chalk from &#39;chalk&#39;;</pre><p>The next step is to load in the OpenAI API key. We need the this key to make API calls to OpenAI to interact with ChatGPT.</p><pre>// Load OpenAI API key from environment variable<br>dotenv.config();<br>const configuration = new Configuration({<br>  apiKey: process.env.OPENAI_API_KEY,<br>});<br>const openai = new OpenAIApi(configuration);</pre><p>We need to initialize two objects. A messages array to store the history of our interaction with the chatbot. This helps the chatbot to keep the history of your messages in memory when giving you back a response. The second object that we need to initialize is the userInterfaceobject. We use this object to interact with the command-line interface.</p><pre>// Initialize messages array<br>const messages: ChatCompletionRequestMessage[] = [];<br><br>// Initialize readline interface<br>const userInterface = readline.createInterface({<br>  input: process.stdin,<br>  output: process.stdout,<br>});</pre><p>Now that we have initialized the userInterfaceobject, we can set the prompt that the user sees when their input is required with .setPrompt(). After that, we add the .prompt() method so that the interface is going to wait for the user to add their input.</p><pre>// Set prompt for user<br>userInterface.setPrompt(`\n${chalk.blue(&#39;Send a message:&#39;)}\n`);<br>userInterface.prompt();</pre><p>When you see the message Send a message: , the user can enter a prompt for the chatbot. We want the chatbot to receive this prompt when the user presses the Enter button. We can do this with the following lines of code:</p><pre>userInterface.on(&#39;line&#39;, async (input) =&gt; {<br>  // Create request message and add it to messages array<br>  const requestMessage: ChatCompletionRequestMessage = {<br>    role: &#39;user&#39;,<br>    content: input,<br>  };<br>  messages.push(requestMessage);<br><br>  // Call OpenAI API to generate response<br>  const completion = await openai.createChatCompletion({<br>    model: &#39;gpt-3.5-turbo&#39;,<br>    messages: messages,<br>  });<br><br>  // Display response message to user<br>  const responseMessage = completion.data.choices[0].message;<br>  if (responseMessage) {<br>    console.log(chalk.green(responseMessage.content));<br>    messages.push({<br>      role: responseMessage.role,<br>      content: responseMessage.content,<br>    });<br>  }<br><br>  // Prompt user for next message<br>  userInterface.prompt();<br>});</pre><p>When the user presses Enter in the command-line interface, the program triggers the line event and extracts the user’s input from the input variable. The program then creates a ChatCompletionRequestMessage to store the input and stores it in the messages array. This message’s role property is set to user to indicate that it represents a user’s input. When ChatGPT generates a response, the program creates another ChatCompletionRequestMessage with the role property set to assistant to indicate that it presents the program’s response.</p><p>Finally, the program is going to make an API call to OpenAI generate a response based on the user’s input. This response is stored in the messages array and will be displayed in the command-line interface.Optionally, when the user quits the program, we can display an exit message:</p><pre>// Handle program exit<br>userInterface.on(&#39;close&#39;, () =&gt; {<br>  console.log(chalk.blue(&#39;Thank you for using this Demo&#39;));<br>});</pre><p>The complete code with all the required interactions should look like this:</p><pre>import { Configuration, OpenAIApi, ChatCompletionRequestMessage } from &#39;openai&#39;;<br>import * as readline from &#39;readline&#39;;<br>import * as dotenv from &#39;dotenv&#39;;<br>import chalk from &#39;chalk&#39;;<br><br>// Load OpenAI API key from environment variable<br>dotenv.config();<br>const configuration = new Configuration({<br>  apiKey: process.env.OPENAI_API_KEY,<br>});<br>const openai = new OpenAIApi(configuration);<br>// Initialize messages array<br>const messages: ChatCompletionRequestMessage[] = [];<br>// Initialize readline interface<br>const userInterface = readline.createInterface({<br>  input: process.stdin,<br>  output: process.stdout,<br>});<br>// Set prompt for user<br>userInterface.setPrompt(`\\n${chalk.blue(&#39;Send a message:&#39;)}\\n`);<br>userInterface.prompt();<br>userInterface.on(&#39;line&#39;, async (input) =&gt; {<br>  // Create request message and add it to messages array<br>  const requestMessage: ChatCompletionRequestMessage = {<br>    role: &#39;user&#39;,<br>    content: input,<br>  };<br>  messages.push(requestMessage);<br>  // Call OpenAI API to generate response<br>  const completion = await openai.createChatCompletion({<br>    model: &#39;gpt-3.5-turbo&#39;,<br>    messages: messages,<br>  });<br>  // Display response message to user<br>  const responseMessage = completion.data.choices[0].message;<br>  if (responseMessage) {<br>    console.log(chalk.green(responseMessage.content));<br>    messages.push({<br>      role: responseMessage.role,<br>      content: responseMessage.content,<br>    });<br>  }<br>  // Prompt user for next message<br>  userInterface.prompt();<br>});<br>// Handle program exit<br>userInterface.on(&#39;close&#39;, () =&gt; {<br>  console.log(chalk.blue(&#39;Thank you for using this Demo&#39;));<br>});</pre><h3>6. Interact with your chatbot 🤖</h3><p>Now it’s time for the moment of truth! Run the following command in your terminal to start up your chatbot:</p><pre>npm run start</pre><p>This command is going to transpile your TypeScript code to JavaScript and run the compiled code in build/index.js . You can now start interacting with ChatGPT using your TypeScript code. Ask it anything that you want. An example of this interaction looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*s-jJW3TciLCtdVjszNxpkQ.png" /><figcaption>Interaction with ChatGPT inside the terminal</figcaption></figure><h3>Takeaway</h3><p>ChatGPT is a powerful tool that can be leveraged by developers to add chatbot functionality to their existing applications. With the new wave of technological innovations happening in AI, learning to use these tools can help you to understand these trends better and provide users with an enhanced experience. By following this tutorial, you can see that it’s quite straightforward to get started with a simple example of connecting to ChatGPT. The next step for you could be to think of ways to integrate a ChatGPT-powered chatbot into your current services or workflows. Happy coding! 😎</p><p>The complete source code can be found <a href="https://github.com/duncanlew/demo-chatgpt-typescript">here</a>.</p><p>If the content was helpful, feel free to support me <a href="https://www.buymeacoffee.com/duncanlew">here</a>:</p><figure><a href="https://www.buymeacoffee.com/duncanlew"><img alt="" src="https://cdn-images-1.medium.com/max/170/0*x2VPAGV3dIIOo_1P.png" /></a><figcaption>Buy me a coffee link for Duncan Lew</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af9ebdf374c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop Anywhere, Anytime with GitHub Codespaces]]></title>
            <link>https://duncanlew.medium.com/develop-anywhere-anytime-with-github-codespaces-e43cf212fea8?source=rss-da8fe21e0b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/e43cf212fea8</guid>
            <category><![CDATA[github-codespaces]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Duncan Lew]]></dc:creator>
            <pubDate>Sat, 04 Feb 2023 19:42:50 GMT</pubDate>
            <atom:updated>2023-02-04T19:42:50.581Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>A Guide to Setting Up and Using GitHub Codespaces for Streamlined Development</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_WMYQG9DklFCbX1BaKBrQ.png" /></figure><p>Getting started with software development in any new project can be a daunting process. Depending on whether you’re running a Windows, Mac, or Linux operating system, the instructions to boot up the project correctly can differ a lot. There are many dependencies, extensions, and command-line tools to install and also network configurations that you might have to set up. And you haven’t even started writing your first line of code! 🤯</p><p>What if there is a way to skip the hassle of getting your local dev environment up and running and immediately start-up the project without any hassle? GitHub Codespaces is here to save the day! 🤩 GitHub Codespaces is a cloud-based development environment that comes fully configured with all the dependencies, IDE, and extensions that you need to start contributing your first line of code. The best part of GitHub Codespaces is that it can run in any browser opening up the possibility to use your iPad, Android tablet, or even your Chromebook as a development machine. You don’t have to worry anymore about the hardware specs of your device since the whole dev setup is running in the cloud. The only thing that you need is a stable internet connection.</p><p>In this article, we’re going to explore how to get started with GitHub Codespaces and use a sample GitHub repository to start up the project, make a change and commit a line of code. Let’s get started!</p><h3>What do you need to get started with GitHub Codespaces?</h3><p>There are many ways to use GitHub Codespaces. The method that we will be using in this article is to start Codespaces from inside your browser. There are also other ways to start it up directly with an IDE like Jetbrains IntelliJ or Visual Studio Code. These methods for starting up Codespaces from an IDE won’t be covered in this article.</p><p>Anyone with a GitHub account can get started with Codespaces. It is free for individual use for up to 60 hours a month. After you exceed this limit, you will have to sign up for a plan to continue coding in the cloud-hosted environment. 60 hours a month should be ample time to decide whether you want to continue using this service full-time or as a side addition to your development tools.</p><h3>1. Start CodeSpaces from a GitHub repository</h3><p>You can start a Codespaces instance from any GitHub repository. I have set up a working React project in a <a href="https://github.com/duncanlew/demo-codespaces">public repository</a> that you can use for Codespaces. Feel free to test it out directly from my repository.</p><p>When you open up the repository page, you will see a green <strong>Code</strong> button in the upper right corner:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*UVsw7WN94oPgNiyCLllMlA.png" /><figcaption>GitHub page in which the green Code button is displayed</figcaption></figure><p>Click on it to open up a menu. Select the <strong>Codespaces</strong> tab and then a different green button called <strong>Create Codespace on main</strong> will be shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*nfr02raZ86kskqTNC9jPFg.png" /><figcaption>Popup with the green button to create a Codespace</figcaption></figure><p>Clicking on <strong>Create Codespace on main</strong> will start up a cloud development environment. A loading screen will be shown while the creation is in progress:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*zp0wmBvR8HWXM52i5JPl1Q.png" /><figcaption>Progress screen for Codespace creation</figcaption></figure><p>After the cloud environment is up and running, you will see a Visual Studio Code instance running from inside your browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*15g8FILkanvmW5LgOsLlRQ.png" /><figcaption>Visual Studio Code from inside the browser</figcaption></figure><p>You’re now ready to start using CodeSpaces! 💻</p><h3>2. Start the React project from inside Codespaces</h3><p>Now that your Codespaces instance is up and running. It’s time to do some actual coding! In the open terminal that is on display, type npm run start and wait for the process to start up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zQqfYaN5cB4vbYtTyGqxQ.png" /><figcaption>Output for running npm run start</figcaption></figure><p>When the React project has started up, it will open up a new tab in your browser in which you can see your front-end page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_KfHEUrwdm4ZmmTPEom5Q.png" /><figcaption>Standard React frontend page</figcaption></figure><p>You have just successfully started your React application from inside the cloud environment! No setup, dependency management or extensions on your own machine is required to make it work. 😎</p><h3>3. Make a code contribution inside Codespaces</h3><p>Let’s go back to our browser tab with Codespaces up and running. Navigate to the following file: src/App.tsx. On line 11 change the line to GitHub Codespaces and save your changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*x_pwsC6qS2vSFU7IUk0IGw.png" /><figcaption>Source code for App.tsx</figcaption></figure><p>Go back to your tab in which you have your active front-end page running and refresh your page. You will see your changes immediately reflected on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSxWnCSo4kLJYWkAbbLLoQ.png" /><figcaption>React frontend page in which one line has been changed</figcaption></figure><p>Now that we’ve made our textual change in App.tsx, we can commit and push this change to our branch. This can also be easily done inside your Codespaces instance. You can either do this from the terminal or from the Source Control sidebar. Being able to perform git actions will depend on your access rights to the GitHub repository from which your Codespaces instance is running.</p><h3>4. Note on port forwarding</h3><p>When you ran npm run start in the previous steps, a local development server was started up from inside Codespaces. When an application inside Codespace starts a server with a localhostURL, port forwarding will automatically get set up so that you can visit the served page from a URL that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*zbfnGxOpuLSAB-bpgW4tvw.png" /><figcaption>Example frontend-page link for serving the React application</figcaption></figure><p>This URL can only be accessed privately. This means that only you can access it with the GitHub account you used to start Codespaces. If you want to share this URL with friends or colleagues so that they can check out the web server from their own devices, you have to make sure that the PORT visibility is set to public. This can be done easily from within Codespaces itself. In the Panel window, click on the PORTS tab. Our React application was being served on localhost:3000. The row with Port number 3000 is the one that corresponds to our local web application. Right-click on this row and click on Port Visibility and then Public to enable public access to your served React page. The options for changing the port visibility will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*T36PqV2jvu7olLoA26QS-Q.png" /><figcaption>Option for changing the port visibility for the React frontend page</figcaption></figure><h3>5. Stop or terminate Codespaces</h3><p>When you’re done with your coding session in Codespaces, closing the browser tab is not enough to terminate Codespaces. The cloud instance will still be running on GitHub’s server and each hour being run counts up to your 60-hour monthly allowance. You can either choose to pause or stop your Codespaces or to delete your Codespace instance completely. This can be done on the page of the GitHub repository by clicking on the green <strong>Code</strong> button and then clicking on the three dots of the active Codespace to show the termination options for your instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*Hg-2SiaOcerQKL-yUrmAxw.png" /><figcaption>Options for stopping or deleting the Codespace instance</figcaption></figure><h3>Wrap-up</h3><p>GitHub Codespaces is a powerful cloud-hosted development environment that provides developers with a secure and efficient way to code, build, and debug their projects. Forgo the hassle of owning a powerful development machine and installing all the required development dependencies. Being a productive developer on an iPad is made possible with Codespaces. With its easy setup and collaboration features, GitHub Codespaces makes it simple for developers to get started quickly and collaborate with others on their projects. Give it a try today and see how it can streamline your development work. Happy coding! 😎</p><p>If the content was helpful, feel free to support me <a href="https://www.buymeacoffee.com/duncanlew">here</a>:</p><figure><a href="https://www.buymeacoffee.com/duncanlew"><img alt="" src="https://cdn-images-1.medium.com/max/170/0*NCYraUX-aDuQpV4W.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e43cf212fea8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Back to the Basics with HTML Forms]]></title>
            <link>https://duncanlew.medium.com/back-to-the-basics-with-html-forms-7d8a7f2dcc1b?source=rss-da8fe21e0b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d8a7f2dcc1b</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Duncan Lew]]></dc:creator>
            <pubDate>Sat, 14 Jan 2023 19:08:50 GMT</pubDate>
            <atom:updated>2023-01-14T19:13:58.827Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Understand the intricacies of how the HTML Form works</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1Ks7JFYMkc7UkwiL06pBQ.png" /></figure><p>Forms are an essential part of any modern website that allows users to interact with data and submit information. Many modern frameworks like Angular and React have their own implementation and wrappers to facilitate the creation of HTML forms, but it&#39;s also important to understand what is happening behind the scenes when you&#39;re making an input form. In this article, we&#39;re going back to the basics of HTML forms and how to use them.</p><h3>Structure of an HTML form</h3><p>An HTML form is composed of a set of elements for users to interact with. These elements can include an input field, a checkbox, and a submit button. All the information filled in from the form fields can be used to submit information to a web application.</p><p>We’re going to create a simple form with two input fields for the username and email address and a submit button. In order to do this, we’re going to introduce three HTML elements:</p><ul><li>&lt;form&gt;: The form element is used as a container for various user input fields</li><li>&lt;input&gt;: This element allows input for our username and email address</li><li>&lt;label&gt;: This element is a caption that is used for the input element</li></ul><p>Using these three elements, we can create a simple HTML form like this:</p><pre>&lt;form&gt;<br>  &lt;label for=&quot;username&quot;&gt;Username&lt;/label&gt;<br>  &lt;input name=&quot;username&quot; id=&quot;username&quot; placeholder=&quot;Username&quot; /&gt;<br><br>  &lt;label for=&quot;email&quot;&gt;Email&lt;/label&gt;<br>  &lt;input name=&quot;email&quot; id=&quot;email&quot; placeholder=&quot;example@email.com&quot; /&gt;<br><br>  &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;<br>&lt;/form&gt;</pre><p>In this HTML sample, we see some attributes inside the &lt;label&gt; and &lt;input&gt; elements. Let’s take a look at what they are.</p><p>Inside the &lt;label&gt; element, the for attribute is used to associate the label with a specific form control. In this case, the label &quot;Username&quot; is associated with the text field that has an <strong>id</strong> of &quot;username&quot;.</p><p>Inside the &lt;input&gt; element. we’ve used a couple of attributes:</p><ul><li>name : This attribute is used to give the input form control a name. We can identify the correct input with this name attribute when the form is submitted.</li><li>placeholder: This is used to display placeholder text when the field hasn’t been filled in yet by the user.</li><li>type: The final &lt;input&gt; element has the attribute type with the value submit. This means that it will become a button that submits the form. All &lt;input&gt; elements can be given a type attribute. If none is defined as in the case of username and email, the default one will be text.</li></ul><p>When this sample HTML form is displayed by the browser, it will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*f0baD4ymu3efPropKStPbg.png" /><figcaption>Basic HTML form rendered in the browser</figcaption></figure><h3>Submitting the form</h3><p>We’ve created a complete working form with two input elements for username and email and a button to submit the data. What will actually happen when you click on the Submit button? The responsibilities are separated into two parts. The browser or the client is responsible for sending the form data, and the server is responsible for receiving and processing the form data. We’re going to take a look at what happens from the perspective of the browser or client.</p><p>Let’s assume that we’ve filled in helloworld and my@email.com for the first two input fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*oD5YLC3Zh8We24C035Guxg.png" /><figcaption>HTML form with filled in data</figcaption></figure><p>When you click on the submit button, a couple of things are going to happen:</p><ul><li>Form data will be collected as a query string based on the input fields like this: username=helloworld&amp;email=my@email.com</li><li>The current browser URL will be retrieved. If the form is being served from localhost:8000, then that is what the current URL will be.</li><li>The browser will navigate to the current address appended with the query string constructed from the form data. The formula for the constructed address is this: &lt;currentUrl&gt;?&lt;queryString&gt;</li><li>The resulting address will be localhost:8000?username=helloworld&amp;email=my@email.com</li></ul><p>Navigating to this newly constructed URL is in its essence a GET request. It’s up to the server to be able to process this URL with the query string parameters. What we often see with form submissions, is that we would like to do a POST request instead. In addition to that, we might also want to post this request to a specific URL. This can all be achieved by adding the method and action attributes in the &lt;form&gt; element like this</p><pre>&lt;form method=&quot;POST&quot; action=&quot;&lt;https://myformurl.com&gt;&quot;&gt;<br>    ...<br>&lt;/form&gt;</pre><p>If this form gets submitted, the browser is going to perform a POST request to the URL <a href="https://myformurl.com/">https://myformurl.com</a> with username=helloworld&amp;email=my@email.com as a payload. The request content-type header will be set to application/x-www-form-urlencoded. It’s then up to the server to be able to process this form submission correctly with the given information.</p><h3>Retrieving the form as a JSON payload</h3><p>In many modern JavaScript frameworks like Angular, React and Vue, form submission is done via a JSON payload. These frameworks usually don’t use a GET request with query string parameters or a POST request with a payload of content-type application/x-www-form-urlencoded. In order to achieve this form extraction as a JSON payload, we are going to add an event listener to the HTML form and some client-side JavaScript.</p><p>The event listener that we are going to add to the HTML form is called onsubmit. This event is fired when a form is submitted. When this onsubmit event is triggered, we want to call a function named extractJson(). We can do it like this:</p><pre>&lt;form onsubmit=&quot;extractJson(event)&quot;&gt;<br>    ...<br>&lt;/form&gt;</pre><p>In this example, the event argument is passed to the extractJson() function. This object is automatically generated by the browser when the form is submitted.</p><p>We now need some JavaScript to extract the JSON from the HTML form. This can be achieved with the following code:</p><pre>function extractJson(event) {<br>  event.preventDefault();<br>  const formData = new FormData(event.target);<br>  const jsonData = Object.fromEntries(formData);<br>  console.log(jsonData);<br><br>  // Send the JSON payload as a next step<br>}</pre><p>The line event.preventdefault(); is used to prevent the default behavior of the form submission to occur. The default behavior, in this case, is the GET request to the current URL with the form data as a query string parameter.</p><p>After preventing the default form behavior, we’re going to use the FormData API to retrieve the FormData which is stored in event.target. We use Object.fromEntries to convert the FormData to a plain JavaScript object and then log into the console. The expected console output will look like this:</p><pre>{<br>  &quot;username&quot;: &quot;helloworld&quot;,<br>  &quot;email&quot;: &quot;my@email.com&quot;<br>}</pre><p>This resulting variable jsonData can be used to send the form data to a server.</p><p>I’ve created a working CodePen sandbox to illustrate the extraction of the form data with these HTML and JavaScript code samples. You can find it over here: <a href="https://codepen.io/duncanlew/pen/mdjwMLO">https://codepen.io/duncanlew/pen/mdjwMLO</a>. Feel free to play around with it! You can check out the console output by clicking on the Console button in the bottom left corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*xoAGbtP4vPpZ8dwxQ9HG4w.png" /><figcaption>Console button in CodePen</figcaption></figure><p>I’ve added some CSS in the code sandbox to style the form a bit, but this is of course outside the scope of this article. 💅 All the CSS styling can be commented out so you can see what the unstyled version of the form looks like. This has no effect on the functionality of the form submission.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*WzgbmX0urXVLsMES1j61TA.png" /><figcaption>Styled HTML form</figcaption></figure><h3>Wrap-up</h3><p>HTML forms are one of the basic building blocks in modern websites to interact with data and submit information. Understanding the basics of how HTML forms work and how to use them is an important part of becoming a proficient web developer. With the right configuration, you can even send the form data as a JSON object. Don’t be afraid to take a step back from the modern frameworks and investigate what is happening technically under the hood. Happy coding! 👨‍💻</p><p>If the content was helpful, feel free to support me <a href="https://www.buymeacoffee.com/duncanlew">here</a>:</p><figure><a href="https://www.buymeacoffee.com/duncanlew"><img alt="" src="https://cdn-images-1.medium.com/max/170/0*NCYraUX-aDuQpV4W.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d8a7f2dcc1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamline Your Java Development Workflow with SDKMAN]]></title>
            <link>https://duncanlew.medium.com/streamline-your-java-development-workflow-with-sdkman-f53002b99ece?source=rss-da8fe21e0b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/f53002b99ece</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[jvm]]></category>
            <dc:creator><![CDATA[Duncan Lew]]></dc:creator>
            <pubDate>Sun, 08 Jan 2023 15:34:56 GMT</pubDate>
            <atom:updated>2023-09-11T12:08:43.791Z</atom:updated>
            <content:encoded><![CDATA[<h4>Switching between Java versions can be as easy as running a single command</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bua043frs6Z15nVLtN7c1A.png" /></figure><p>Do you have multiple versions of Java, Maven, Gradle, or other SDKs to manage? Are you tired of manually switching between different versions of these SDKs? SDKMAN to the rescue! SDKMAN is a command-line tool that allows you to quickly switch between various versions of SDKs, making it easier and more efficient to develop and test your applications. In this article, we’ll discuss the benefits of using SDKMAN, provide some installation instructions, and explain how to use it to switch Java versions.</p><h3>Benefits of using SDKMAN</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*yOOIxdU5C4efoaLeuQm0wQ.png" /><figcaption>Logo of SDKMAN</figcaption></figure><p>SDKMAN is a great tool for developers because it makes it easier to manage and switch between different versions of Java. By default, you can only have one version of Java installed on your computer at a time. With SDKMAN, you can easily switch between different Java versions without needing to uninstall or reinstall Java every time.</p><p>Another great benefit of SDKMAN is that it also works out of the box for other SDKs in the JVM ecosystem, like Maven, Gradle, Scala and SBT. You don’t have to install a different manager for each SDK.</p><p>In addition to that, SDKMAN makes it easier to keep your Java versions up-to-date. SDKMAN will automatically check for updates and notify you when new versions of Java are available. This saves you time and effort, as you don’t need to manually search for updates</p><p>Finally, SDKMAN is a tool built in bash and is completely free to use. It’s open-source and available for anyone to use.</p><h3>Installation</h3><p>Installing SDKMAN is very easy. All you need to do is run the following command in your terminal:</p><pre>curl -s &quot;https://get.sdkman.io&quot; | bash</pre><p>If the command has been executed successfully, the output is going to look similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlaOM_QaG5Tca9Csasz66Q.png" /><figcaption>Installation result of SDKMAN</figcaption></figure><p>Once the command has been run, you can use SDKMAN to install and switch between different versions of Java. You might have to restart your Terminal before the sdk commands will work. To check whether SDKMAN works in your terminal after the installation, type the following command:</p><pre>sdk version</pre><p>It should be able to output the version of SDKMAN like this:</p><pre>SDKMAN 5.16.0</pre><h3>Installing Java versions</h3><p>SDKMAN makes it very easy to install different Java versions. To list all available Java versions that you can install, simply run the following command:</p><pre>sdk list java</pre><p>This will list all the available versions of Java that you can install. If you want to install Java 11 from the vendor Temurin, you can look for the identifier in this list which is: 11.0.17-tem. Type q to exit the list. Using the identifier for the Java version you want to install, run the following installation command:</p><pre>sdk install java 11.0.17-tem</pre><p>After successfully installing Java 11, the output will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gbV4c5f8cRfUGQJmi6RvqA.png" /><figcaption>Installation result for Java 11</figcaption></figure><p>If you need to install Java 17 from Temurin, it’s as easy as copying the identifier from the output command of sdk list java and placing it in the sdk install command:</p><pre>sdk install java 17.0.5-tem</pre><h3>Switching Java versions</h3><p>To switch between Java versions, you need to look for the identifier of your Java version in sdk list java and copy that value to switch to. If you’d like to switch to Java 11 of Temurin, run the following command:</p><pre>sdk use java 11.0.17-tem</pre><p>If you’d like to switch to Java 17 of Temurin, this would be the correct command:</p><pre>sdk use java 17.0.5-tem</pre><h3>Making a specific Java version the default</h3><p>If you’d like to make a specific Java version the default, like version 17 of Temurin, you can run the following command:</p><pre>sdk default java 17.0.5-tem</pre><h3>How about Maven, Grade, and the rest?</h3><p>We’ve seen how to install and switch between Java versions. But how would you know which SDKs are supported? No worries! The complete list of SDKs supported by SDKMAN can be found here: <a href="https://sdkman.io/sdks">https://sdkman.io/sdks</a>. How do you install and switch between other JVM-based SDKs like Maven, Grade, and the rest? The principle is the same for Java. You simply have to replace the Java and identifier command with the one the SDK you want to use:</p><pre>sdk list maven<br>sdk install maven &lt;version-identifier&gt;</pre><h3>Conclusion</h3><p>SDKMAN streamlines the management of all the SDKs that you’d need in the JVM ecosystem. We’ve covered how to easily install and switch Java versions and also how to do that for other SDKs that you’d need. SDKMAN is definitely a tool worth checking out and can help you save time and effort in the process. This is especially helpful for teams that are working on multiple projects with different SDK version requirements. Happy coding! 😎</p><p>If the content was helpful, feel free to support me <a href="https://www.buymeacoffee.com/duncanlew">here</a>:</p><figure><a href="https://www.buymeacoffee.com/duncanlew"><img alt="" src="https://cdn-images-1.medium.com/max/170/0*NCYraUX-aDuQpV4W.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f53002b99ece" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Six Essential Tips for Boosting your JavaScript Skills]]></title>
            <link>https://duncanlew.medium.com/six-essential-tips-for-boosting-your-javascript-skills-d9dd9aa43ba7?source=rss-da8fe21e0b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9dd9aa43ba7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Duncan Lew]]></dc:creator>
            <pubDate>Sat, 31 Dec 2022 16:09:27 GMT</pubDate>
            <atom:updated>2022-12-31T16:09:27.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cyXq8vktgt9VI7egEJZpRg.png" /></figure><p>JavaScript was introduced in 1995 and its standards are actively being maintained by ECMA International — hence the name ECMAScript for JavaScript. Since 2015, major versions of the JavaScript language are being introduced every year in June. So JavaScript is constantly evolving, and new features are regularly being added to the language. Are you looking to take your JavaScript skills to the next level with all the relevant new features? Whether you’re a beginner or an experienced developer, there are always ways to improve and learn new techniques. In this blog post, we’ll explore six essential tips that can help you level up your JavaScript skills. For each tip, we’ll also point out which ECMAScript version is required to be able to use it.</p><h3>1. Optional Chaining</h3><p>Have you tried accessing nested properties inside an object in which the intermediate properties might be undefined? To avoid your code from throwing errors like Cannot read properties of undefined, we write very convoluted statements wrapped with &amp;&amp; operators like this:</p><pre>if (request.body &amp;&amp; request.body.product &amp;&amp; request.body.product.price) {<br>	console.log(request.body.product.price);<br>}</pre><p>JavaScript has a feature called optional chaining which is a way to access or modify properties of objects without worrying if an intermediate property is undefined. The statement will simply return undefined without throwing an error and ending your code execution prematurely. This optional chaining allows you to write cleaner, more concise code. By using optional chaining, you can avoid having to write multiple checks to verify the existence of an object before attempting to access it.</p><p>Rewriting the same if statement with optional chaining will look like this:</p><pre>if (request?.body?.product?.price) {<br>	console.log(request.body.product.price);<br>}</pre><p>This feature was introduced in ES2020.</p><h3>2. Nullish coalescing operator</h3><p>When you want to assign a value to a variable, you might be placing null and undefined checks to make sure that you’re retrieving the intended values. If that’s not the case, we might want to provide a fallback value in that case. Such a code sample could look like this:</p><pre>const userName = (user?.name !== null &amp;&amp; user?.name !== undefined) ?<br>    user.name :<br>    &#39;Anonymous&#39;;</pre><p>In JavaScript, there is a nullish coalescing operator (??) that allows developers to provide a fallback value when working with null or undefined values. This operator can be used to check for null or undefined values and provide an alternative value when the initial value is null or undefined.</p><p>For example, you can use the nullish coalescing operator to simplify the code sample from above like this:</p><pre>const userName = user?.name ?? &#39;Anonymous&#39;;</pre><p>This feature was introduced in ES2020.</p><h3>3. Maps Instead of For Loop</h3><p>When you start a JavaScript programming course, one of the first topics typically taught is for loops. For loops are a type of loop that repeats a set of instructions a certain number of times. They are used to iterate over data structures like arrays or objects and can be used to perform a wide variety of tasks.</p><p>If you want to iterate through an array and store the value of each number squared in a new array, it would look like this with a for loop:</p><pre>const numbers = [1, 2, 3, 4, 5];<br>const squares = [];<br>for (let i = 0; i &lt; numbers.length; i++) {<br>    squares.push(numbers[i]**2);<br>}</pre><p>With the introduction of newer, more modern features in JavaScript, for loops are not always the best option for some tasks. Maps are a powerful data structure that can often be used instead of for loops to improve performance. The map() method takes a callback function as its argument and returns an array with the results of calling the callback on each element in the array. This allows you to quickly and easily iterate over an array without having to write a loop.</p><p>The benefit of using a Map is that it doesn’t cause side-effects in your code and always allows you to create a new array. The resulting code with a Map would look like this:</p><pre>const numbers = [1, 2, 3, 4, 5];<br>const squares = numbers.map(number =&gt; number ** 2);</pre><p>This feature was introduced in ES2015 or ES6.</p><h3>4. Arrow Functions</h3><p>Arrow functions are a concise way to define functions in JavaScript, and they have several benefits over traditional function declarations. Arrow functions have a shorter syntax than regular functions, which can make your code more readable. Additionally, arrow functions are lexically scoped, meaning that the value of the this keyword inside an arrow function is the same as the value outside of it. This can be very helpful when working with objects and methods.</p><p>For example, consider the following regular function:</p><pre>function add(a, b) {<br>    return a + b;<br>}</pre><p>This can be written as an arrow function like this:</p><pre>const add = (a, b) =&gt; a + b;</pre><p>This feature was introduced in ES2015 or ES6.</p><h3>5. Object Destructuring</h3><p>Object destructuring is a feature of JavaScript that allows you to quickly and easily extract values from an object. It allows you to create variables that contain the values of specific properties in an object, which can be useful when you need to access the same properties repeatedly.</p><p>For example, consider the following code:</p><pre>const product = {<br>    name: &quot;iPhone&quot;,<br>    color: &quot;purple&quot;,<br>    price: 1000<br>};<br><br>const name = product.name;<br>const color = product.color;<br>const price = product.price;</pre><p>Using object destructuring, you can extract the values from the user object and assign them to variables like this:</p><pre>const product = {<br>    name: &quot;iPhone&quot;,<br>    color: &quot;purple&quot;,<br>    price: 1000<br>};<br><br>const { name, color, price } = product;</pre><p>This feature was introduced in ES2015 or ES6.</p><h3>6. Object literal enhancement</h3><p>Now that you know what Object destructuring is, it’s time to take a look at object literal enhancement. This is a feature of JavaScript that is the exact opposite of object destructuring. It allows you to grab variables and create objects with fewer lines of code. For example, consider the following code:</p><pre>const name = &quot;iPhone&quot;;<br>const color = &quot;purple&quot;;<br>const price = 1000;<br><br>const product = {<br>    name: name,<br>    color: color,<br>    price: price<br>};</pre><p>Using object literal enhancement, you can simplify this code to:</p><pre>const name = &quot;iPhone&quot;;<br>const color = &quot;purple&quot;;<br>const price = 1000;<br><br>const product = { name, color, price };</pre><p>This feature was introduced in ES2015 or ES6.</p><h3>Conclusion</h3><p>JavaScript is constantly getting enriched by new features every year. By following these up-to-date tips and continuing to learn and grow, you can level up your JavaScript skills and become a more proficient and successful developer. Don’t be afraid to challenge yourself and try new things — it’s the best way to improve and keep up with the ever-changing world of technology. Happing coding! 😎</p><p>If the content was helpful, feel free to support me <a href="https://www.buymeacoffee.com/duncanlew">here</a>:</p><figure><a href="https://www.buymeacoffee.com/duncanlew"><img alt="" src="https://cdn-images-1.medium.com/max/170/0*NCYraUX-aDuQpV4W.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9dd9aa43ba7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easily Format and Highlight Your Code in Google Docs]]></title>
            <link>https://duncanlew.medium.com/easily-format-and-highlight-your-code-in-google-docs-c51cbc0ce430?source=rss-da8fe21e0b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/c51cbc0ce430</guid>
            <category><![CDATA[google-docs]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[code-block]]></category>
            <dc:creator><![CDATA[Duncan Lew]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 17:24:42 GMT</pubDate>
            <atom:updated>2022-12-18T17:24:42.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NxPquzzjUeFzWRd1dK817w.jpeg" /></figure><p>Google Docs is a popular word processing tool that allows you to create and edit documents online. Code formatting in Google Docs hasn’t always been an easy task to achieve. If you wanted to put a code block directly into your Google Docs document, you would have ended up with unformatted code with no syntax highlighting. This isn’t always easy on the eyes and is not conducive to quickly scanning your code to get a sense of its purpose. There are other ways to achieve this in a more aesthetically pleasing way, but that meant having to use add-ons as a work-around. But fret no more, Google has got you covered! One of the new notable features that Google just <a href="https://workspaceupdates.googleblog.com/2022/12/format-display-code-google-docs.html">announced</a> is Code Formatting, which makes your code easier to read and understand.</p><h3>How to use it</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LD3H8GCcezqAiDkGba8Z-A.gif" /><figcaption>Gif illustrating how to use code formatting. Source: Google</figcaption></figure><p>To access this code-formatting feature in your current Google Docs document, select <em>Insert &gt; Building blocks &gt; Code Blocks</em>. Afterwards, select the programming language of your choice. It’s also possible to access this feature by typing @project assets in the document and selecting <em>Code blocks</em>.</p><h3>Availability</h3><p>According to Google’s post, the code formatting feature in Google Docs will be available to all Google Workspace customers starting on January 3, 2023. Google has not stated yet that they have plans to roll it out to those with personal Google Accounts in the future. Hopefully this will change in the near future.</p><h3>Wrap-up</h3><p>Google Docs is constantly getting improved with new features and this time it’s a boon for us developers out there! Code formatting in Google Docs is a useful tool that can help you create documents that are easier to read and understand. Whether you are working on a document that includes a lot of code or just want to insert a few lines of code into your document, Google Docs has you covered. 👨‍💻</p><p>If the content was helpful, feel free to support me <a href="https://www.buymeacoffee.com/duncanlew">here</a>:</p><figure><a href="https://www.buymeacoffee.com/duncanlew"><img alt="" src="https://cdn-images-1.medium.com/max/170/0*piVWSQay3tg2puI8.png" /></a><figcaption>Buy me a coffee link for Duncan Lew</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c51cbc0ce430" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>