<?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 Rainer Regan on Medium]]></title>
        <description><![CDATA[Stories by Rainer Regan on Medium]]></description>
        <link>https://medium.com/@rainerregan?source=rss-1e03268e6d1e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*k_TSFBrj2cgE7YFfqJRLdw.png</url>
            <title>Stories by Rainer Regan on Medium</title>
            <link>https://medium.com/@rainerregan?source=rss-1e03268e6d1e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:24:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rainerregan/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[How to Clone Github Private Repository with SSH]]></title>
            <link>https://rainerregan.medium.com/how-to-clone-github-private-repository-with-ssh-74f4fb28a967?source=rss-1e03268e6d1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/74f4fb28a967</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Rainer Regan]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 06:56:30 GMT</pubDate>
            <atom:updated>2024-12-07T06:56:30.463Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVfoB8j-za99iMdVH47FaQ.png" /></figure><p>Cloning a repository from GitHub can be tricky sometimes. There are some ways to clone a private repository on your machine. The most popular ones are using personal access tokens and SSH keys.</p><p>Using a GitHub personal access token is relatively easy, you just need to generate a PAT, and then append the token on the clone URL, but this will expose risk to your repo. If your token is leaked, then your repos are at risk.</p><p>Another way that is less risky to do is by using the SSH key, Here is how to do it on Ubuntu.</p><p>For this tutorial, I will be using Ubuntu 22.04LTS. But for now, I will show you on the Ubuntu desktop, but the method will be the same.</p><h3>Step 1: Make Sure Git is Installed</h3><p>You want to clone something from GitHub, of course, you need Git installed on your machine. We are using Ubuntu, Git should be installed by default. But its not hurt to check ;)</p><p>First check it by typing:</p><pre>git --version</pre><p>If Git is installed, you&#39;ll see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*LHgCZcq6YaiZlAtP-Rsj8w.png" /></figure><p>Otherwise, you need to install Git, You can check on how to install Git on Ubuntu.</p><h3>Step 2: Generating SSH Key</h3><p>This is the most important step, generating an SSH key from your machine.</p><p>To create a new SSH key you can create it using the ED25519 algorithm, associating with your email. You should replace the email below with your email address.</p><pre>ssh-keygen -t ed25519 -C &quot;your-email@example.com&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xY691-ZaCCD9aZ0wm1Yx7A.png" /><figcaption>Generating the SSH key</figcaption></figure><p>Next, the machine will ask about the SSH key file save directory, we will keep it by default. Press enter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZP9yP-6E7iL0fPVKRld-g.png" /></figure><p>Then you will be asked to enter the passphrase, we need to keep the key passphrase empty for easier access. Press Enter twice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEVtWo6lYbVgX4AqiPrhHg.png" /></figure><p>If the creation is successful, this will be shown, this is the location of your public and private key.</p><p>Then you can copy your SSH key using cat based on your save directory. This is the case for me.</p><pre>cat /home/ubuntu/.ssh/id_ed25519</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*HJbSk5ZoMoZWpxjxYN9Kww.png" /></figure><p>Copy all the content, and we will enter this into GitHub Settings.</p><h3>Step 3: Add SSH Key to GitHub</h3><p>You have created your SSH key, after copying the key, we will proceed to give access to this machine on our private repository.</p><p>Open GitHub, and direct to Settings on your <a href="https://github.com/settings/profile">profile</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*-tmcl4cbuAaOTDX2F6lSsw.png" /></figure><p>Then, direct to the SSH and GPG Keysmenu. Click on New SSH Key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3G7kmS9kGs2jFPntSllsQ.png" /></figure><p>Paste your SSH key and then give a title. Then click Add SSH key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uB_s_desA2jQ4TSPfn7f1A.png" /></figure><p>If successful, you will see your key has been added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EO43IxovbUKvSlF7do1jIw.png" /></figure><h3>Step 4: Cloning the Repository</h3><p>After adding the key, you can directly clone the repo using git clone command, but this time, using SSH option. Copy this from the repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*E9hp7oXaQXh3rS6NDjfy5g.png" /></figure><p>Then, Clone it on the machine.</p><pre>git clone git@github.com:username/repo-name.git</pre><p>Type yes if needed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3qVGRLcPDdwDUjC8kDjiQ.png" /></figure><p>Voila! your repo is now cloned to your systems. you can check it by typing</p><pre>ls</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74f4fb28a967" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Simple Pie Chart with Chart.js on React]]></title>
            <link>https://rainerregan.medium.com/how-to-create-a-simple-pie-chart-with-chart-js-on-react-1e5a16f364a3?source=rss-1e03268e6d1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e5a16f364a3</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Rainer Regan]]></dc:creator>
            <pubDate>Wed, 01 May 2024 17:21:33 GMT</pubDate>
            <atom:updated>2024-05-01T17:21:33.056Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GYhWsVdXRC__tRrcC7BrVg.png" /></figure><p>Hi, welcome back to my mini tutorial series. In this guide, I will tell you a simple trick to create a simple pie chart with Chart.js library on a React App.</p><p>Chart.js is an awesome Javascript library that provides tools to create awesome custom charts on your website. To follow this tutorial, please make sure that you have an active React project.</p><h3>Step 1 — Installing Chart.js and react-chartjs-2</h3><p>The most important thing is to install the Chart.js library on your project using NPM. BUT, to use Chart.js on React easily, we can utilize a React wrapper for Chart.js, which is react-chartjs-2.</p><p>Now, please make sure to install these two libraries.</p><pre>npm install chart.js react-chartjs-2</pre><h3>Step 2 — Prepare the Dataset</h3><p>Next, you may want to prepare the dataset that you want to show using a pie chart on your website. In this case, I will use a dummy dataset, but you can use any dataset you want, even if you want to fetch data from API or your database.</p><p>For this guide, I will simply create dummy data of my app user role.</p><pre>const data = {<br>  labels: [&quot;Customer&quot;, &quot;Business&quot;],<br>  datasets: [<br>    {<br>      data: [12, 29],<br>      backgroundColor: [<br>        &#39;rgba(255, 99, 132, 0.2)&#39;,<br>        &#39;rgba(54, 162, 235, 0.2)&#39;,<br>      ],<br>      borderWidth: 1,<br>    },<br>  ],<br>};</pre><p>This is the explanation:</p><ul><li>Label: This is the label for each data category, in this case, I will go with business and customer user type</li><li>Datasets: This array will tell chart.js the data that you want to show. For this sample, I will go with an array of two data for each category, 12 Customer users, and 29 Business users.</li><li>Background color: This will tell chart.js the color that you want to give for each data category on the pie chart.</li><li>Border width: The border width for the pie-chart.</li></ul><h3>Step 3 — Using the Pie Chart Component</h3><p>After preparing the data, you can now create a Pie chart using chart js but first, we need to import the components that are needed.</p><p>First, we need to import these from the chart.js and react-chartjs-2</p><pre>import { Pie } from &#39;react-chartjs-2&#39;<br>import { Chart as ChartJS, ArcElement, Tooltip, Legend } from &#39;chart.js&#39;;</pre><p>We will use the Pie component from the react-chartjs-2 wrapper, but we need to also register ArcElement, Tooltip, and Legend from chart js first.</p><pre>ChartJS.register(ArcElement, Tooltip, Legend);</pre><p>After that, we can now use the Pie component</p><pre>&lt;Pie data={data} /&gt;</pre><p>I have created a custom component for this chart, so my final code will look like this:</p><pre>import { Pie } from &#39;react-chartjs-2&#39;<br>import { Chart as ChartJS, ArcElement, Tooltip, Legend } from &#39;chart.js&#39;;<br><br>ChartJS.register(ArcElement, Tooltip, Legend);<br><br>const TotalUserPieChart = () =&gt; {<br>  const data = {<br>    labels: [&quot;Customer&quot;, &quot;Business&quot;],<br>    datasets: [<br>      {<br>        data: [12, 29],<br>        backgroundColor: [<br>          &#39;rgba(255, 99, 132, 0.2)&#39;,<br>          &#39;rgba(54, 162, 235, 0.2)&#39;,<br>        ],<br>        borderWidth: 1,<br>      },<br>    ],<br>  };<br><br>  return (<br>    &lt;Pie data={data} /&gt;<br>  )<br>}<br><br>export default TotalUserPieChart</pre><p>After reloading your app, the chart will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*riULyN4VXSRn-0O7sCyVWA.png" /></figure><h3>Conclusion</h3><p>Congratulations on your first Pie chart using chart.js, by the end of this guide, you have successfully created a simple pie chart using Chart.js library. You can now explore more about this chart-making experience. Your next step is to try other chart types. You can explore more about other chart type on their official documentation.</p><p>Thank you, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e5a16f364a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Tailwind Image Background on Next Js]]></title>
            <link>https://rainerregan.medium.com/how-to-use-tailwind-image-background-on-next-js-20dff451c3cb?source=rss-1e03268e6d1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/20dff451c3cb</guid>
            <category><![CDATA[ui-design]]></category>
            <category><![CDATA[tailwind]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Rainer Regan]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 09:36:57 GMT</pubDate>
            <atom:updated>2024-04-25T09:36:57.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d8HJMOBcaDp04O4pac1oyA.png" /></figure><p>Next Js is one of the most popular web application frameworks with react-based language. Tailwind, on the other hand, is used by a lot of developers for easier use of CSS by only using a set of classes directly to the DOM.</p><h3>Prerequisites</h3><p>I will assume that you already have knowledge in Tailwind and NextJs. To follow this tutorial, you also need a Next Js project with Tailwind installed.</p><h3>Step 1 — Copy the Image to Public Folder</h3><p>Firstly, you need to prepare the image and copy it into the public folder, so your file structure will look like this:</p><pre>./<br>└── next-web/<br>    ├── README.md<br>    ├── next-env.d.ts<br>    ├── next.config.mjs<br>    ├── node_modules/<br>    ├── package.json<br>    ├── postcss.config.mjs<br>    ├── public/<br>    │   ├── hero-bg.png &lt;----- THIS IS YOUR IMAGE<br>    │   ├── next.svg<br>    │   └── vercel.svg<br>    ├── src/<br>    ├── tailwind.config.ts<br>    ├── tsconfig.json<br>    └── yarn.lock</pre><h3>Option 1 — Using Tailwind Arbitrary Value</h3><p>Tailwind provides us with a very useful utility that allows us to create a custom value for the styling by directly injecting the value on the class list.</p><p>We can use brackets “[]” on the class name to inject the value.</p><p>For this case, we can use the bg-... class and CSS URL utility, it will look like this:</p><pre>bg-[url(https://medium.com/&quot;your-image-path&quot;)]<br></pre><p>Your code will look like this:</p><pre>const Hero = () =&gt; {<br>  return (<br>    &lt;div className=&#39;... bg-[url(https://medium.com/&quot;/hero-bg.jpg&quot;)]&#39;&gt;<br>      ...<br>    &lt;/div&gt;<br>  )<br>}</pre><p>After refreshing the page, your page will look like this. Tailwind will add the image into the background via URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1iP04vQGNUzTy6Jga_e1ag.png" /></figure><h3>Option 2 — Create a Custom Styling</h3><p>Arbitrary value is good for quick styling, but it will be a mess if you have a long name for the file, or if you want to re-use the background image. By creating a custom styling you can use a custom class name and re-use it anytime on any components of your project.</p><p>First, you need to open your tailwind config file on the root. This file is called “tailwind.config.ts”.</p><p>You will see a default config like this:</p><pre>import type { Config } from &quot;tailwindcss&quot;;<br><br>const config: Config = {<br>  content: [<br>    &quot;./src/pages/**/*.{js,ts,jsx,tsx,mdx}&quot;,<br>    &quot;./src/components/**/*.{js,ts,jsx,tsx,mdx}&quot;,<br>    &quot;./src/app/**/*.{js,ts,jsx,tsx,mdx}&quot;,<br>  ],<br>  theme: {<br>    extend: {<br>      backgroundImage: {<br>        &quot;gradient-radial&quot;: &quot;radial-gradient(var(--tw-gradient-stops))&quot;,<br>        &quot;gradient-conic&quot;:<br>          &quot;conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))&quot;,<br>      },<br>    },<br>  },<br>  plugins: [],<br>};<br>export default config;</pre><p>You can see that Tailwind has already given us an example of how to use a theme extension for a background image.</p><pre>theme: {<br>  extend: {<br>    backgroundImage: {<br>      &quot;gradient-radial&quot;: &quot;radial-gradient(var(--tw-gradient-stops))&quot;,<br>      &quot;gradient-conic&quot;:<br>        &quot;conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))&quot;,<br>    },<br>  },<br>},</pre><p>In this case, Tailwind has created a custom class for a gradient. We can delete the gradient-radial and gradient-conic objects and replace them with our own.</p><pre>backgroundImage: {<br>  &quot;hero-image&quot;: &quot;url(https://medium.com/&#39;/hero-bg.jpg&#39;)&quot;<br>},</pre><p>So, the final config will looks like this</p><pre>import type { Config } from &quot;tailwindcss&quot;;<br><br>const config: Config = {<br>  content: [<br>    &quot;./src/pages/**/*.{js,ts,jsx,tsx,mdx}&quot;,<br>    &quot;./src/components/**/*.{js,ts,jsx,tsx,mdx}&quot;,<br>    &quot;./src/app/**/*.{js,ts,jsx,tsx,mdx}&quot;,<br>  ],<br>  theme: {<br>    extend: {<br>      backgroundImage: {<br>        &quot;hero-image&quot;: &quot;url(https://medium.com/&#39;/hero-bg.jpg&#39;)&quot;<br>      },<br>    },<br>  },<br>  plugins: [],<br>};<br>export default config;</pre><p>After saving the config, you can use the custom class on your component</p><pre>const Hero = () =&gt; {<br>  return (<br>    &lt;div className=&#39;... bg-hero-image&#39;&gt;<br>      ...<br>    &lt;/div&gt;<br>  )<br>}</pre><p>This will give the same result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d8HJMOBcaDp04O4pac1oyA.png" /></figure><h3>Conclusion</h3><p>Using Tailwind CSS will make your front-end development much easier, yet, you still should have a good understanding of how CSS works. Using a custom image for the background in Tailwind is easy, you can utilize the arbitrary values in Tailwind to inject the URL directly. Another option to use a background image is by using custom styling to create a custom class. By using this technique, you can re-use the class on your other component, so you don&#39;t need to re-type the URL again and again.</p><p>Thank you and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20dff451c3cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Dockerize a Typescript Node.js App.]]></title>
            <link>https://rainerregan.medium.com/how-to-dockerize-a-typescript-node-js-app-250f8bd1d181?source=rss-1e03268e6d1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/250f8bd1d181</guid>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Rainer Regan]]></dc:creator>
            <pubDate>Wed, 24 Apr 2024 18:47:11 GMT</pubDate>
            <atom:updated>2024-04-24T18:47:11.338Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5tJzgSzvi7xff-gmFGoxJw.png" /></figure><p>Hi, we are back with the Dockerize series here. Docker is one of the most amazing tools to make your app development much easier and quicker. Moreover, Docker will help us to shorten the path needed to deploy our app.</p><p>Docker is a tool that will allow developers to containerize their apps and run them easily across different ecosystems without any worries of incompatibility. Docker runs your app’s image into a container that can be run on any OS that supports the Docker daemon.</p><h3>What is Node.js</h3><p>If you are searching for this title, you may or may not have known what Node Js is, but if you came across this article accidentally, don’t worry, I will explain Node.js as briefly as possible.</p><p>Node.js is one of the most popular Javascript server runtime environments. You may often hear that Javascript is mainly used in front-end development for DOM manipulation, but this is not the case. Node.js will allow us to run Javascript from the server side.</p><h3>Why Typescript?</h3><p>Typescript is a more advanced version of the Javascript language. Typescript allows developers to use strictly typed Javascript code to ensure the scalability and maintainability of the code. With Typescript, you don&#39;t need to worry about Javascript syntax inconsistencies.</p><h3>Prerequisites</h3><p>Now, we will start this tutorial, but before advancing, I want to make sure that you already have installed these apps on your systems:</p><ul><li>Node.js (run <strong>node -v</strong> on your terminal to check if Node is installed). You can install Node.js from their official website <a href="https://nodejs.org/en">here</a>.</li><li>Docker</li><li>Git (optional). If you want to use a demo project, you can install Git on your system to clone it directly.</li><li>A Typescript Node Js Project (optional). I will show you how to create a simple Node app with the Express framework, or you can clone my demo repository.</li><li>VS Code or any code editor.</li></ul><p>Now, let&#39;s begin.</p><h3>Step 1 — Create a Typescript Node.js App (Optional)</h3><h4>Clone Demo App</h4><p>In this step, I will show you how to create a simple Node js app, if you already have a project, you can use your own project or you can use my demo project by cloning it from my GitHub.</p><pre>git clone https://github.com/rainerregan/node-docker-demo.git</pre><p>Then, you need to change the directory to the project and install all of its dependencies.</p><pre>cd node-docker-demo<br>npm install</pre><p>Now, you can try to run the app</p><pre>npm run dev</pre><h4>Create Node app from scratch</h4><p>To make this tutorial focus on the dockerize process, I will not try to cover all the steps of creating a Node JS app using Typescript from scratch, but you can read my other article on creating the Node JS app using Typescript from scratch <a href="https://rainerregan.medium.com/how-to-create-node-js-express-app-using-typescript-from-scratch-cbd539284e81">here</a>.</p><h3>Step 2 — Create a Dockerfile</h3><p>Before creating a container to run our app, we need to create a Docker image of our app. Image is a bundle of our app with all of its dependencies, so we can run this into a container that can be deployed on any Docker environment.</p><p>To create a Docker image, we need a file called ‘Dockerfile’. A Dockerfile is a set of commands or instructions for building a Docker image. These commands define the steps required to set up the environment and configure the application inside the container.</p><p>To create a Dockerfile, we can create a new file called ‘Dockerfile’ on our root folder, and yes, without any extensions.</p><pre>node-docker-demo/<br>├── Dockerfile &lt;&lt;&lt;--- Create this<br>├── node_modules/<br>├── package-lock.json<br>├── package.json<br>└── src/</pre><p>Then open the file and type this command. I will try to explain the command to be as clear as possible.</p><pre># Set the base image from Docker repository to build our app. In this case we want to use node image to run our node app<br>FROM node:18.16.0-alpine as base<br><br># Then, we need to copy our package.json and .env file into the image root folder. <br>COPY package.json ./<br><br># Then, we need to install the dependencies inside the base image<br>RUN yarn install<br><br># After installing the dependencies, we need to copy the src folder from our local file into the base image<br>COPY src ./src<br><br># Copy tsconfig.json to base image too<br>COPY tsconfig.json ./tsconfig.json<br><br># Then, run the build command, this will compile the ts files into javascript files<br>RUN npm run build<br><br># After using base image for build process, we can create another image for the production build<br># Start production image build, we will use the same node image<br>FROM node:18.16.0-alpine<br><br># Copy node modules and build directory from base image to new image<br>COPY --from=base ./node_modules ./node_modules<br>COPY --from=base ./package.json ./package.json<br>COPY --from=base /dist /dist<br><br># Expose port 3000, and start the app.<br>EXPOSE 3000<br>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;start&quot;]</pre><p>After entering this command on the Dockerfile, we need to create a docker ignore file to prevent directories and files from being copied into the image.</p><p>Create a ‘.dockerignore’ file on the root, and type this:</p><pre>./node_modules<br>Dockerfile<br>.dockerignore<br>docker-compose.yml</pre><p>We want all files and folders from this list to be ignored in the image-building process.</p><h3>Step 3 — Using Docker Compose</h3><p>In this tutorial, I will use Docker Compose to make it easier to build and run the container. Without Docker Compose, we can still build and run the app, but it will take a longer command to type, and I want to keep it as simple as possible because, in the development phase, you will need to rebuild the image regularly.</p><p>First, create a new file on the root folder named ‘docker-compose.yml’. In this file, we will define the requirements for the container.</p><pre># We will use Docker compose v3.9<br>version: &#39;3.9&#39;<br><br>services:<br>  api:<br>    image: node-docker-demo:latest # Specify your custom Node.js image name and tag<br>    build: .<br>    command: npm run start<br>    ports:<br>      - &#39;4000:3000&#39; # Specify the exposed port, we will need this to access the app from local machine<br>    volumes:<br>      - ./api:/app</pre><p>Docker compose will handle the building and running process, so you can use simple commands to run or build the image.</p><p>With this step done, you have finished the Dockerizing preparation, now you can utilize Docker Compose to build or build &amp; run the app.</p><h3>Step 4 — Running The App Using Docker Compose</h3><p>After setting up the Dockerfile and Docker Compose, we can try to run the app using Docker Compose.</p><p>By running this command, Docker will automatically build your image and run the container.</p><pre>docker compose up</pre><p>Then, you will see the output like this</p><pre>host@computer % docker compose up         <br>      <br>[+] Running 1/1<br> ! api Warning                                                                                   4.2s <br>[+] Building 15.2s (14/14) FINISHED                                              docker:desktop-linux<br> =&gt; [api internal] load .dockerignore                                                            0.0s<br> =&gt; =&gt; transferring context: 2B                                                                  0.0s<br> =&gt; [api internal] load build definition from Dockerfile                                         0.0s<br> =&gt; =&gt; transferring dockerfile: 1.14kB                                                           0.0s<br> =&gt; [api internal] load metadata for docker.io/library/node:18.16.0-alpine                       1.8s<br> =&gt; [api internal] load build context                                                            0.0s<br> =&gt; =&gt; transferring context: 629B                                                                0.0s<br> =&gt; CACHED [api base 1/6] FROM docker.io/library/node:18.16.0-alpine@sha256:9036ddb8252ba7089c2  0.0s<br> =&gt; [api base 2/6] COPY package.json ./                                                          0.1s<br> =&gt; [api base 3/6] RUN yarn install                                                             11.9s<br> =&gt; [api base 4/6] COPY src ./src                                                                0.0s <br> =&gt; [api base 5/6] COPY tsconfig.json ./tsconfig.json                                            0.0s <br> =&gt; [api base 6/6] RUN npm run build                                                             1.1s <br> =&gt; CACHED [api stage-1 2/4] COPY --from=base ./node_modules ./node_modules                      0.0s <br> =&gt; [api stage-1 3/4] COPY --from=base ./package.json ./package.json                             0.0s <br> =&gt; [api stage-1 4/4] COPY --from=base /dist /dist                                               0.0s <br> =&gt; [api] exporting to image                                                                     0.0s<br> =&gt; =&gt; exporting layers                                                                          0.0s<br> =&gt; =&gt; writing image sha256:10fc77d29b7cbeed026862277ebf9093386cd7000c349ea97c07a16f49c78e86     0.0s<br> =&gt; =&gt; naming to docker.io/library/node-docker-demo:latest                                       0.0s<br>[+] Running 1/1<br> ✔ Container node-docker-demo-api-1  Created                                                     0.0s <br>Attaching to api-1<br>api-1  | <br>api-1  | &gt; docker-demo@1.0.0 start<br>api-1  | &gt; NODE_ENV=production node dist/index<br>api-1  | <br>api-1  | Server is running on http://localhost:3000</pre><p>We can see that the server is now running on port 3000, but remember, 3000 is the port that we set for the app, since the app is running inside an isolated container, we should access the app via the bridge port that we have set on the docker-compose.yml</p><pre>...<br>  ports:<br>    - &#39;4000:3000&#39; # Specify the exposed port, we will need this to access the app from local machine<br>....</pre><p>In this file, we have set the exposed port to be 4000. So, we can visit localhost:4000 to see if our app is running perfectly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hS1Ic1o5ftbd7obpdYhN6w.png" /></figure><p>You can see that our app is now running on port 4000, Yay~.</p><h3>Conclusion</h3><p>In this article, you have learned how to utilize Docker and Docker Compose to create a Docker image that will then be used as a container to run a Nodejs App. You also learn how to create a Dockerfile to define the steps used in building the image.</p><p>Thank you and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=250f8bd1d181" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Node js Express App Using Typescript from Scratch.]]></title>
            <link>https://rainerregan.medium.com/how-to-create-node-js-express-app-using-typescript-from-scratch-cbd539284e81?source=rss-1e03268e6d1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbd539284e81</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Rainer Regan]]></dc:creator>
            <pubDate>Wed, 24 Apr 2024 17:54:40 GMT</pubDate>
            <atom:updated>2024-04-24T17:59:18.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DBwrSzH_7JtyDYzUFa9Izw.png" /></figure><p>In this article, you will learn how to create a simple Node.js app using Typescript support. Before we start, we need to know what is Node js, Express, and Typescript, and what is the advantage of using Typescript over Javascript.</p><h3>What is Node.js?</h3><p>Node.js is one of the most popular Javascript server runtime environments. You may often hear that Javascript is mainly used for the front-end side of website development. But thanks to Node, we can now utilize Javascript on the back end.</p><h3>What is Typescript?</h3><p>Simply, Typescript is a programming language that is more advanced than Javascript. We can say Typescript is similar to Javascript. The difference between JS and TS is that Typescript will allow developers to use strict typing for the code. Javascript is notorious for its inconsistencies with its syntax and commonly causes many bugs in an app.</p><p>… And, why the hell should I use Typescript?</p><p>As we will use the Node app mainly for the back-end version, it is advised to utilize Typescript for the development, because it will create a more scalable and maintainable code for the future. This will significantly reduce errors and bugs in the app.</p><h3>What is Express?</h3><p>I won&#39;t explain too much about this. In simple terms, Express or Express.js is a minimum and flexible web application framework for Node Js. Express offers a wide range of features for building web applications and APIs. Express is designed as flexible as possible to give developers the freedom to define their own project structure.</p><p>Now, you should have a little grasp of Typescript, Node, and Express. We can begin creating a new app from scratch.</p><h3>Prerequisites</h3><p>To follow this tutorial, you need several apps installed on your systems.</p><ul><li>Node. This is the most important, please make sure you have installed node on your machine, or you can download it from their official website <a href="https://nodejs.org/en">here</a>.</li><li>Git (Optional). I will use Git to track changes.</li><li>VS Code or any code editor/IDE that you like.</li></ul><p>If all are installed, we can now advance to the tutorial.</p><h3><strong>Step 1 — Create a New Folder</strong></h3><p>Firstly, you need to create a new folder for our project, let’s call it express-demo.</p><pre>mkdir express-demo</pre><p>Then, change the directory to the folder.</p><pre>cd express-demo</pre><h3><strong>Step 2 — Init new Node js App</strong></h3><p>Inside the folder, we can create a new Node app from scratch. We can run this npm command.</p><pre>npm init -y</pre><p>This command will create a new package.json file for our node app. The ‘-y’ flag will tell the terminal to create a new package.json file using default options.</p><h3><strong>Step 3 — Install Express js.</strong></h3><p>For this tutorial, we will use the Express framework to create a simple routing for our app. We will install Express via npm.</p><pre>npm install express</pre><p>Then, to add support for Typescript types, install the Typescript types via NPM for the dev environment.</p><pre>npm i --save-dev @types/express</pre><p>NPM will install Express and create a node_modules folder containing all dependencies.</p><h3><strong>Step 4 — Create an index.ts file and create the folder structure.</strong></h3><p>First, create a src/ folder inside our root folder. We will put all of our files inside the src folder.</p><p>Next, we will create an index.ts file inside the src folder for running our app, so our initial folder structure will look like this:</p><pre>express-demo/<br>├── node_modules/<br>├── package-lock.json<br>├── package.json<br>└── src/<br>    └── index.ts</pre><h3><strong>Step 5 — Create a simple Express App</strong></h3><p>We can start to create a simple Express app. Open the index.ts app and type this code.</p><pre>// Import Express from the node_modules.<br>import Express from &#39;express&#39;<br>import { Response, Request } from &#39;express&#39; // Import the right response and request<br><br>// Create a new Express instance<br>const app = Express()<br>// Set the port that this app will run on<br>const PORT = 3000<br><br>// Create a simple GET route that will return a simple &quot;hello world!&quot; text using Express.<br>app.get(&#39;/&#39;, (req: Request, res: Response) =&gt; {<br>  res.send(&quot;Hello world&quot;) // Send simple hello world<br>})<br><br>// Start the server<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on http://localhost:${PORT}`);<br>});</pre><p>This code will create a new Express instance and assign a GET route to return simple text.</p><h3><strong>Step 6 — Run the app</strong></h3><p>To run a Typescript node app, we cannot use a direct node command, we need to use an additional library to support the app.</p><p>First, you need to install the ts-node library for the dev environment.</p><pre>npm i --save-dev ts-node</pre><p>After installing, you can run the app using the ts-node command and target our index file.</p><pre>npx ts-node src/index.ts</pre><p>Then, you will see the output like this</p><pre>% npx ts-node src/index.ts</pre><pre>Server is running on <a href="http://localhost:3000/">http://localhost:3000</a></pre><p>This message signs that our app is successfully run. Now we can visit port 3000 on localhost to see our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCOmPFprlIj-aNR6YTGylA.png" /></figure><p>Yay, your app is now up and running. You have created a simple Node js Express app.</p><h3>Conclusion</h3><p>In this tutorial, you have learned on how to create a simple Node Js Express app from scratch. This tutorial also covers the usage of ts-node for running the app with Typescript support. The next step is to learn the advances of Node js with Typescript such as controllers, routes, services, and unit tests. I will try to create another tutorial explaining this soon. Please stay tuned~~.</p><p>Thank you and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbd539284e81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Dockerize Next Js App]]></title>
            <link>https://rainerregan.medium.com/how-to-dockerize-next-js-app-b73e0134f973?source=rss-1e03268e6d1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b73e0134f973</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Rainer Regan]]></dc:creator>
            <pubDate>Sat, 20 Apr 2024 09:58:18 GMT</pubDate>
            <atom:updated>2024-04-20T09:58:18.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddNj945GnYGlt7Q3oxEMoA.png" /></figure><p>Docker is one of the most useful tools that will ease your app development journey. Docker allows developers to containerize their app and all of its dependencies into a single container, so it can be deployed easily on any environment that runs Docker.</p><h3>Prerequisites</h3><p>This tutorial will teach you how to dockerize a Next Js app, I will assume that you already have:</p><ul><li>A Next Js project.</li><li>Besides this, please make sure that you have installed Node Js and Docker daemon on your machine</li><li>Yarn installed on your machine</li></ul><h3>Step 1 — Create Dockerfile</h3><p>First, you need to create a new file on your project root, this file will be called “Dockerfile” without any extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*nTKfXQT9YMbvCwp0y8Uf5g.png" /><figcaption>Sample project structure</figcaption></figure><p>Next, open the file and insert this Docker command for the Dockerfile file.</p><pre>FROM node:18-alpine AS base<br><br># Install dependencies only when needed<br>FROM base AS deps<br># Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.<br>RUN apk add --no-cache libc6-compat<br>WORKDIR /app<br><br># Install dependencies based on the preferred package manager<br>COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./<br>RUN \<br>  if [ -f yarn.lock ]; then yarn --frozen-lockfile; \<br>  elif [ -f package-lock.json ]; then npm ci; \<br>  elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm &amp;&amp; pnpm i --frozen-lockfile; \<br>  else echo &quot;Lockfile not found.&quot; &amp;&amp; exit 1; \<br>  fi<br><br><br># Rebuild the source code only when needed<br>FROM base AS builder<br>WORKDIR /app<br>COPY --from=deps /app/node_modules ./node_modules<br>COPY . .<br><br># Next.js collects completely anonymous telemetry data about general usage.<br># Learn more here: https://nextjs.org/telemetry<br># Uncomment the following line in case you want to disable telemetry during the build.<br># ENV NEXT_TELEMETRY_DISABLED 1<br><br>RUN yarn build<br><br># If using npm comment out above and use below instead<br># RUN npm run build<br><br># Production image, copy all the files and run next<br>FROM base AS runner<br>WORKDIR /app<br><br>ENV NODE_ENV production<br># Uncomment the following line in case you want to disable telemetry during runtime.<br># ENV NEXT_TELEMETRY_DISABLED 1<br><br>RUN addgroup --system --gid 1001 nodejs<br>RUN adduser --system --uid 1001 nextjs<br><br>COPY --from=builder /app/public ./public<br><br># Set the correct permission for prerender cache<br>RUN mkdir .next<br>RUN chown nextjs:nodejs .next<br><br># Automatically leverage output traces to reduce image size<br># https://nextjs.org/docs/advanced-features/output-file-tracing<br>COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./<br>COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static<br><br>USER nextjs<br><br>EXPOSE 3000<br><br>ENV PORT 3000<br># set hostname to localhost<br>ENV HOSTNAME &quot;0.0.0.0&quot;<br><br>CMD [&quot;node&quot;, &quot;server.js&quot;]</pre><p>These commands will build your app, put all dependencies, and run your app inside an isolated container with an exposed port to access it.</p><p>But, by using this file only, it will use a long command to run. Instead, we can utilize Docker to compose to make it easier to build.</p><h3>Step 2 — Using Docker Compose</h3><p>Instead of using only Dockerfile, we can use Docker Compose. To use it, first, we need to create another new file, this file will be called ‘docker-compose.yml’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*C7_HXT4L3mBV4BtzpI0zqQ.png" /><figcaption>Create a new file</figcaption></figure><p>Inside this file, we can put this docker-compose commands:</p><pre>version: &#39;3.9&#39;<br>services:<br>  web:<br>    build:<br>      context: ./<br>      target: runner<br>    image: example-image<br>    volumes:<br>      - .:/app<br>    command: npm run dev<br>    ports:<br>      - &quot;3000:3000&quot;<br>    environment:<br>      NODE_ENV: development<br>    platform: linux/amd64</pre><p>Now, you are ready to build and run the app using docker-compose.</p><h3>Step 3 — Containerize Using Docker Compose</h3><p>After you have set up the docker-compose YML file, you can utilize this command to build the app into an image, that later can you push into Docker registry such as Docker Hub or any custom registry.</p><pre>docker compose build</pre><h3>Conclusion</h3><p>In this tutorial, you have learned how to containerize a Next Js app, starting from creating the Dockerfile and using Docker Compose to ease the build process.</p><p>Thank you and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b73e0134f973" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Install Docker on Ubuntu 22.04 Server]]></title>
            <link>https://rainerregan.medium.com/how-to-install-docker-on-ubuntu-22-04-server-059ff197bfc4?source=rss-1e03268e6d1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/059ff197bfc4</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[app-deployment]]></category>
            <dc:creator><![CDATA[Rainer Regan]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 17:02:37 GMT</pubDate>
            <atom:updated>2024-04-19T17:02:37.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQ9UpVA-uWMYbm2Q7iyTYg.png" /></figure><p>From my experiences in software engineering, Docker is by far the most effective tool that gives me ease in development and app deployment in different ecosystems.</p><p>Docker is a tool that simplifies app processes inside a container. This container allows developers to package up an application with all of its dependencies into a bundle. This will make the app run consistently in any environment.</p><blockquote>Let’s think Docker is like a lunchbox. In a lunchbox, you can neatly pack all the different components of your meal — sandwiches, fruits, snacks — each in its own compartment. Like a lunchbox, Docker allows you to package up all the components of your application — like the code, libraries, and dependencies — into a container. So, Docker is like a lunchbox for your applications, making them easy to carry and deploy wherever you need them.</blockquote><h3>Prerequisites</h3><p>To follow this tutorial, please make sure that you have fulfilled these requirements:</p><ul><li>A running Ubuntu 22.04 machine, including a sudo user.</li><li>Opened SSH access using SSH client if you want to connect the machine via remote access.</li></ul><h3>Step 1 — Preparation &amp; Installation</h3><p>Before installing Docker using APT, we need to do some preparation on our Ubuntu machine. The first step in this section is to make sure the docker installation package is up to date on our machine. We can update our package list by running this.</p><pre>sudo apt update</pre><p>Next, we need to install some packages that will allow apt to use packages using HTTPS.</p><pre>sudo apt install apt-transport-https ca-certificates curl software-properties-common</pre><p>To ensure we install Docker from a valid official Docker repository, we need to add Docker’s GPG key to our system. GPG Key or GNU Privacy Guard in simplified terms is an implementation to create a secure data transmission between sources and is also used to verify the genuineness of the message origin.</p><pre>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg</pre><p>Then, we can add the Docker repository to our APT sources:</p><pre>echo &quot;deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable&quot; | sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null</pre><p>After adding the new source, we can update our APT repository to recognize the new addition.</p><pre>sudo apt update</pre><p>Then, you need to check the installation of docker-ce. Make sure that you install Docker from its official repository instead of default Ubuntu repository.</p><pre>apt-cache policy docker-ce</pre><p>After running the command above, you will notice that docker-ce is not installed, but it has the candidate version.</p><pre>docker-ce:<br>  Installed: (none)<br>  Candidate: 5:26.0.2-1~ubuntu.22.04~jammy<br>  Version table:<br>     5:26.0.2-1~ubuntu.22.04~jammy 500<br>        500 https://download.docker.com/linux/ubuntu jammy/stable amd64 Packages<br>     5:26.0.1-1~ubuntu.22.04~jammy 500<br>        500 https://download.docker.com/linux/ubuntu jammy/stable amd64 Packages</pre><p>The version may be different on your machine. Then, we can start installing Docker</p><pre>sudo apt install docker-ce</pre><p>You will be informed that this will take disk spaces, just type ‘Y’ and enter</p><pre>After this operation, 430 MB of additional disk space will be used.<br>Do you want to continue? [Y/n] Y</pre><p>After the process has finished, the daemon automatically starts and the process automatically starts on boot. To make sure the process is running, run this command:</p><pre>sudo systemctl status docker</pre><p>You will see something like this</p><pre>root@ubuntu-s-1vcpu-2gb-sgp1-01:~# sudo systemctl status docker<br>● docker.service - Docker Application Container Engine<br>     Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)<br>     Active: active (running) since Fri 2024-04-19 16:45:22 UTC; 2min 1s ago<br>TriggeredBy: ● docker.socket<br>       Docs: https://docs.docker.com<br>   Main PID: 121510 (dockerd)<br>      Tasks: 7<br>     Memory: 29.1M<br>        CPU: 361ms<br>     CGroup: /system.slice/docker.service<br>             └─121510 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock</pre><p>To exit from the systemctl status, press Ctrl + C.</p><p>By installing docker, besides enabling the Docker daemon, you will also be given access to the ‘docker’ command for using Docker.</p><h3>Step 2 — Using Docker Command</h3><p>To use docker, you can use command and options with arguments. The syntax for the docker command will look like this:</p><pre>docker [option] [command] [arguments]</pre><p>To see the list of all commands, you can type:</p><pre>docker</pre><p>This command will return a response of the complete Docker command list:</p><pre>Usage:  docker [OPTIONS] COMMAND<br><br>A self-sufficient runtime for containers<br><br>Common Commands:<br>  run         Create and run a new container from an image<br>  exec        Execute a command in a running container<br>  ps          List containers<br>  build       Build an image from a Dockerfile<br>  pull        Download an image from a registry<br>  push        Upload an image to a registry<br>  images      List images<br>  login       Log in to a registry<br>  logout      Log out from a registry<br>  search      Search Docker Hub for images<br>  version     Show the Docker version information<br>  info        Display system-wide information<br><br>Management Commands:<br>  builder     Manage builds<br>  buildx*     Docker Buildx<br>  compose*    Docker Compose<br>  container   Manage containers<br>  context     Manage contexts<br>  image       Manage images<br>  manifest    Manage Docker image manifests and manifest lists<br>  network     Manage networks<br>  plugin      Manage plugins<br>  system      Manage Docker<br>  trust       Manage trust on Docker images<br>  volume      Manage volumes<br><br>Swarm Commands:<br>  swarm       Manage Swarm<br><br>Commands:<br>  attach      Attach local standard input, output, and error streams to a running container<br>  commit      Create a new image from a container&#39;s changes<br>  cp          Copy files/folders between a container and the local filesystem<br>  create      Create a new container<br>  diff        Inspect changes to files or directories on a container&#39;s filesystem<br>  events      Get real time events from the server<br>  export      Export a container&#39;s filesystem as a tar archive<br>  history     Show the history of an image<br>  import      Import the contents from a tarball to create a filesystem image<br>  inspect     Return low-level information on Docker objects<br>  kill        Kill one or more running containers<br>  load        Load an image from a tar archive or STDIN<br>  logs        Fetch the logs of a container<br>  pause       Pause all processes within one or more containers<br>  port        List port mappings or a specific mapping for the container<br>  rename      Rename a container<br>  restart     Restart one or more containers<br>  rm          Remove one or more containers<br>  rmi         Remove one or more images<br>  save        Save one or more images to a tar archive (streamed to STDOUT by default)<br>  start       Start one or more stopped containers<br>  stats       Display a live stream of container(s) resource usage statistics<br>  stop        Stop one or more running containers<br>  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE<br>  top         Display the running processes of a container<br>  unpause     Unpause all processes within one or more containers<br>  update      Update configuration of one or more containers<br>  wait        Block until one or more containers stop, then print their exit codes<br><br>Global Options:<br>      --config string      Location of client config files (default &quot;/root/.docker&quot;)<br>  -c, --context string     Name of the context to use to connect to the daemon (overrides DOCKER_HOST env<br>                           var and default context set with &quot;docker context use&quot;)<br>  -D, --debug              Enable debug mode<br>  -H, --host list          Daemon socket to connect to<br>  -l, --log-level string   Set the logging level (&quot;debug&quot;, &quot;info&quot;, &quot;warn&quot;, &quot;error&quot;, &quot;fatal&quot;) (default &quot;info&quot;)<br>      --tls                Use TLS; implied by --tlsverify<br>      --tlscacert string   Trust certs signed only by this CA (default &quot;/root/.docker/ca.pem&quot;)<br>      --tlscert string     Path to TLS certificate file (default &quot;/root/.docker/cert.pem&quot;)<br>      --tlskey string      Path to TLS key file (default &quot;/root/.docker/key.pem&quot;)<br>      --tlsverify          Use TLS and verify the remote<br>  -v, --version            Print version information and quit<br><br>Run &#39;docker COMMAND --help&#39; for more information on a command.<br><br>For more help on how to use Docker, head to https://docs.docker.com/go/guides/</pre><p>To see the description of each command, you can run:</p><pre>docker COMMAND --help<br><br>// For example<br>docker pull --help</pre><p>Docker will return the complete description for the ‘pull’ command.</p><pre>Usage:  docker pull [OPTIONS] NAME[:TAG|@DIGEST]<br><br>Download an image from a registry<br><br>Aliases:<br>  docker image pull, docker pull<br><br>Options:<br>  -a, --all-tags                Download all tagged images in the repository<br>      --disable-content-trust   Skip image verification (default true)<br>      --platform string         Set platform if server is multi-platform capable<br>  -q, --quiet                   Suppress verbose output</pre><p>To see a complete guide on how to use Docker, you can visit their official documentation at <a href="https://docs.docker.com/go/guides/">https://docs.docker.com/go/guides/</a></p><h3>Conclusions</h3><p>Congratulations! You have successfully installed Docker on your Ubuntu machine, the next step is to learn how to use Docker properly from creating images, pushing images, pulling images, running a container, and so on. I will try to create a regular article on how to use Docker properly. Please stay tuned!</p><p>Thank you and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=059ff197bfc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Install MySQL on Ubuntu 22.04 Server]]></title>
            <link>https://rainerregan.medium.com/how-to-install-mysql-on-ubuntu-22-04-server-9ec794e84f7a?source=rss-1e03268e6d1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ec794e84f7a</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mysql-server]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Rainer Regan]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 06:15:14 GMT</pubDate>
            <atom:updated>2024-04-18T06:15:14.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wltmp3q4qnrMT9ncrY0arA.png" /></figure><p>MySQL is one of the most popular database management systems that have been used in many apps. It’s renowned for its compatibility with many tech stacks. MySQL implements a relational model and uses a Structured Query Language or SQL.</p><p>To use MySQL, you can install it on a server such as VPS or install it on your local machine. MySQL servers will work on many operating systems, but the most popular is Linux-based OS, such as Ubuntu.</p><p>In this tutorial, we will go through step-by-step on how to set up MySQL on your Ubuntu machine. Please take note that I will assume you already have a connection to your remote machine SSH if you are using a VPS because this tutorial will not cover the SSH setup, I may create another article to explain it later.</p><h3>Prerequisites</h3><p>Before starting, I will assume that you:</p><ul><li>Already have access to your Ubuntu machine (locally or remotely).</li><li>Have a good understanding of how to run commands on a Linux-based terminal.</li></ul><h3>Step 1 — Preparation and Installing MySQL</h3><p>MySQL can be installed through the APT package repository on Ubuntu. At this time, the latest MySQL version is 8.*</p><p>Before installing, please make sure to update your package index on your machine.</p><pre>sudo apt update</pre><p>After that, you can start installing the MySQL server</p><pre>sudo apt install mysql-server</pre><p>You will be asked to use additional disk space, just say ‘yes’</p><pre>After this operation, 243 MB of additional disk space will be used.<br>Do you want to continue? [Y/n] y</pre><p>Then, to make sure the server is running on the system service, run this command.</p><pre>sudo systemctl start mysql.service</pre><p>You can run this command to see the status of MySQL service</p><pre>sudo systemctl status mysql.service</pre><p>It will look like this</p><pre>root@ubuntu-s-1vcpu-2gb-sgp1-01:~# sudo systemctl status mysql.service <br>● mysql.service - MySQL Community Server<br>     Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)<br>     Active: active (running) since Thu 2024-04-18 05:35:46 UTC; 57s ago<br>   Main PID: 92105 (mysqld)<br>     Status: &quot;Server is operational&quot;<br>      Tasks: 38 (limit: 2323)<br>     Memory: 365.3M<br>        CPU: 1.528s<br>     CGroup: /system.slice/mysql.service<br>             └─92105 /usr/sbin/mysqld</pre><p>Congratulation! you have installed MySQL on your machine. But don’t celebrate early! you may have installed MySQL, but you have not set the password for the root user. Without this, you cannot create users or databases.</p><p>In the next section, we will cover how to configure MySQL.</p><h3>Step 2 — Configuring MySQL</h3><p>After installing, the next thing that you want to do is configure the MySQL server, including setting the root password, disallowing root remote access, and removing the sample user and database.</p><p>To start the configuration wizard, we can run</p><pre>sudo mysql_secure_installation</pre><p>After running this command, the MySQL server will take you through some prompts that you can utilize to change your MySQL installation.</p><p>The first prompt you will be asked is to set up the validate password plugin, this plugin will validate the db user password, just type ‘y’ and enter. Then, you will be asked to choose the password validation policy.</p><p>In this tutorial, we will use the low-validation one, but please make sure to use the strong validation policy for a production environment to ensure database security.</p><pre>Securing the MySQL server deployment.<br><br>Connecting to MySQL using a blank password.<br><br>VALIDATE PASSWORD COMPONENT can be used to test passwords<br>and improve security. It checks the strength of password<br>and allows the users to set only those passwords which are<br>secure enough. Would you like to setup VALIDATE PASSWORD component?<br><br>Press y|Y for Yes, any other key for No: y <br><br>There are three levels of password validation policy:<br><br>LOW    Length &gt;= 8<br>MEDIUM Length &gt;= 8, numeric, mixed case, and special characters<br>STRONG Length &gt;= 8, numeric, mixed case, special characters and dictionary                  file<br><br>Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 0</pre><p>By July 2022, MySQL installation will skip root password setup, but you can always change the root password using ALTER USER later after the installation configuration is finished.</p><pre>Skipping password set for root as authentication with auth_socket is used by default.<br>If you would like to use password authentication instead, this can be done with the &quot;ALTER_USER&quot; command.<br>See https://dev.mysql.com/doc/refman/8.0/en/alter-user.html#alter-user-password-management for more information.</pre><p>After choosing the password validation policy, the installation wizard will ask you to whether remove the anonymous user or not. This anonymous user is used for testing only, we will remove it now.</p><pre>By default, a MySQL installation has an anonymous user,<br>allowing anyone to log into MySQL without having to have<br>a user account created for them. This is intended only for<br>testing, and to make the installation go a bit smoother.<br>You should remove them before moving into a production<br>environment.<br><br>Remove anonymous users? (Press y|Y for Yes, any other key for No) : y</pre><p>The next prompt is to disable the root connection from the remote, this will make sure no one can log in to your root account from any remote network, and can only be accessed through localhost. If you wish to create a remote connection, you can create another DB user with a specific policy to connect from a remote network.</p><pre><br>Normally, root should only be allowed to connect from<br>&#39;localhost&#39;. This ensures that someone cannot guess at<br>the root password from the network.<br><br>Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y</pre><p>Next step, you will be asked to remove the test database and its access. We will not need this, just remove all testing databases.</p><pre>By default, MySQL comes with a database named &#39;test&#39; that<br>anyone can access. This is also intended only for testing,<br>and should be removed before moving into a production<br>environment.<br><br><br>Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y</pre><p>Next, after dropping the access to the test database, you will need to reload the database privilege, press ‘y’, and enter.</p><pre>Reloading the privilege tables will ensure that all changes<br>made so far will take effect immediately.<br><br>Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y</pre><p>After this command, you will see a message that indicates the finish of the installation.</p><p>To connect to your root user from your localhost machine, you can run this command</p><pre>sudo mysql<br><br>Welcome to the MySQL monitor.  Commands end with ; or \g.<br>Your MySQL connection id is 11<br>Server version: 8.0.36-0ubuntu0.22.04.1 (Ubuntu)<br><br>Copyright (c) 2000, 2024, Oracle and/or its affiliates.<br><br>Oracle is a registered trademark of Oracle Corporation and/or its<br>affiliates. Other names may be trademarks of their respective<br>owners.<br><br>Type &#39;help;&#39; or &#39;\h&#39; for help. Type &#39;\c&#39; to clear the current input statement.<br><br>mysql&gt;   </pre><p>To exit from the MySQL terminal, you can run this command</p><pre>mysql&gt; exit;</pre><p>Congratulations! You have installed and configured the MySQL server on your Ubuntu machine. The next step is you can create a new database or new user for your MySQL server.</p><p>Thank you and stay coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ec794e84f7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring React Custom Context for Effective State Management]]></title>
            <link>https://rainerregan.medium.com/exploring-react-custom-context-for-effective-state-management-91be09fcec1c?source=rss-1e03268e6d1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/91be09fcec1c</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Rainer Regan]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 02:35:22 GMT</pubDate>
            <atom:updated>2023-08-22T02:35:22.230Z</atom:updated>
            <content:encoded><![CDATA[<p>When building complex React applications, managing state effectively becomes a critical task. While there are various state management libraries available, React’s built-in Context API offers a powerful solution to share states across components without resorting to prop drilling. In this article, we’ll delve into the concept of custom Context in React and learn how to harness its potential for better state management.</p><h4>Understanding React Context:</h4><p>React Context is a mechanism that allows data to be passed through the component tree without needing to pass props down manually at every level. It consists of two parts: the Provider and the Consumer. The Provider component wraps around a group of components and provides the data (state) that should be accessible to those components. The Consumer component can then access the provided data.</p><h4>Creating a Custom Context:</h4><p>Step 1: Create the Context</p><p>Start by creating a new JavaScript file, e.g., MyContext.js. In this file, import React and use the React.createContext() function to create your custom context.</p><pre>// MyContext.js<br>import React from &#39;react&#39;;<br><br>const MyContext = React.createContext();<br><br>export default MyContext;</pre><p>Step 2: Create the Provider:</p><p>In the same file, create a component that acts as the provider. This component will wrap around the components that need access to the context’s data.</p><pre>// MyContext.js<br>import React, { useState } from &#39;react&#39;;<br><br>const MyContext = React.createContext();<br><br>const MyProvider = ({ children }) =&gt; {<br>  const [data, setData] = useState(initialData);<br><br>  return (<br>    &lt;MyContext.Provider value={{ data, setData }}&gt;<br>      {children}<br>    &lt;/MyContext.Provider&gt;<br>  );<br>};<br><br>export { MyProvider, MyContext };</pre><p>Step 3: Wrap Components</p><p>In your main app file (e.g., App.js), wrap the components that need access to the custom context with the provider component.</p><pre>// App.js<br>import React from &#39;react&#39;;<br>import { MyProvider } from &#39;./MyContext&#39;;<br>import ComponentA from &#39;./ComponentA&#39;;<br>import ComponentB from &#39;./ComponentB&#39;;<br><br>const App = () =&gt; {<br>  return (<br>    &lt;MyProvider&gt;<br>      &lt;ComponentA /&gt;<br>      &lt;ComponentB /&gt;<br>    &lt;/MyProvider&gt;<br>  );<br>};<br><br>export default App;</pre><p>Step 4: Access Context Data</p><p>In the components that need to consume the context data, import the custom context and use the useContext Hook to access the provided data.</p><pre>// ComponentA.js<br>import React, { useContext } from &#39;react&#39;;<br>import { MyContext } from &#39;./MyContext&#39;;<br><br>const ComponentA = () =&gt; {<br>  const { data, setData } = useContext(MyContext);<br><br>  // Use data and setData here<br><br>  return &lt;div&gt;Component A&lt;/div&gt;;<br>};<br><br>export default ComponentA;</pre><p>React’s Custom Context API offers a clean and efficient way to manage the state that needs to be shared across multiple components. By creating a custom context, you can encapsulate specific states and logic, promoting modularity and reusability in your application. This approach simplifies the state management process and enhances the maintainability of your React projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91be09fcec1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an iOS Hand-drawing Recognition Augmented Reality App Using CoreML, Vision, ARKit, and…]]></title>
            <link>https://rainerregan.medium.com/building-an-ios-hand-drawing-recognition-augmented-reality-app-using-coreml-vision-arkit-and-cec600f6e605?source=rss-1e03268e6d1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cec600f6e605</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[scenekit]]></category>
            <category><![CDATA[arkit]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[coreml]]></category>
            <dc:creator><![CDATA[Rainer Regan]]></dc:creator>
            <pubDate>Wed, 31 May 2023 07:59:28 GMT</pubDate>
            <atom:updated>2023-05-31T07:59:28.552Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an iOS Hand-drawing Recognition Augmented Reality App Using CoreML, Vision, ARKit, and SceneKit.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2BwD_0ZeQlqW5DpKnLPH5A.png" /><figcaption>ARKit and CoreML Logo. The logo copyright belongs to Apple.</figcaption></figure><p>AR or augmented reality is one of the brightest and most fascinating technologies invented in the modern mobile engineering era. Augmented reality allows us to see seamlessly integrated computer-generated content, such as three-dimensional objects with the real world only using your mobile smartphone camera. This opens a lot of possibilities for new ideas that can be implemented in the mobile app development and games industry.</p><p>In the Apple ecosystem, there is a tool that gives access to developers to build an amazing AR app with ease. This tool, or we can call it a framework, is ARKit. Developed by Apple, ARKit is a powerful framework that empowers developers to create immersive and interactive AR applications for iOS devices.</p><p>Another great framework that is also developed by Apple is CoreML. Apple, renowned for its innovative ecosystem, introduced Core ML, a powerful framework that brings the potential of machine learning to its devices and empowers developers to create intelligent applications.</p><p>Core ML simplifies the integration of ML models into iOS, iPadOS, macOS, watchOS, and tvOS apps, making it accessible to developers without extensive ML expertise. It offers a wide range of pre-trained models covering areas like image recognition, natural language processing, and even complex tasks like object detection and sentiment analysis.</p><h4>Introduction</h4><p>In this article, we will focus on creating an iOS augmented reality that is integrated with the CoreML framework to detect the user’s hand drawing based on a trained machine learning model. For learning purposes, I have trained an ML model using the CreateML app from Apple to simplify the process of training an ML model. Also, this model will only accommodate six types or classes of trained hand-drawing patterns. These trained objects are trees, The Eiffel Tower, a bridge, a traffic light, a bus, and a car.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*Zan781dWZbwrbiONl3dXlw.png" /><figcaption>The example of the Eiffel Tower hand drawing was used for model training.</figcaption></figure><p>In this article, we will not focus on the ML training process, because it will be separated on another topic. Training a machine learning model will take a lot of time to do, so I have prepared a trained model that you can download here. This trained ML model was trained using 1500+ hand-drawing photos from Google’s QuickDraw <a href="https://github.com/googlecreativelab/quickdraw-dataset">dataset</a> that has been converted into image form before being processed inside the CreateML app. By using this model, we can save some time and be more focused on the development process.</p><h4>Prerequisites</h4><p>In this article, we will use MacOS 13.4+ with Xcode version 14.3 (14E222b). Also, it is required to have a physical iPhone device compatible with the Xcode version to test the AR app, because testing an AR app with the simulator is almost impossible. So, prepare your device and software, and we will start right away🔥.</p><p>If you want to skip reading and jump directly to the project, you can visit my GitHub repository here:</p><p><a href="https://github.com/rainerregan/HandDrawingRecognitionAR">https://github.com/rainerregan/HandDrawingRecognitionAR</a></p><h4>The Setup</h4><p>Before we do anything further, we need to create a new Augmented Reality app on Xcode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ppp7klaPO-9DSIyZQMUqA.png" /></figure><p>Let&#39;s start with “Hand Drawing Recognition AR”. We will be using Storyboard and SceneKit as the content technology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onzgcI_vm5dHcfIi5dGhUQ.png" /></figure><p>After the project is successfully created, Xcode will automatically create a boilerplate code for the sample app. We can take advantage of this sample project and improve it.</p><p>I want to make my code as clean as possible, so I will separate the delegate into an extension:</p><pre>//<br>//  ViewController.swift<br>//  Hand Drawing Recognition AR<br>//<br>//  Created by Rainer Regan on 27/05/23.<br>//<br><br>import UIKit<br>import SceneKit<br>import ARKit<br><br>class ViewController: UIViewController {<br><br>    @IBOutlet var sceneView: ARSCNView!<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        // Set the view&#39;s delegate<br>        sceneView.delegate = self<br>        <br>        // Show statistics such as fps and timing information<br>        sceneView.showsStatistics = true<br>        <br>        // Create a new scene<br>        let scene = SCNScene(named: &quot;art.scnassets/ship.scn&quot;)!<br>        <br>        // Set the scene to the view<br>        sceneView.scene = scene<br>    }<br>    <br>    override func viewWillAppear(_ animated: Bool) {<br>        super.viewWillAppear(animated)<br>        <br>        // Create a session configuration<br>        let configuration = ARWorldTrackingConfiguration()<br><br>        // Run the view&#39;s session<br>        sceneView.session.run(configuration)<br>    }<br>    <br>    override func viewWillDisappear(_ animated: Bool) {<br>        super.viewWillDisappear(animated)<br>        <br>        // Pause the view&#39;s session<br>        sceneView.session.pause()<br>    }<br><br>}<br><br>// MARK: - ARSCNViewDelegate<br>extension ViewController : ARSCNViewDelegate {<br>    func session(_ session: ARSession, didFailWithError error: Error) {}<br>}</pre><p>This is the example code of a starter SceneKit project. As you can see, ViewController is the main code section for this app, and we will be more focused on this file.</p><p>If we run this boilerplate code, we will see something like below. There is a default 3D model of a fighter jet anchored to the detected horizontal plane in the real world. You can try to interact with this default model by walking around the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2lK0ElnZ2iZHp_y-WbLUAg.png" /><figcaption>Your first AR application using AR Kit and SceneKit</figcaption></figure><p>Congratulations!! You have created your first AR application 🔥. But this is not what we aimed for in this article, we will make a much cooler AR app.</p><h4>The 3D Assets</h4><p>Thanks to some 3D artists on the internet, we can gather some 3D assets that we can use for the AR application. Based on the trained ML model I’ve mentioned before, we will be focusing on six classifications of objects: trees, The Eiffel Tower, a bridge, a traffic light, a bus, and a car. So, the 3D assets that we will be using are that objects.</p><p>To use the 3D models on SceneKit, the format of the model should be .uzdz . Usdz is a file format that is used on iOS apps, especially for AR. With this format, we can directly import the 3D model into the Xcode project without any issues.</p><p>I will use Sketchfab for my source of 3D models, and I will prefer to use free models available on Sketchfab for this project. Here is the list:</p><ul><li><a href="https://sketchfab.com/3d-models/japanese-bus-nagoya-city-bus-aichi-37c0a04a7aef4139b6aa037d17e768e5">Japanese bus “Nagoya City Bus” (Aichi) by VRC-IW</a></li><li><a href="https://sketchfab.com/3d-models/laurel-tree-low-poly-f1a5baa9d2e24f27a98be75f23f38f35">Laurel Tree — Low Poly by Alan Zimmerman</a></li><li><a href="https://sketchfab.com/3d-models/free-la-tour-eiffel-8553f94d06e24cb4b0fde1080f281674">( FREE ) La tour Eiffel by SDC PERFORMANCE™️</a></li><li><a href="https://sketchfab.com/3d-models/nyc-the-high-bridge-1a98cc4fe0064c009f4c2da35f0fc232">NYC, The High Bridge by 99.Miles</a></li><li><a href="https://sketchfab.com/3d-models/mazda-rx7-stylised-898e9be8c8964f6298188a2901216e80">Mazda RX7 Stylised by Sheldonj99</a></li><li><a href="https://sketchfab.com/3d-models/traffic-light-aeed7931c96a4428aa8ff71eb398ee43">Traffic Light by TomCalcoen</a></li></ul><p>You need to download all assets from the list above in order to continue building the AR app. Notes: you are not constrained to use those 3d models, you can use any models you want, but make sure the 3d models are in the same classification as the trained machine learning model. NOTE: Make sure to download 3D models as .usdz . And after that, rename each file to its respective classification name, e.g. Laurel_tree_---.usdz as tree.usdz</p><p>After you have downloaded and renamed the assets, you can drag and drop the assets directly into the project to import the assets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7LEC8dUWWqxr2L7w09Oxfg.png" /></figure><p>Make sure to tick “Copy items if needed” to copy the files into the project.</p><p>After importing files, your project structure would look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*_jOlXqz8ZKd2bUQKQeU48w.png" /><figcaption>Project structure after importing 3d files</figcaption></figure><h4>Creating UI</h4><p>After the 3D assets are imported, we need to create the basic interface for the scanning session. We need a debug text for displaying the detected classification and the reset button for cleaning the virtual world from deployed 3d models.</p><p>So, we can start by modifying the Main screen on the storyboard. The component we need is a label and a button. Also, to make our app more interactive, we can add a ‘crosshair’ image on the center of the screen to make user easier to scan their hand drawing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drg3mO8GMFIabLc19FUjGA.png" /><figcaption>Default main screen</figcaption></figure><p>We can start by opening the main screen storyboard and you can see the default layout of this main page. We won’t jump into details on how to modify the UI, we only need to add some basic components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*u75j3512U3ueAuhh5Hob2Q.png" /><figcaption>Adding a label to the page</figcaption></figure><p>Firstly, we need to add a label on the page and center it horizontally and add some spacing from the top of the safe area. After that, we can link the component to the ViewController by dragging the label component from the structure tree while holding the ‘control’ key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*KRNAKl7F7mmZY8wN32mVZw.png" /><figcaption>Connect the component to ViewController</figcaption></figure><p>We will name this component ‘debugText’. In ViewController, the code should look like this:</p><pre><br>class ViewController: UIViewController {<br>  // ...<br><br>    @IBOutlet weak var debugText: UILabel!<br><br>  // ...<br>}</pre><p>We will create another component, and also link it to the ViewController, this time, we will add a Button, and connect this to the ViewController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*JeRlrPFlkSX0C6aPakNDBw.png" /></figure><p>Besides connecting, we also want to create the button action to handle the reset function. For this, leave this empty with the only print function.</p><pre><br>class ViewController: UIViewController {<br><br>  // ..<br>    @IBOutlet weak var resetButton: UIButton!<br>    <br>    @IBAction func resetButtonAction() {<br>        print(&quot;Reset&quot;)<br>    }<br><br>  // ...<br>}</pre><p>Another thing, we need to lock the device orientation to portrait, so the UI will not break. Inside the viewDidLoad() function, we need to add this code:</p><pre>// Lock the device orientation to the desired orientation<br>UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: &quot;orientation&quot;)</pre><p>So the whole viewDidLoad function would look like this:</p><pre>override func viewDidLoad() {<br>    super.viewDidLoad()<br>    <br>    // Lock the device orientation to the desired orientation<br>    UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: &quot;orientation&quot;)<br>    <br>    // Set the view&#39;s delegate<br>    sceneView.delegate = self<br>    <br>    // Show statistics such as fps and timing information<br>    sceneView.showsStatistics = true<br>    <br>    // Create a new scene<br>    let scene = SCNScene(named: &quot;art.scnassets/ship.scn&quot;)!<br>    <br>    // Set the scene to the view<br>    sceneView.scene = scene<br>}</pre><p>By using this code, our orientation will not change even though the iPhone is rotated sideways.</p><p>Not only that, inside the ViewController class, add more functions to force the orientation of the application.</p><pre>override var supportedInterfaceOrientations: UIInterfaceOrientationMask {<br>    // Specify the supported orientations (in this case, only portrait)<br>    return .portrait<br>}<br><br>override var shouldAutorotate: Bool {<br>    // Disable autorotation<br>    return false<br>}</pre><h4>The Tap Gesture</h4><p>In this article, we will use <strong>raycasting </strong>to display the 3D model in the virtual AR world. To implement this, we need to set the handleTap function on the AR kit.</p><p>Firstly, create a handleTap function inside the ViewController class.</p><pre><br>@objc func handleTap(gestureRecognizer : UITapGestureRecognizer) {<br>    /// Create a raycast query using the current frame<br>    if let raycastQuery: ARRaycastQuery = sceneView.raycastQuery(<br>        from: gestureRecognizer.location(in: self.sceneView),<br>        allowing: .estimatedPlane,<br>        alignment: .horizontal<br>    ) {<br>        // Performing raycast from the clicked location<br>        let raycastResults: [ARRaycastResult] = sceneView.session.raycast(raycastQuery)<br>        <br>        print(raycastResults.debugDescription)<br>        <br>        // Based on the raycast result, get the closest intersecting point on the plane<br>        if let closestResult = raycastResults.first {<br>            /// Get the coordinate of the clicked location<br>            let transform : matrix_float4x4 = closestResult.worldTransform<br>            let worldCoord : SCNVector3 = SCNVector3Make(transform.columns.3.x, transform.columns.3.y, transform.columns.3.z)<br>            <br>            /// Load 3D Model into the scene as SCNNode and adding into the scene<br>            // TODO: Later, We will load the 3D model on the raycasted location.<br>        }<br>    }<br><br>    <br>}</pre><p>From the function, firstly we need to create a ray cast query from the gesture recognition of the sceneView, to the estimated plane located on the SceneKit environment, and in this case, we will only detect the horizontal plane.</p><p>From that query, we will be getting a result containing the transformation on the ray cast target on the estimated plane. From that, we will extract the transformation in the form of a 4x4 float matrix and the world coordinates. Later, we will load and display the selected 3D model onto that location and transformation.</p><p>After creating the handleTap function, inside the viewDidLoad method, create a new UITapGestureRecognizer, and assign it to the view.</p><pre><br>// Set the tap gesture recognizer<br>let tapGesture = UITapGestureRecognizer(<br>    target: self,<br>    action: #selector(self.handleTap(gestureRecognizer:))<br>)<br>view.addGestureRecognizer(tapGesture)</pre><h4>AR Configuration</h4><p>We need to specify the preferred plane to be detected by the AR, so we need to adjust the configuration on the viewWillAppear method, this time we need to add this code under the initialization of configuration.</p><pre>// Create a session configuration<br>let configuration = ARWorldTrackingConfiguration()<br>configuration.planeDetection = [.horizontal]</pre><h4>The Machine Learning</h4><p>After setting up the AR, we can start focusing on the more exciting stuff, machine learning. In this article, we will be using a pre-trained model, so we don&#39;t have to go through all tiring model training sessions. You can download the machine learning model from the <a href="https://github.com/rainerregan/HandDrawingRecognitionAR">GitHub repository.</a></p><p>First, create a new group named ‘Model’ at the root of the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*cLIjrrV4dzYt3gXdbjS7nA.png" /></figure><p>After that, import the file into the group by drag-and-dropping the file directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*O0no2OjtgNmCz1UnBK9rhA.png" /></figure><p>The model is not integrated with the project and is ready to use. By doing this we can now start to integrate it with our code.</p><p>After that, we can import the data model into our view controller. We need to create new variables.</p><pre>/// The ML model to be used for recognition of arbitrary objects.<br>private var _handDrawingModel: HandDrawingModel_v4!<br>private var handDrawingModel: HandDrawingModel_v4! {<br>    get {<br>        if let model = _handDrawingModel { return model }<br>        _handDrawingModel = {<br>            do {<br>                let configuration = MLModelConfiguration()<br>                return try HandDrawingModel_v4(configuration: configuration)<br>            } catch {<br>                fatalError(&quot;Couldn&#39;t create HandDrawingModel due to: \(error)&quot;)<br>            }<br>        }()<br>        return _handDrawingModel<br>    }<br>}</pre><p>This code will import the hand drawing machine learning model we have copied before, and store it inside a variable.</p><p>After the model is present in our code, we can start using that. Inside the ViewController, create new functions to handle the classification request and create a handler function to handle the result.</p><p>Under the handleTap function, create a new function for creating classification requests like below.</p><pre>private lazy var classificationRequest: VNCoreMLRequest = {<br>    do {<br>        // Instantiate the model from its generated Swift class.<br>        let model = try VNCoreMLModel(for: handDrawingModel.model)<br>        let request = VNCoreMLRequest(model: model, completionHandler: { [weak self] request, error in<br>            self?.classificationCompleteHandler(request: request, error: error)<br>        })<br>        <br>        // Crop input images to square area at center, matching the way the ML model was trained.<br>        request.imageCropAndScaleOption = .centerCrop<br>        <br>        // Use CPU for Vision processing to ensure that there are adequate GPU resources for rendering.<br>        request.usesCPUOnly = true<br>        <br>        return request<br>    } catch {<br>        fatalError(&quot;Failed to load Vision ML model: \(error)&quot;)<br>    }<br>}()</pre><p>This method will handle the classification request from the AR camera and process it using Vision to get the classification result using the Machine Learning model. This method will also call the callback function to process the classification result. So, we need to create another method, this time it will be called classificationCompleteHandler.</p><pre>func classificationCompleteHandler(request: VNRequest, error: Error?) {<br>    guard let results = request.results else {<br>        print(&quot;Unable to classify image.\n\(error!.localizedDescription)&quot;)<br>        return<br>    }<br>    <br>    // The `results` will always be `VNClassificationObservation`s, as specified by the Core ML model in this project.<br>    let classifications = results as! [VNClassificationObservation]<br>    <br>    // Show a label for the highest-confidence result (but only above a minimum confidence threshold).<br>    if let bestResult = classifications.first(where: { result in result.confidence &gt; 0.5 }),<br>        let label = bestResult.identifier.split(separator: &quot;,&quot;).first {<br>        identifierString = String(label)<br>        confidence = bestResult.confidence<br>    } else {<br>        identifierString = &quot;&quot;<br>        confidence = 0<br>    }<br>    <br>    DispatchQueue.main.async { [weak self] in<br>        self?.displayClassifiedResult()<br>    }<br>}</pre><p>This function will handle the result sent by classification request. This function will extract the result and save the best result with the best confidence into a class-level variable. So we need to create it first.</p><pre><br>class ViewController: UIViewController {<br><br>  // ...<br>  <br>  /// A  variable containing the latest CoreML prediction<br>  private var identifierString = &quot;&quot;<br>  private var confidence: VNConfidence = 0.0<br>  private let dispatchQueueML = DispatchQueue(label: &quot;com.exacode.dispatchqueueml&quot;) // A Serial Queue<br>  private var currentBuffer : CVImageBuffer?<br><br>  //...<br>}</pre><p>The identifier string will be storing the latest prediction result in the form of a string. The confidence will be storing the confidence level of the latest prediction. The dispatchQueue is a variable for creating a queue for machine learning requests. The current buffer will store the latest frame buffer from the sceneView before being passed into the ML request.</p><p>Next, we need to create a function to pass the image buffer from that captured frame of a sceneView to the machine learning request. This function will act as a bridge function before passing into the ML request.</p><pre>func classifyCurrentImage() {<br>    let orientation = CGImagePropertyOrientation(UIDevice.current.orientation)<br>    <br>    let imageRequestHandler = VNImageRequestHandler(<br>        cvPixelBuffer: currentBuffer!,<br>        orientation: orientation<br>    )<br>    <br>    // Run Image Request<br>    dispatchQueueML.async {<br>        do {<br>            // Release the pixel buffer when done, allowing the next buffer to be processed.<br>            defer { self.currentBuffer = nil }<br>            try imageRequestHandler.perform([self.classificationRequest])<br>        } catch {<br>            print(error)<br>        }<br>    }<br>}</pre><p>To get the orientation for the captured frame, we need to create a new Utility file called ‘Utilities’ to extend the CGImagePropertyOrientation.</p><p>Create a new group called Support, and inside, create a file called Utilities.</p><pre>import Foundation<br>import ARKit<br><br>// Convert device orientation to image orientation for use by Vision analysis.<br>extension CGImagePropertyOrientation {<br>    init(_ deviceOrientation: UIDeviceOrientation) {<br>        switch deviceOrientation {<br>        case .portraitUpsideDown: self = .left<br>        case .landscapeLeft: self = .up<br>        case .landscapeRight: self = .down<br>        default: self = .right<br>        }<br>    }<br>}</pre><p>So in the short term, we will capture each frame of the AR view from the sceneView and send the image buffer to the opening function before passing it again into the machine learning request.</p><p>This is optional, but for giving information to the user about what machine learning has detected, we can create one more function to display the result to the debug text and console.</p><pre>func displayClassifiedResult() {<br>    // Print the clasification<br>    print(&quot;Clasification: \(self.identifierString)&quot;, &quot;Confidence: \(self.confidence)&quot;)<br>    print(&quot;---------&quot;)<br>    <br>    self.debugText.text = &quot;I&#39;m \(self.confidence * 100)% sure this is a/an \(self.identifierString)&quot;<br>}</pre><p>This function will be called from the classifyCurrentImage function and display the classification result in the console and label on the UI.</p><h4>Starting the Classification Process</h4><p>To start the classification request we need to call it every frame is updated. To do this, we need to create an extension from the ViewController class and implement ARSessionDelegate.</p><p>Inside the delegate, create a session function to track the frame update.</p><pre><br>// MARK: - ARSessionDelegate<br>extension ViewController: ARSessionDelegate {<br>    func session(_ session: ARSession, didUpdate frame: ARFrame) {<br>        guard currentBuffer == nil, case .normal = frame.camera.trackingState else {<br>            return<br>        }<br>        <br>        // Retain the image buffer for Vision processing.<br>        self.currentBuffer = frame.capturedImage<br>        classifyCurrentImage();<br>    }<br>}</pre><p>On the viewDidLoad function, set the session delegate to itself</p><pre>sceneView.session.delegate = self</pre><p>After that, create a function to restart the ar session and start the classification process.</p><pre>// MARK: - Restart Session and Rerun AR<br>private func restartSession() {<br>    let configuration = ARWorldTrackingConfiguration()<br>    configuration.planeDetection = [.horizontal, .vertical]<br>    sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])<br>}</pre><p>On the viewDidLoad function, on the bottom, call the function.</p><pre>override func viewDidLoad() {<br>  // ...<br><br>  // Start the scanning session<br>  self.restartSession()<br>}</pre><p>With this, you can now see the classification result from the label text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4zkgyXqz-w0TB53vz9yWA.png" /></figure><p>Congratulation! you have created the image classification using an AR camera, now we can focus on displaying the 3D model.</p><p>Displaying the 3D Model</p><p>Now, after the ML prediction is completed, we can now focus on displaying the 3D model.</p><p>First, we need to create a function to determine which 3D model should be loaded based on the prediction data. Inside the ViewController class, create one more function.</p><pre>func loadNodeBasedOnPrediction(_ text: String) -&gt; SCNNode? {<br>    guard let urlPath = Bundle.main.url(/service/forresource: text.trimmingCharacters(in: .whitespacesAndNewlines), withExtension: &quot;usdz&quot;) else {<br>        return nil<br>    }<br>    let mdlAsset = MDLAsset(url: urlPath)<br>    mdlAsset.loadTextures()<br>    <br>    let asset = mdlAsset.object(at: 0) // extract first object<br>    let assetNode = SCNNode(mdlObject: asset)<br>    assetNode.scale = SCNVector3(0.001, 0.001, 0.001)<br><br>    return assetNode<br>}</pre><p>This function will take a parameter of a predicted hand-drawing image and display the assets based on the classification.</p><p>For this function, we will be using the SCNNode from SceneKit ModelIO, so we need to import it.</p><pre>// Other imports<br>import SceneKit.ModelIO</pre><p>Back to handleTap function, call this function whenever the screen is tapped.</p><pre>@objc func handleTap(gestureRecognizer : UITapGestureRecognizer) {<br>        <br>    /// Create a raycast query using the current frame<br>    if let raycastQuery: ARRaycastQuery = sceneView.raycastQuery(<br>        from: gestureRecognizer.location(in: self.sceneView),<br>        allowing: .estimatedPlane,<br>        alignment: .horizontal<br>    ) {<br>        // Performing raycast from the clicked location<br>        // ...<br>        <br>        // Based on the raycast result, get the closest intersecting point on the plane<br>        if let closestResult = raycastResults.first {<br>            /// Get the coordinate of the clicked location<br>            // ...           <br><br>            /// Load 3D Model into the scene as SCNNode and adding into the scene<br>            guard let node : SCNNode = loadNodeBasedOnPrediction(identifierString) else {return}<br>            sceneView.scene.rootNode.addChildNode(node)<br>            node.position = worldCoord<br>        }<br>    }<br>}</pre><p>As you can see, we will create a SCNNode on every click on the view, and call the loadNodeBasedOnPrediction method to get the right 3D model. After that, we will assign the node to the scene and set its position based on the raycast result.</p><h4>Testing The Result</h4><p>To test the result of what we have created before, take a piece of paper and draw one of these objects: a tree, the Eiffel Tower, a bridge, a traffic light, a car, or a bus. After that, start the application and point your camera to the hand drawing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mXJcpCGLRMMadm8rpIY2_g.png" /><figcaption>A tree is placed on the hand drawing.</figcaption></figure><p>Congratulations !!! 🎉 👏 You have created an AR application that can detect your hand drawing!</p><h4>Optional: Reset Button</h4><p>This is an optional step and will not affect the main function of this app. This step will explain the implementation of the reset button and clear the virtual world of any placed objects.</p><p>To start, modify the IBAction we have created before to this code:</p><pre>@IBAction func resetButtonAction() {<br>    print(&quot;Reset&quot;)<br>    guard let sceneView = sceneView else {return}<br>    sceneView.scene.rootNode.enumerateChildNodes { (node, stop) in<br>    node.removeFromParentNode() }<br>}</pre><p>And re-run the application. You will be able to reset the world.</p><h4>Conclusion</h4><p>Congratulations on your first app on integrating AR and Machine Learning. This article is only covering a small number of possibilities that you can create with this technology. It is fascinating that Apple developed these cool frameworks. Now it’s your turn to create cooler applications using these frameworks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cec600f6e605" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>