teleren/devto huggingface dataset:
How to easily make every property in a type alias or interface to readonly properties in TypeScript?
Tags: typescript
Published: 2022-05-12 00:00:00

---
  title: How to easily make every property in a type alias or interface to readonly properties in TypeScript?
  published: true
  tags: TypeScript
  date: Thu May 12 2022 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/easily-make-every-property-type-or-interface-readonly-typescript
  cover_image: https://melvingeorge.me/_next/static/images/main-726c584b696d3211168b25af3cfb7ee9.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/easily-make-every-property-type-or-interface-readonly-typescript)
  
To easily make every property on a `type alias` or `interface` to readonly properties, you can use the `Readonly` utility type and pass the `type alias` or `interface` as the first type argument to it using the angled brackets symbol (`<>`).

### TL;DR

```ts
// a simple type
type Person = {
  name: string;
  age: number;
};

// make all the properties in the
// `Person` type to be readonly
type ReadonlyPerson = Readonly<Person>;

// contents of the `ReadonlyPerson` type
/*
{
  readonly name: string;
  readonly age: number;
}
*/
```

For example, let's say we have a type called `Person` with 2 properties called `name` having the type of `string` and `age` having the type of number like this,

```ts
// a simple type
type Person = {
  name: string;
  age: number;
};
```

Now to make all the properties in the `Person` type to be readonly we can use the `Readonly` utility type and pass the `Person` interface as the first type argument to it using the angled brackets symbol (`<>`).

It can be done like this,

```ts
// a simple type
type Person = {
  name: string;
  age: number;
};

// make all the properties in the
// `Person` type to be readonly
type ReadonlyPerson = Readonly<Person>;

// contents of the `ReadonlyPerson` type
/*
{
  readonly name: string;
  readonly age: number;
}
*/
```

Now if you hover over the `ReadonlyPerson` type you can see that all the properties are now readonly which is what we want to happen.

See the above code live in [codesandbox](https://codesandbox.io/s/easily-make-every-property-type-or-interface-readonly-typescript-okk6uh?file=/src/index.ts).

That's all 😃!

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

---
Automatically archiving Dependabot and Semantic Release emails
Tags: gmail, dependabot, appscript
Published: 2022-05-27 04:32:32

---
title: Automatically archiving Dependabot and Semantic Release emails
published: true
date: 2022-05-12 00:00:00 UTC
tags: gmail, dependabot, appscript
canonical_url: https://justin.poehnelt.com/posts/archive-github-dependabot-semantic-release-emails-with-appscript/
---

As an Open Source maintainer, I get hundreds of emails a day from Dependabot and Semantic Release. A while back, I put together the below [Google Apps Script](https://developers.google.com/apps-script) snippet to automatically archive the emails based upon some simple regex patterns to accomplish the following tasks:

- Archive Dependabot emails that are merged or closed
- Archive Semantic Release publish notifications on pull requests and issues.

Currently this is running in a cron every 5 minutes.

```js
function main() {
  // archive dependabot notifications
  GmailApp.moveThreadsToArchive(
    GmailApp.search('label:"inbox" from:dependabot[bot]').filter((thread) =>
      threadMatches(thread, [/Merged .* into .*/, /Closed /])
    )
  );

  // archive semantic release publish notifications
  GmailApp.moveThreadsToArchive(
    GmailApp.search('label:"inbox" from:github-actions[bot]').filter((thread) =>
      threadMatches(thread, [
        /This PR is included in version/,
        /This issue has been resolved in version/,
      ])
    )
  );
}

function threadMatches(thread, patterns) {
  const messages = thread.getMessages();

  if (messages.length > 1) {
    for (let message of messages) {
      for (let pattern of patterns) {
        const match = message.getBody().match(pattern);

        if (match) {
          return true;
        }
      }
    }
  }

  return false;
}
```

This is all pretty basic, but it does the job. Future work might focus on inverting the dependabot functionality so that depending on the date of the thread and current status of the pull request, the thread will be moved to the inbox if action is required.

I have yet to find the perfect workflow for my open source work spanning different repositories, organizations, etc. Email is a good backstop for complete coverage and the scripts above give me some eventual consistency.
Using Foreman to start services in development
Tags: rails, tutorial
Published: 2022-05-11 23:36:47

In any development environment it's usually needed to start many background services to be able to code properly.

I don't like to keep all necessary services running in my machine all the time to save resources, so I start them only when needed; and starting them one-by-one it's too much work.

Comes [Foreman](https://github.com/ddollar/foreman) to the rescue! Foreman is a gem (for Ruby, but it already ported to many others languages) that will load a Procfile and start/stop the services configured by demand.

For example, every time I start coding in a project, I need to run all those services:
- PostgreSQL
- Redis
- Webpacker
- Rails server
- Rails worker

Automation of this procedure is simple. Lets first create a `Procfile` and save it on the project root directory.

`./Procfile`
```
postgres: postgres -D /usr/local/var/postgres
redis: redis-server /usr/local/etc/redis.conf
webpacker: bundle exec bin/webpack-dev-server
rails: bundle exec rails server
worker: bundle exec rails jobs:work
```

As you can see, it's easy. Just follow this simple rule:
```
service_name: command to run it
```

Then type:

```
$ foreman start

20:30:42 postgres.1 | started with pid 42458
20:30:42 rails.1    | started with pid 42459
20:30:42 worker.1   | started with pid 42460
20:30:42 redis.1    | started with pid 42461
20:30:42 webpack.1  | started with pid 42462
```

and you are ready to go!

Thanks [David Dollar](https://github.com/ddollar) for this awesome gem.
Season 9 of DevDiscuss is here! Let's talk about design patterns...
Tags: devdiscuss, webdev, javascript, discuss
Published: 2022-05-11 22:53:33

---
title: Season 9 of DevDiscuss is here! Let's talk about design patterns...
published: true
description:
series: DevDiscuss Season 9  
tags: devdiscuss, webdev, javascript, discuss
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e526zmdjfba0jghsjuwn.png
---

_**DevDiscuss Season 9 is here!**_ 🎉

In the premiere, my cohost @ridhwana and I focused on using design patterns to improve how you architect web apps with @lydiahallie & @addyosmani — co-authors of the new book _[Learning Patterns](https://www.patterns.dev/)_. 

{% embed https://dev.to/devdiscuss/s9e1-using-design-patterns-to-improve-how-you-architect-web-apps %}

> ### <mark>After you listen to our show, I'd love to hear about the design patterns that _you_ find to be the most helpful/compelling!<mark> Comment below!

---

We hope you enjoy listening to the season 9 premiere of DevDiscuss: the show where we tackle the burning questions that impact all our lives as developers. 

#### Links to listen on your favorite podcast platform:
- [Apple Podcasts](https://podcasts.apple.com/us/podcast/s9-e1-using-design-patterns-to-improve-how-you-architect/id1513053883?i=1000560465220)
- [Spotify](https://open.spotify.com/episode/7ceKwVCeOFftk8NQpNCKao)
- [Google](https://podcasts.google.com/feed/aHR0cHM6Ly9mZWVkcy5kZXZwb2RzLmRldi9kZXZkaXNjdXNzX3BvZGNhc3QueG1s/episode/aHR0cHM6Ly9kZXZwb2RzLmRldi9wb2RjYXN0cy9kZXZkaXNjdXNzLzY2?sa=X&ved=0CAQQkfYCahcKEwjgqani_df3AhUAAAAAHQAAAAAQCg)
- [Listen Notes](https://www.listennotes.com/podcasts/devdiscuss-dev-xtQvoDylAUg/)
- [TuneIn](https://tunein.com/podcasts/Technology-Podcasts/DevDiscuss-p1324596/?topicId=172021758)
- [RSS Feed](http://feeds.codenewbie.org/devdiscuss_podcast.xml)
- [DEV Pods Site](https://devpods.dev/podcasts/devdiscuss/episodes/263)

> #### _Acknowledgements_ 
> - The wonderful _@levisharpe for producing & mixing the show_
> - _Our season nine sponsors: [Cockroach Labs](https://www.cockroachlabs.com/lp/serverless/?utm_source=devdiscuss&utm_medium=sponsor&utm_campaign=na-brand-dev-serv-launch-beta&utm_content=lp-serverless-learn-more-podcast-0511&utm_term=prosp), [Swimm](https://swimm.io/?utm_source=dev.to&utm_medium=podcast&utm_campaign=devdiscuss_podcastQ2), [Drata](https://drata.com/partner/devdiscuss) & [Stellar](https://quest.stellar.org/)!_
Don't parse CSVs by hand!
Tags: javascript, programming
Published: 2022-05-11 22:52:53

I've seen custom JavaScript code to parse CSV data a number of times. It looks something like this:

```js
const csvData = fs.readFileSync(csvFilePath, 'utf8');
const lines = csvData.split('\n');
const rows = lines.map(line => line.split(','));
```

So simple, and it may be fine if you're parsing a single static CSV file whose content you know. But if you're parsing unknown CSV files, don't do this, there are many ways it can break.

## What Can Go Wrong

### Escaped cells

Columns in a CSV file may contain commas. Such columns are typically escaped with quotes. The raw data for a row with such a column might look something like this:

```
Name,Best Line
Hamlet,"To be, or not to be"
```

Though the second line has two commas, this produces a table with two columns, not three:

| Name | Best Line |
| ---- | --------- |
| Hamlet | To be, or not to be |

This breaks the simple CSV parser implementation which just splits on `,`.

### Line Endings

The simple CSV parser implementation assumes LF line endings (`\n`), but text files, including CSV files, created on Windows will often have CRLF line endings (`\r\n`). Further, there may be line ending characters within escaped cells. Needless to say, these cases break the simple CSV parser implementation.

## What to do instead

Bring in a library that's built for this. I like to use [csv-parse](https://www.npmjs.com/package/csv-parse). It's easy to use:

```js
import { parse as csvParse } from 'csv-parse/sync';

const csvData = fs.readFileSync(csvFilePath, 'utf8');
const rows = csvParse(csvData);
```

That's it.

## Conclusion

I know no one likes bringing in libraries to solve what seems to be a simple task, but parsing arbitrary CSVs correctly is actually a lot harder than it looks at first glance. Save yourself the pain, use someone else's battle-hardened parser.
What is Six Sigma Methodology and How it used
Published: 2022-05-11 22:40:42

The particular Six Sigma technique was developed in the mid-1980s by engineers at Motorola in an effort to improve producing processes. At their core, Six Sigma involves collecting and leveraging data to eliminate defects and waste in producing, with the conclusion goal of increasing overall efficiency and quality.

The expression “sigma” is a measurement showing how far from perfect a process or manufacturer can get—by 6 Sigma standards, companies should reduce producing defects to less than 3. 4 per 1 , 000, 000 units.

Businesses use the Six Sigma methodology to further improve techniques by identifying the errors that may lead to flaws and implementing new management systems once errors have already been addressed. The technique is most effective with repetitive, set up line-style functions where individual steps can be isolated, evaluated, and improved on.

## How 6 Sigma used?

Actually developed for producing, Six Sigma can now be found across many industrial sectors. Nevertheless , just because companies in various areas have applied this methodology doesn’t actually mean that these companies have used it appropriately or effectively. Outside a manufacturing operation, 6 Sigma often neglects to yield the type of results needed to justify such a time-consuming and expensive management change.

In order to function effectively, 6 Sigma requires buy-in from everyone included. It requires a substantial upfront cost to implement and educate employees on the methodology of 6 Sigma and their execution.

Employees of all levels must be trained in the various opportunities of the technique as well. Persons who have completed a [Six Sigma green belt training](https://www.igmguru.com/quality-management/lean-six-sigma-green-belt-certification-training/) class earn belts to specify their level—Green Devices are for starters, Black Belts are for project market leaders, and Master Dark Belts are for those in demand of implementing 6 Sigma throughout the business enterprise.
My Django/React Heroku Deployment Checklist
Tags: django, react, webdev, heroku
Published: 2022-05-11 22:27:51

This is a working document and not currently meant to serve as a How-To or guaranteed to be exhaustive/bug free, but rather give myself a centralized set of steps to draw from. 

This is "Part 2" of a Django deployment checklist. Part 2 focuses on adding a compiled React App as static files so the two run as one unified application.
[Part 1 can be found here](https://dev.to/thomz/my-django-heroku-checklist-3p72)

-Update any calls to your back-end to use your Heroku domain
-cd into the react-app front end and run `npm run build`. This will generate a "build" folder in your react-app project directory. 
```terminal
my-computer/my-react-app/ $ npm run build
```
Create a folder in your your Django project directory called "frontend" and copy the build folder into this frontend folder. Path should look like `my-django-app/frontend/build`, "my-django-app" being the root folder for this application.

-Tell Django to look for these static files by updating the DIRS setting in the TEMPLATES variable
settings.py
  +Also a STATICFILES_DIRS variable to settings so it knows where to find these static files

```python

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'frontend/build')],
...

    },
]

# Put this near your other STATIC variables
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'frontend/build/static')]
```

-Configure urls.py to use a regular expression path with TemplateView. We are using the index.html from our static build files that react generated for us. The regular expression will ensure that our React routing functions correctly.

urls.py
```python
from django.urls import include, path, re_path
from django.views.generic import TemplateView

urlpatterns = [
    path('mypaths/', include('app.urls')),
    re_path(r".*", TemplateView.as_view(template_name='index.html')),
    ...
]
```
Encrypting Folders on MacOS
Tags: security, devops, tutorial
Published: 2022-05-11 22:07:46

1. Create a new folder, for my example the folder is named "secretstuff". 

2. Copy whatever files, folders or content you want to protect into the secretstuff folder.

3. Launch the Disk Utility, from the file menu, select new image, image from folder.

4. I selected the folder I created from step 1 above. Set the encryption to 256-bit AES, and the image format to compressed. Select Save. When prompted, provide a long and strong password, store the password in a safe place separate from the folder and the final dmg file once created.  

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

5. A new secretstuff.dmg file will be created, dont forgot to delete the source secretstuff folder, but leave the secretstuff.dmg file.  

6. If you want to access the contents of the secretstuff.dmg file, you may do so by using the same Disk Utility tool, from the file menu, select open disk image, when prompted enter the password created above during step 4.
Creando un proyecto de React con Vite
Tags: beginners, vite, react, spanish
Published: 2022-05-11 21:51:59

A continuación voy a contarles cómo podemos iniciar nuestro proyecto de React utilizando Vite. Para ello en la consola vamos a posicionarnos sobre la carpeta que contendrá nuestra carpeta del proyecto y vamos a ejecutar el siguiente comando:

```
$ npm create vite@latest
```
Allí vite nos irá conduciendo para poder crear nuestro proyecto a gusto. Podremos elegir el nombre del proyecto, el framework y la variante que utilizaremos para nuestro proyecto.

Al finalizar la instalación nos dirá que debemos correr los siguientes comandos para instalar y ejecutar el servidor de desarrollo:

```
$ cd [nombre-del-proyecto]
$ npm install
$ npm run dev
```
Debemos ingresar a la carpeta del proyecto con el primer comando y luego ejecutamos el segundo comando, donde se instalarán todas las dependencias que necesita para crear nuestro proyecto con Vite. **¡Felicitaciones!** Ya tienes creadas las bases de tu proyecto con Vite. 

Para verificar que todo funciona correctamente puedes correr el servidor de desarrollo con el último comando y si todo salió bien, deberías visualizar la siguiente página en tu navegador: http://localhost:3000/

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

Ahora ya puedes prepararte un mate o un café :) y ponerte a escribir el código de tu proyecto inicializado con Vite. ¡Éxito!

Aquí puedes encontrar toda la [documentación oficial de Vite](https://vitejs.dev/).

_¡A codear con un buen café!_ Gracias por leer.
Alright, here we go!
Tags: beginners, linux, cloud
Published: 2022-04-12 12:34:38

After studying Networking and Sys Admin stuff back at school about 8 years ago (damn I'm getting old), I worked in the field for a couple years. But you know, life has it's ways of messing with you so I ended up doing something completely unrelated.
But I never lost the enthusiasm for tech and now I can finally get back in the business.. thing is, I don't know all that much practical stuff.
So here's the plan, I want to be in a Cloud or Sys Admin related job in a year's time. I'm a very "jack of some trades, master of none" guy, mostly because I've studied on my own but haven't put into daily practice at a job, so it'll definitely be a challenge but I have a good idea of where to start.

As we all know, clouds are made of Linux servers and the sky is the limit, so I'm starting there; I'll sprinkle in some Python as well (and some Bash oc) since I believe anyone in tech needs to know the basics of programming. Being able to automate simple things is a very powerful tool.

The way I'm getting familiar with Linux is mostly through Hack The Box and Over The Wire stuff which is incredibly fun, but probably lacking in the Admin side of things, so I have to find some other study materials. The objective is to get something like the LPI Linux Essentials or Linux+.
I also have a small MikroTik router that I love messing around with, setting up and resetting it into different configurations and I plan on using it in conjunction with a Linux machine setup as a NAS later on.

For Python, I'm going through the great Edube Interactive free Python course so I can then get the PCEP-30-01 Exam (entry-level). Programming isn't my main focus here so that exam will be enough for now.

I think Dev.to will be an amazing platform for me to document my voyage and eventually look back on it with pride :)
Discussions of what lies ahead are abundant this time of year, but What are some of your top-five cloud predictions for 2022?
Tags: cloudnative, cloudskills, web3, webdev
Published: 2022-05-11 21:41:12

Discussions of what lies ahead are abundant this time of year, but this roundup ([watch here](https://community.lohika.com/home/events/web3-why-it-matters-and-how-to-think-about-it-in-2022-2022-02-10)) is worth reading. 2022 Cloud prediction To Watch out For **What are some of your top-five cloud predictions for 2022?**
As a software engineer, how quickly do you get left behind if you don’t constantly update your skills?
Tags: webdev, devops, siliconvalley, productivity
Published: 2022-05-11 21:33:00

As a [**software engineer**](https://community.lohika.com/home/blogs/how-fintech-start-up-engineering-leaders-manage-rapid-scaling-2022-01-29), how quickly do you get left behind if you don’t constantly update your skills?
Lambda Functions
Tags: serverless, aws, lambd, cloud
Published: 2022-05-11 21:30:23

● A function is a block of code in Lambda.
● You upload your application/code in the form of single or multiple functions.
● You can upload a zip file, or you can upload a file from the S3 bucket as well.
● After deploying the Lambda function, Lambda automatically monitors
functions on your behalf, reporting metrics through Amazon CloudWatch.
observed data reverting back in mobx-react with bootstrap-4
Published: 2022-05-11 21:01:41

I've been seeing an issue in mobx-react with bootstrap-4 and I'm getting some unexpected results that is driving me crazy.   I've boiled it down to the simple example below.   
1) `Model` object that simply holds an array of `data`.  And an `action` that provides a way to add `data` to the array.
2) `App` component that instantiates the model object and will render:
- the model's `data` which is an array rendered as JSON string (that data is marked as `observable`).
- A button to add a new object to model (the add is marked as an `action` in the model object)
All this works fine, if I don't wrap the `Button` in a bootstrap4 `Form`, like below:
```
render() {    
    return (
      <>
          {JSON.stringify(this.model.data)}

          <Button onClick={this.addNewItem}>Add Another</Button>      
      </>
    )
  }
```
But if the `Button` is wrapped in a bootstrap4 `Form`, you can see a slight delay where the JSON is changed to include the new item, but then instantly reverts back to the old data which does not include the new item.

```
render() {    
    return (
      <>
          {JSON.stringify(this.model.data)}

        <Form>
              <Button onClick={this.addNewItem}>Add Another</Button>
        </Form>
      

      </>
    )
  }
```
Any idea what might be going on here?   Full Source is below.
Thanks,
Chris

```
import React, { Component } from 'react';
import { observer } from 'mobx-react'
import { Card, Form, Button } from 'bootstrap-4-react';
import { action, makeObservable, observable } from 'mobx';

class Model {
  data = null
  constructor(data) {
      this.data = data

      makeObservable(this, {
          data: observable,
          add: action
      })
  }
  add() {
      this.data.push({ "Date": new Date() })
  }
}

class App extends Component {

  constructor(props) {
    super(props)
    this.addNewItem = this.addNewItem.bind(this);
    var data = [
      {
        "Date": new Date()
      }
    ]
    this.model = new Model(data)
  }

  addNewItem() {
    this.model.add()
  }

  render() {    
    return (
      <>
          {JSON.stringify(this.model.data)}

        <Form>
              <Button onClick={this.addNewItem}>Add Another</Button>
        </Form>
      

      </>
    )
  }
}

export default observer(App);
```