teleren/devto huggingface dataset:
Automatically Updating Podman Containers
Tags: linux, containers
Published: 2023-01-06 03:01:49

---
title: Automatically Updating Podman Containers
published: true
date: 2022-05-16 02:20:47 UTC
tags: Linux,Containers
canonical_url: https://brandonrozek.com/blog/auto-updating-podman-containers/
---

Recently, I have been [transitioning to Podman](/blog/rootless-docker-compose-podman) for running my container infrastructure. In the process, I brought over Watchtower which I have previously used for auto-updating docker containers. Before doing so, I didn’t check its [compatibility](https://github.com/containrrr/watchtower/issues/1060) (whoops) and found a few of my containers would every other week or so not come back up.

I then remembered that I restart my server for general system updates almost every day. What if I perform the podman container updates on start up? After modiyfing my systemd service to include an extra field called `ExecStartPre` and removing Watchtower, I found no more missing containers! The field `ExecStartPre` performs a pull (update) before starting up the containers via `ExecStart`.

```
[Unit]
Description=Docker Compose Application Service
Requires=network.target podman.socket
After=network.target podman.socket

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/home/brandonrozek
ExecStartPre=/usr/bin/docker-compose pull
ExecStart=/usr/bin/docker-compose up -d --force-recreate
ExecStop=/usr/bin/docker-compose down
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target

```
Databases
Published: 2022-05-16 01:46:02

**What is a database?**

A database is a collection of data. Its organized to structure information that is usually controlled by a database management system or refered to as DBMS. The most common type of database is typically modeled in rows and columns in. a series of tables to make processing and data query efficient. Most databases use Structured Query Language(SQL) for writing and querying data.

**What is Structured Query Language(SQL)?**

SQL is a programming language used by relational databases to query, manipulate, define data, and to provide access control. The data is stored in database objects that's called tables. A table is a collection of related data entries and it consists of columns and rows.

Let's have a table called Customers. The following example is to look at the "Customers" table:

```SQL
SELECT * FROM Customers;
```
The keyword "SELECT" means to get access to the following table. "*" means for all the columns, "FROM" keyword is to refer to which table you want and Customers is the table. So all together the statement is saying we select to see all the columns from the table Customers.

Every table is broken up into smaller entities called fields. A field is a column in a table that is designed to contain information about every record in the table. There is also a row sometimes refer to as a record. A row is each indivdual entry that exist in a table. Think in the Customers table. A record is a horizontal entity in a table. A column is a vertical entity in a table that contains all information within a specific field in a table.
Building a simple invoice generator with Node Js
Tags: javascript, invoice, node
Published: 2022-05-16 01:05:51

## Why ❓🤔
After each online coaching sessions, at the beginning, that was a pain to find a good invoice generator platform as I was not yet ready for a 20€ monthly subscription just for handling the invoice part.

None was enough flexible for my own use 🙄 so.. I decided to build my own mini-invoice generator with Node Js ✅  ( that took approx 1h max ⌛️ )

No more talk..Straight to the point 💪🏼

## The main parts ⚙️:
**1. Storing clients in Json :**

Yep that one is simple..for now x)

(Note: these are fictional characters of course 😝 )

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0gnyioxr8sy7ejpc6vpc.png)
 

**2. Creating the route:**
Using express router, just create a POST /invoice route.
`const router = express.Router();
router.post('/', handleCreateInvoice);`

Then add the Joi Schema. Why ? It allows to define schema and validate the schema before calling the controller/handler of invoice creation.

Source: [https://joi.dev/](https://joi.dev/)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xk2v6ozy0re90kopt37w.png)
 

**3. Handling the invoice creation:**

I used the module pdf-kit to generate the pdf to be sent to the client.

[pdf-kit](https://www.npmjs.com/package/pdfkit)

 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p2ljzpqc4ez1ahvufozd.png)

**4. Email sending:**
A small function using `gmail-send` npm module which accepts html as an input ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sc5u2yfjk3c842t9s8zg.png)
 

## Yep..so what about the result ?

A snapshot of my first trials ^^  ( yep that email should be more personnalized and better structure 😊 )

Insomnia POST Call
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sz2uh52175rtsk419eav.png)
 
Final result 😁
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sshpxoh9v56ff0dlnfox.png)

**<u>The pdf:</u>**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c28gnrayf3qcn4awmst2.png)
 


## Next steps:
- Front-end ( React 🤔 ) 
- Database 💿
- make it online x)
- Iterate 👀

## And you 💪🏼? 
Tell us in the comments which mini-project you built 👀😊

## Wanna support me ?
I am blogging during my free time ^^ like most people on this platform 😊 however I'm not against a small coffee if you want to support me 💪🏼 Link below:

[https://ko-fi.com/dev_it_out](https://ko-fi.com/dev_it_out)


P.S: I added the sample on Github ( [https://github.com/njivaolafpro/invoice-management-sample](https://github.com/njivaolafpro/invoice-management-sample)
What's your most used JavaScript framework?
Tags: javascript, webdev, discuss, react
Published: 2022-05-16 00:36:53

Most of the web developers tend to use JavaScript frameworks rather than using vanilla JavaScript. So, what's the one JavaScript framework you have got hooked into, what's your most used JavaScript framework and what made you stick to it?

For me, the framework is **React**, it's the framework I started with initially and then eventually moved on to **Next.js**, I have used react in most of my projects and now I'm trying out **Vue.js**.
How to easily make a new type by removing or excluding certain values from a union type in TypeScript?
Tags: typescript
Published: 2022-05-16 00:00:00

---
  title: How to easily make a new type by removing or excluding certain values from a union type in TypeScript?
  published: true
  tags: TypeScript
  date: Mon May 16 2022 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/easily-make-new-type-remove-certain-values-from-union-type-typescript
  cover_image: https://melvingeorge.me/_next/static/images/main-98298b2d49d7896115bd56eb02027ff7.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/easily-make-new-type-remove-certain-values-from-union-type-typescript)
  
To easily make a new type by removing or excluding certain values from a union type in TypeScript, you need to use the `Exclude` utility type and pass the union type to remove the values from as its first type argument, and the union type composed of values to remove or a string if only single value as its second type argument.

### TL;DR

```ts
// a simple union type
type AcceptedValues = "Hello" | "Hi" | 43 | true;

// make a new type by removing the values of `43`
// and `true` using the `Exclude` utility type
type RefinedTypes = Exclude<AcceptedValues, 43 | true>; // "Hello" | "Hi"
```

For example, let's say we have a union type called `AcceptedValues` which is composed of values like `Hello`, `Hi`, `43` and true like this,

```ts
// a simple union type
type AcceptedValues = "Hello" | "Hi" | 43 | true;
```

Now to make a new type by removing the values of `43` and `true`, we can use the `Exclude` utility type and pass the `AcceptedValues` type as its first type argument, and the union type composed of `43` and `true` as its second argument type.

It can be done like this,

```ts
// a simple union type
type AcceptedValues = "Hello" | "Hi" | 43 | true;

// make a new type by removing the values of `43`
// and `true` using the `Exclude` utility type
type RefinedTypes = Exclude<AcceptedValues, 43 | true>; // "Hello" | "Hi"
```

Now if you hover over the `RefinedTypes` type in an editor or look into the contents of the type, you can see that the values `43` and `true` are excluded and only the `Hello` and `Hi` values are present in it.

We have successfully made a new type by excluding certain values from the union type in TypeScript. Yay 🥳!

See the above code live in [codesandbox](https://codesandbox.io/s/easily-make-new-type-remove-certain-values-from-union-type-typescript-ng5p01?file=/src/index.ts).

That's all 😃!

### Feel free to share if you found this useful 😃.

---
How to implement horizontal media scroller component in React with CSS only
Tags: nextjs, react, webdev
Published: 2022-05-16 12:53:56

---
title: How to implement horizontal media scroller component in React with CSS only
published: true
date: 2022-05-16 00:00:00 UTC
tags: nextjs,react,webdev
canonical_url: https://bstefanski.com/implement-horizontal-media-scroller-component-react-css
---

It is a common practice to render list in form of horizontal swipeable carousel on mobile resolutions. For that I created a simple, almost no-JS component for that. It uses JavaScript only for centering the overflow container.

![A preview of media scroller component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/htco7nyjndadd9qyn8eg.png)
 

I used [`styled-components`](https://styled-components.com/) and [`styled-breakpoints`](https://github.com/mg901/styled-breakpoints) for this, but you can easily transform this to any other CSS-in-JS approach.

```jsx
import { Container } from 'components/Container';  
import { useEffect, useRef } from 'react';  
import { down } from 'styled-breakpoints';   
import styled from 'styled-components';  
  
const GridContainer = styled(Container)`  
  ${down('sm')} {  
    max-width: 100%;  
    margin: unset;  
    padding: 0;  
  }  
`;  
  
const Grid = styled.div<{ desktopMinWidth: string; mobileMinWidth: string }>`  
  display: grid;  
  grid-template-columns: ${({ desktopMinWidth }) => `repeat(auto-fill, minmax(${desktopMinWidth}, 1fr))`};  
  grid-gap: 18px;  
  
  ${down('sm')} {  
    padding: 0 20px;  
    position: relative;  
  
    cursor: grab;  
    scrollbar-width: none;  
    -ms-overflow-style: none;  
  
    ::-webkit-scrollbar {  
      width: 0px;  
      background: transparent;  
    }  
  
    display: flex;  
    overflow-x: auto;  
    scroll-snap-type: x mandatory;  
    -webkit-overflow-scrolling: touch;  
  
    & > * {  
      min-width: ${({ mobileMinWidth }) => mobileMinWidth};  
      max-width: ${({ mobileMinWidth }) => mobileMinWidth};  
      scroll-snap-align: center;  
    }  
  }  
`;  
  
interface SwipeableGridProps {  
  mobileMinWidth: string;  
  desktopMinWidth: string;  
  children: React.ReactNode;  
  className?: string;  
}  
  
export const SwipeableGrid = ({  
  mobileMinWidth,  
  desktopMinWidth,  
  children,  
  className,  
}: SwipeableGridProps) => {  
  const swipeableGridRef = useRef<HTMLDivElement | null>(null);  
  
  useEffect(() => {  
    const currentEl = swipeableGridRef.current;  
    if (currentEl) {  
      currentEl.scrollLeft = currentEl.clientWidth / 2;  
    }  
  }, []);  
  
  return (  
    <GridContainer>   
      <Grid  
        desktopMinWidth={desktopMinWidth}  
        mobileMinWidth={mobileMinWidth}  
        ref={swipeableGridRef}  
        className={className}  
      >  
        {children}  
      </Grid>  
    </GridContainer>  
  );  
};
```
NextCloud/S3/Latency for fellow chief information officers
Tags: opensource, aws
Published: 2022-05-15 23:00:03

As the chief information officer ;) for my self-hosted NextCloud instance, one of my primary responsibilities is to ensure that the network infrastructure is performant and cost-effective. 

This is especially true if your use S3 storage with your NextCloud instance. In my case, I am using Wasabi S3.

Wasabi S3 provides reliable storage and a highly competitive rate. So I knew that I did well as the chief information officer of my one-person show.

However, my NextCloud instance is located in Sydney, and the Wasabi S3 bucket is hosted in the US. My users are based down-under, and Wasabi S3 did not have a data center in Australia. As you can imagine, this did not boast well for the performance side of things since the latency was not great. Even minor delays in transmission can cause significant reductions in usability.

Thankfully Wasabi S3 opened a new data center in Sydney, so I can fulfill my duty to ensure NextCloud is performant.

Read this post to see my test results from AWS and my local ISP: 
https://anto.online/tips-and-tools/wasabi-s3-speed-test-results-from-sydney-australia/

I have now decided to move my data from the US and Australia. This is guaranteed to improve latency and help boost performance for all my users.
Winning Card (DSA Series)
Tags: datastructure, algorithms, javascript
Published: 2022-05-15 22:44:34

---
title: Winning Card (DSA Series)
published: true
description: Part 4 of Data Structure and Algorithm problem solving series.
tags: DataStructure, Algorithms, Javascript
//cover_image: https://direct_url_to_image.jpg
---
## Problem
Winning Card
In a card game, each player will be given a set of random cards. Players will throw on the table their one winning card, the player with the highest card wins.

**A winning card is the card that only exists once in the set of cards, and the highest one.**

Given an array of sets of integers cards, return the card of the winning player. Return -1 If no such card is found.

* Example 1:
* Input: cards = [[5,7,3,9,4,9,8,3,1], [1,2,2,4,4,1], [1,2,3]]
* Output: 8

* Example 2:
* Input: cards = [[5,5], [2,2]]
* Output: -1

## Solution

 * Loop through the 2 dimensional array,
 * On second loop, if item exist in hashset, delete prev occurence of i. Else add to hashset
 * loop through hashset for the highest number
 
```javascript
function winningCard(multiArray) {
    let map = new Set();
    multiArray.forEach(item => {
        for (let i = 0; i < item.length; i++) {
            if (map.has(item[i])) {
               map.delete(item[i])
            } else map.add(item[i])
        }
    })

    if (map.size === 0) return -1;

    let highest = 0;
    for (let i of map) {
        if(i > highest) {
            highest = i
        }
    }

   return highest;
}
```

Anyway, if you have a better way of solving this, you can drop your solution in the comments. I'm no expert. Just learning aloud.

Don't forget to like, share and drop a comment. :)
NPM Library to get a list of WordPress posts' character counts using the WP REST API
Tags: javascript, wordpress, wprestapi, npm
Published: 2022-05-15 22:40:46

## NPM Library to get a list of WordPress posts' character counts

I have created an npm library to retrieve the character count of all articles published on WordPress using the REST API provided by WordPress.
The name is `wp-rest-api-posts-wordcount`.

Check the GitHub repository for details.
https://github.com/shinshin86/wp-rest-api-posts-wordcount

Installation and code examples are as follows.

Install:

```sh
npm install wp-rest-api-posts-wordcount
# or
yarn add wp-rest-api-posts-wordcount
```

Example:

```javascript
const getWordcountList = require('wp-rest-api-posts-wordcount');

(async () => {
  try {
    const response = await getWordcountList('your wordpress url');
    console.log(response);
  } catch (e) {
    console.error(e);
  }
})();
```

## What is WP REST API?
To briefly explain the WP REST API used in this library, WordPress provides the following endpoints for REST APIs.

https://developer.wordpress.org/rest-api/

This can be disabled on the WordPress side, but is probably currently enabled by default if you have not made any changes to your settings.

This REST API can be used to retrieve information about published articles.

For example, you can check the value `x-wp-total` in the response header to get the number of target WordPress pages, etc.
You can use it in various ways, so it would be interesting to read this document once.
(I actually use `x-wp-total` in my npm library)

### Code sample using WP REST API

Here is where the WP REST API is actually used in `wp-rest-api-posts-wordcount`.

This shows that it is very easy to use the WP REST API.

```typescript
const targetUrl = `${url}/wp-json/wp/v2/posts`;
const response = await fetch(targetUrl);
const wpTotalPageCount: number = response.headers.get('x-wp-total');
```

It is possible to retrieve information about public posts by sending a request to the endpoint `your_wordpress_url/wp-json/wp/v2/posts` like this.

`response.headers.get('x-wp-total')` to get the number of pages in WordPress.

From this sample, you can see that this API is easy to use.

Various information can be found by checking the official documentation.

Let's build all sorts of useful tools using the WP REST API!
The infamous Two Sum problem. (DSA Series 3)
Tags: datastructure, algorithms, javascript
Published: 2022-05-15 22:34:45

---
title: The infamous Two Sum problem. (DSA Series 3)
published: true
description: Part 3 of Data Structure and Algorithm problem solving series.
tags: DataStructure, Algorithms, Javascript
//cover_image: https://direct_url_to_image.jpg
---
## Problem

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

 * Example
 * Input: nums = [2,7,11,15], target = 9 
 * Output: [0,1]
 * Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
 * Input: nums = [3,2,4], target = 6
 * Output: [1,2]
 * Input: nums = [3,3], target = 6
 * Output: [0,1]

 


## Solution

 * THIS WILL ONLY WORK IF ITEMS ARE SORTED
 * let there be two pointers, one point to the beginning of array (low), and the other to the end of array (high).
 * while low < high,
 * if the sum of the value at low and high = target, return the indices
 * if the sum of the values at low and high > target, reduce high index by 1
 * if the sum of the values at low and high < target, increase the low by 1
```javascript
function twoSum(array, target){
    let low = 0;
    let high = array.length - 1;

    while (low < high) {
        const sum = array[low] + array[high];
        if (sum === target) return [low, high];
        if (sum > target) high--;
        else if (sum < target) low++;
    }
}
```

Method Two
```javascript
/**
 * 
 * Input: nums = [2,7,11,15], target = 9 
 * Output: [0,1]
 * Initialize a map,
 * loop through array, 
 * subtract currentItem from target to get compliment, 
 *  if compliment exist in map, return [currentItmIdx, compliment[]]
 * else add map[curentItem] = idx
 * @param {*} array 
 * @param {*} target 
 */
function twoSumMethod2(array, target){
    const map = {};

    for (let i = 0; i < array.length; i++) {
        let com = target - array[i];
        if(map[com] !== undefined) return [i, map[com]]
        else map[array[i]] = i;
    }
    return -1
}
```
### Test Examples
const nums = [2,7,11,15], target = 9;
const nums = [3,3], target = 6

-

Anyway, if you have a better way of solving this, you can drop your solution in the comments. I'm no expert. Just learning aloud.

Don't forget to like, share and drop a comment. :)
Day 6,7/100 complete
Tags: beginners, programming, 100daysofcode
Published: 2022-05-15 22:34:41

#100DaysOfCode Day 6,7 of 100 complete. Forgot to post my update on Friday and Saturday. So far, those have been the most difficult days to complete the challenge since it’s the weekend and things get planned. Currently now learning C language to learn the fundamentals. Practicing in a sandbox through the CS50 course on basic instructions. I’ll be posting another update tonight for day 8.
Group Anagram. (DSA Series 2)
Tags: datastructure, algorithms, javascript
Published: 2022-05-15 21:59:27

---
title: Group Anagram. (DSA Series 2)
published: true
description:  Part 2 of Data Structure and Algorithm problem solving series.
tags: DataStructure, Algorithms, Javascript
//cover_image: https://direct_url_to_image.jpg
---

## Problem

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
 * Example
 * Input: strs = ["eat","tea","tan","ate","nat","bat"]
 * Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
 * 
 * Input: strs = [""]
 * Output: [[""]]
 * 
 * Input: strs = ["a"]
 * Output: [["a"]]
 */

### Solution
```javascript

/**
 * for each item in array, sort alphabetically, then add sorted item to map as key, push index to value array eg; {aet:[0,1,3], ...}
 * return values of every word(key) in the map as an array.
 * Time Complexity is O(n)... I think. _Not sure if the sorting of each word takes an additional O(n)_ 
 */
function groupAnagram(arr){
    const map = {}
    for(let i = 0; i < arr.length; i++) {
       const sortedWord = [...arr[i] ].sort((a,b)=> a.localeCompare(b)).join();
       map[sortedWord] = map[sortedWord] !== undefined ? [...map[sortedWord], arr[i]] : [arr[i]]
    }
    
    return Object.values(map);
}
```

Anyway, if you have a better way of solving this, you can drop your solution in the comments. I'm no expert. Just learning aloud.

Don't forget to like, share and drop a comment. :)