teleren/devto huggingface dataset:
Null Object Pattern
Tags: engenhariadesoftware, nullobject
Published: 2022-03-20 20:32:49

A _keyword null_ é o que usamos para indicar ausência de valor. O inventor no valor nulo, introduzido no ALGOL, foi Tony Hoare. Hoare se desculpou por ter inventado o valor _null_ em 2009, chamando esse feito de “meu erro um bilhão de dólares”, uma vez que é causado uma confusão quando uma variável declarada como tendo o tipo string, por exemplo, pode também não ser uma string, mas _null_. Em muitas linguagens, como é o caso do Typescript, se uma variável puder carregar o valor _null_ (ou undefined, que possui a mesma ideia para o intuito desse texto), é obrigatório que o programador declare isso. Nesses casos, podemos dizer que a variável é _nullable_.

O motivo para _null_ ter o potencial de ser programático é que isso cria mais uma alternativa nos programas, onde algo acontecerá dependendo se a variável for nula ou não. Um exemplo disso, é para o caso de que eu precise utilizar métodos de um tipo. Utilizando JavaScript como exemplo, supondo uma string com o valor ‘Hello, world’ salva na variável “message”, o output para message.substring(0, 5) deve ser a string ‘Hello’. A partir do momento que é possível que “message” seja nula, caso não tratada a possibilidade, isso pode acarretar num erro de execução do projeto, uma vez que “substring” é um método de string, que o valor nulo não possui. 

### De forma sintetizada, se algo pode ser _null_, é necessário checar se o valor é nulo ou não.

Apesar do exemplo anterior demonstrar o aumento de complexidade do desenvolvimento de uma aplicação devido a possibilidade do valor nulo, é importante ressaltar a sua importância e por que ele é usado. A principal vantagem do uso do Padrão _Null Object_ é a possibilidade de considerar diferentes componentes como iguais, de tratá-los da mesma forma. Um exemplo é uma árvore binária, que apesar de existir uma diferença entre os nós comuns e as chamadas folhas (nós sem filhos), podemos tratá-los da mesma forma na hora de construir uma função que retorne todos os nós. Um exemplo disso é utilizando uma função recursiva, onde caso o nó não possua filhos, simplesmente ele não precisa retornar nada, e essa diferenciação é feita utilizando o valor _null_. Outro exemplo seria com polimorfismo, onde a super entidade veículo pode possuir o método "ligar", mas que usando o valor nulo não precisamos possuí-lo quando criarmos uma sub entidade bicicleta.
 
![Imagem de uma árvore binária](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jpqq4ycpexuxgolg19fu.png)

---

_Este artigo escrito durante a disciplina IF977 - Engenharia de Software pelos alunos de graduação em Sistemas de Informação pela Universidade Federal de Pernambuco: Deborah Espíndola, Gustavo Henrique Lima, José Edson, Kevin Beltrão e Liliane Carla_
Telescope week 9
Published: 2022-03-20 19:52:18

This week I was primarily working with `Eslint` issues.

https://github.com/Seneca-CDOT/telescope/issues/3153

At first look, issues look easy to do, but because of some reasons, all of our eslint checks failed on Thursday with a "no-shadow error." I thought it was my local mistake and started googling how to solve this. After hours of fighting with error and resolving merge conflicts, I decided to close my pull rudest and create a new one cause it was all messy. Oh, conflicts. 

> If you want to solve the merge conflict, merge first.

I was desperate and decided to switch to a different issue related to the `Supabase backup strategy`. 

https://github.com/Seneca-CDOT/telescope/issues/2822

Previously, I never had experience with Supabase. That's why I decide to create a small `getting-started` project. I liked it. 
Supabase work on PostgreSQL.
I started researching database backup strategies. I found seven best practices to do it. I started from the Reddit thread on how to solve the issue:https://www.reddit.com/r/Supabase/comments/rlq5mk/how_can_i_backup_my_supabase_database_and_buckets/
```
You can backup your database yourself at any time using pg_dump. You could also backup your buckets with some script, but I don't know where you'd back up to? Most people back up TO S3, where your buckets are stored.
```
After a few searches on `ph_dump,` I found this great post from Supabase itself `https://supabase.com/blog/2020/07/17/postgresql-physical-logical-backups`.

This is where I stopped with my research on weekend I decided to switch back to eslint and kind of did them:
https://github.com/Seneca-CDOT/telescope/pull/3271
https://github.com/Seneca-CDOT/telescope/pull/3269

This was a great week; I'm curious how many issues we will land for 2.9. Let's see.


### Conclusion

⚠️ Computer Architecture Blog Post: Link

### Links

🖇 Follow me on [GitHub](https://github.com/aserputov) 

🖇 Follow me on [Twitter](https://twitter.com/aserputov)

_p.s This post was made for Telescope.
Recent issues with npm packages
Tags: npm, opensource
Published: 2022-03-20 19:50:59

Hi all,
I would like to know your opinion, on recent issues with open-source npm packages, (faker, now ipc). I know that open source is not making a revenue, but does it give you right to bring down any project, for financial or any political reason. Don't reinvent the wheel would be put to question in recent future. I personally think wether open source or not one should be liable for his product.
Before anyone starts, I would like to say that I was not affected by those issues.
I made a wordle clone! 🚀
Tags: showdev, typescript, react, tailwindcss
Published: 2022-03-20 19:41:41

Yes that's right, another wordle clone. You can play it [here](https://nexdle.vercel.app/).

[nexdle](https://nexdle.vercel.app/) is a [wordle](https://www.nytimes.com/games/wordle/index.html) clone made with [React](https://reactjs.org/), [TypeScript](https://www.typescriptlang.org/), [TailwindCSS](https://tailwindcss.com/), [Vite](https://vitejs.dev/), [Zustand](https://github.com/pmndrs/zustand) and tested with [Vitest](https://vitest.dev/). 

This project was a great learning experience for me. Things I learnt while making nexdle:
- CSS Grids
- Using state management libraries ([Zustand](https://github.com/pmndrs/zustand) in this case)
- Using testing tools like Jest ([Vitest](https://vitest.dev/) in this case)

Before this I had made a simple [todo-app](https://github.com/nexxeln/todo-app) to get comfortable with using TypeScript in React projects. Now after using it for 2 projects, I'm absolutely in love with it. TypeScript is just so good for catching errors before shipping the app to production, and the autocomplete you get is just crazy. It takes the developer experience to a whole another level.

I used TailwindCSS for all the styling because lets face it, CSS is really fricking hard. Tailwind just makes it really simple and quick to make a stunning ui. Just add pre-built CSS utility classes and you're good to go!

I didn't use `create-react-app` for this project. Instead I used Vite. Vite is a module bundler, just like webpack. Since I've come across Vite, I haven't gone back to `create-react-app`. It's just faster, has less dependencies so the build size is less. If you haven't tried it yet, I highly recommend you do!

I finally learnt how to use state management libraries. In this project I used Zustand, which is like a bare bones version of [Redux](https://redux.js.org/). It's better than using the Context API as its less boilerplatey. I figured for a small project I don't really need to use a heavy library like Redux.

A few weeks ago I learnt how to use [Jest](https://jestjs.io/) and I was really excited to try it out here. But I found out that it wasn't compatible with Vite. So I found this really awesome library called Vitest. Honestly, testing was the most fun part of the whole project. It helps you catch bugs before production and is just really fun to do.
![testing](https://us-east-1.tixte.net/uploads/nexxel.needs.rest/Code_7Bk8VB3xBb.png)

Vitest also has this crazy ui testing option, I haven't explored it a lot but it's just insane. Check this out:
![insane](https://github.com/nexxeln/nexdle/blob/main/images/Code_Vyzc5YbawL.gif?raw=true)
I also uploaded this gif to [YouTube](https://youtu.be/2GLYNV5cQ-Y) since it's kind of long. You can watch it there if you prefer that.

So that's it for this blog. All the code for nexdle can be found [here](https://github.com/nexxeln/nexdle/).

If you made it this far thanks for reading!
How to build AWS SERVERLESS AURORA
Published: 2022-03-20 19:31:16

**step 1**
Create an rds database and choose the serverless option. Make sure the API button is clicked.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/33xvey5jxouxt8fhmoee.jpg)

**step 2**
connect the query editor to the database
Case statement in SQL
Tags: tabular, sql
Published: 2022-03-20 19:26:08

I was recently trying into make the relational columns to rows.  I came across case statement.

The CASE statement goes through conditions and returns a value when the first condition is met (like an if-then-else statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause.

If there is no ELSE part and no conditions are true, it returns NULL.

Example below shows how to flatten subject name columns to rows with generic subject...

id  name   english maths science
123 Harry   90       75       85
345 Porter  70       80       90
-----------

Now the below query can transpose columns to row using subject_sequence table's rows.
SELECT
  id,name,
  CASE seq_id 
     WHEN 1 THEN 'english'
     WHEN 2 THEN 'maths'
     WHEN 3 THEN 'science'
  END AS subject, 
  CASE seq_id 
     WHEN 1 THEN english
     WHEN 2 THEN maths
     WHEN 3 THEN science
  END AS marks
FROM student CROSS JOIN subject_sequence;

Output:
  id  name     subject   marks
----  -------  --------  -----
 123  Harry    english      90
 123  Harry    maths        75
 123  Harry    science      85
 345  Porter   english      70
 345  Porter   maths        80
 345  Porter   science      90
React component lifecycle.
Published: 2022-03-20 18:43:27

In React, a component's lifecycle refers to the events that occur from initialization to destruction. React components undergo three main phases: Mounting, Updating, and Unmounting. Each phase has a set of lifecycle methods that you can override to perform actions at specific points in the component's life.

Basically, the React Component lifecycle has 3 stages: 
1. Mount.
2. Update.
3. UnMounting.

1. - Mount : 
'Initial Stage' This stage starts when any component enters into DOM, here are four methods in this stage.
1. constructor()
2. getDerivedStateFromProps()
3. render()
4. componentDidMount()


2. - Updating :
When any changes of props or state make changes in the component, then the component enters this stage. here are five methods in this stage.
1. getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforUpdate()
5. componentDidUpdate()


3. - UnMounting :
When any component is excluded from the DOM, then the component enters this stage. get here done one method in this stage.
1. componentWillMount()



###An image of React Component Lifecycle -
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/30l94r5yjqwhoj91xhev.png)
*(This image is collected from the internet)*

<hr>
Docker CMD and ENTRYPOINT and Kubernetes args and command
Tags: devops, kubernetes, docker, linux
Published: 2022-03-20 18:36:52

## Docker

Without passing any commands to `docker run` both do the same job. However, when `docer run` is used CMD is replaced if an argument was provided to `docker run` while ENTRYPOINT will append the arguments to the value defined in the entry point. 

You can use both inside the Dockerfile as the parameters of `CMD` will be appended to `ENTRYPOINT`.

### CMD
```dockerfile
# docker run ubuntu-sleep sleep 10

FROM ubuntu

CMD sleep
```

### ENTRYPOINT
```dockerfile
# docker run ubuntu-sleep 10

FROM ubuntu

ENTRYPOINT ["sleep"]
```

## Kubernetes
It's dead simple, `args` in equivalent to `CMD` and `command` is equivalent to `ENTRYPOINT`
A tale of rsync
Tags: devops, linux
Published: 2022-03-20 18:34:57

I was migrating `/var` directory on some on-premises server I was working on from a low space disk to a larger one and I had to use the infamous `rsync` for this. I found the necessary parameters to on this [article](https://linuxconfig.org/how-to-move-var-directory-to-another-partition) but I didn't like the idea of copying & pasting blindly without knowing what each parameters do. So I just looked the man page of rsync and decided to document what I found here for future references.

The full command I used:

```bash
rsync -aqx /var/* /mnt/newvar
```

Here's a table with each flag explained:


| Flag | Usage                                  |
|------|----------------------------------------|
| -a   | Shorthand for `-rlptgoD`               |
| -r   | Recursive                              |
| -l   | Copy symlinks as symlinks              |
| -p   | Preserve permissions                   |
| -t   | Preserve modification time             |
| -g   | Preserve group                         |
| -o   | Preserve user                          |
| -D   | Preserve devices files & special files |
| -x   | Don't cross filesystem boundaries ()   |
| -q   | Make it quiet                          |


The `-x` flag means don't copy other filesystem files and directories like NFS, Samba, ..etc. [1](https://unix.stackexchange.com/questions/107113/meaning-of-crossing-filesystem-boundaries-one-file-system-etc)
Integer to Roman
Tags: javascript, algorithms
Published: 2022-03-20 18:07:45

We'er going to kick things off by creating 2 variables. One will store our numbers, and the other will store the corresponding roman numeral, and both will go from highest to lowest. 

This will allow us to associate a number with its counterpart. **Note:** _Remember to put each number and roman numeral as a string within the overall array._

```
    let numbers = ['1000', '900', '500', '400', '100', '90', '50', '40', '10', '9', '5', '4', '1']
    let romans = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
    let result = ''

```

Now that we have this dict ready, we can loop through the number and find out if the number given is greater than the current number.

If it is, we will add the corresponding roman numeral to a result variable, then we will subtract the given number by the current number. 

We will continue to do this loop until we are 0 and then we return the result string.

```
    let numbers = ['1000', '900', '500', '400', '100', '90', '50', '40', '10', '9', '5', '4', '1']
    let romans = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
    let result = ''
    
     //loop through numbers
     for (let i = 0; i < numbers.length; i++){

         //set variable to current number
         let current = numbers[i]

         //while the number equal the current number or is 
          bigger then it 
         while (num >= current) {


            //add the corresponding numeral to the result 
             string
             result += romans[i]
             
              //subtract the num by the current current in the 
              numbers array
             num-=current
         }
     }
 
       //return the result
    return result
};

```
MyUnsplash
Tags: javascript, node, firebase, react
Published: 2022-03-20 17:58:36

Unsplash Clone

###### Client side repo : https://github.com/nisabmohd/MyUnsplash
###### Server side repo : https://github.com/nisabmohd/MyUnsplash-API



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


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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2msnc9346kgypuu64zsx.png)
How do people package Altair themes? (II)
Tags: python, altair, datavisualization, vega
Published: 2022-03-20 17:51:03

After we saw [four examples in the first part](https://dev.to/joaompalmeiro/how-do-people-package-altair-themes-36p3), let's look at four more and learn more about how people package [Altair](https://altair-viz.github.io/index.html) themes.

Based on the [altair-latimes](https://github.com/datadesk/altair-latimes) package, we have [altair-reveal](https://pypi.org/project/altair-reveal/). In this package, we can find the [Reveal](https://revealnews.org/) theme for Altair. An interesting detail in this theme is the empty space available at the bottom of each chart (bottom padding) to accommodate manually added sources and credits. We can see this detail, as well as several examples, from this [notebook](https://github.com/cirlabs/altair-theme-reveal/blob/main/examples.ipynb) directly on GitHub.

For the [Sun Sentinel](https://en.wikipedia.org/wiki/Sun-Sentinel) theme, there is [sunsentinel_theme](https://github.com/SunSentinel/sunsentinel-altair-theme). This theme is based on [husky_theme](https://github.com/deppen8/husky-altair-theme), and for us to use it, we have to follow the steps mentioned in the [first part](https://dev.to/joaompalmeiro/how-do-people-package-altair-themes-36p3) (it is not a `pip` installable Python package).

Based on [spaCy](https://spacy.io/) branding, we can find two themes in the [spacy-altair-theme](https://github.com/pmbaumgartner/spacy-altair-theme) package. One of them is a monospaced version of the available base theme. In addition to a function for each of the themes (each function contains some constants and returns a dictionary with the configuration for the respective theme), we can also find three importable lists for the three types of defined color palettes. To use these themes, we just need to `alt.themes.enable()` the desired one, as these are [`alt.themes.register()`ed](https://github.com/pmbaumgartner/spacy-altair-theme/blob/main/spacy_altair_theme/themes.py#L156) when we [import the package](https://github.com/pmbaumgartner/spacy-altair-theme/blob/main/spacy_altair_theme/__init__.py#L3). As a final note, some color variants were chosen from spaCy's [style guide](https://spacy.io/styleguide) because of contrast (like dark blue and dark green instead of blue and green, respectively).

In the case of the [pcolor](https://github.com/catethos/pcolor) package (bootstrapped from the [nbdev template](https://github.com/fastai/nbdev_template)), we can find an Altair (and [seaborn](https://seaborn.pydata.org/)) theme for personal use. This package contains color constants and various utilities, in addition to the typical function for the theme (`pulsifi_theme`). It also provides a [utility function](https://github.com/catethos/pcolor/blob/master/pcolor/core.py#L218) called `setup_altair()` that wraps up theme registration and activation.

Finally, if you have any questions or suggestions, feel free to leave a comment below!
Max Water Container
Tags: javascript, algorithms
Published: 2022-03-20 17:09:54


Let's observe the logic behind the chart we're seeing.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tw1fqmqpbo29oayw8nef.png)

The area, and the answer, is 49. 

We got that number because we looked at the distance between the two indices and then multiplied it by the minimum value of both indices. 

Let's look at the first part, the width, since finding an area is width times height.

```
result = (j-i)*min(height[j], height[i])
         ______
           7

 height = [1,8,6,2,5,4,8,3,7]
             _             _
             1             8
                 
   8-1 = 7
```

Now let's look at the second part. The height.

```
result = (j-i)*min(height[j], height[i])
                ___________________
                   7

 height = [1,8,6,2,5,4,8,3,7]
             _             _
             8             7
                 
  min(7, 8) = 7
```
               
And let's do the last step just for kicks, multiplying them together, then we'll jump into code.
     
```
result = (j - i)*min(height[j], height[i])
          ___________________  _________________________
              7             *             7
           **= 49**

```

And that is how we will get our answer. 

The first thing we want is to declare variables. i is at the left, and j is at the right.

Then we will want them to move left and right.

```

function maxWater (array) {
 let i = 0
 let j = array.length - 1
 let area = 0

}
```

Now let start iterating through the array, and we will do so with a while loop until the two pointers meet each other. 

```

function maxWater (array) {
 let i = 0
 let j = array.length - 1
 let area = 0

 while (i < j) {
   const temp = (j - i).Math.min(array[j], array[i])
   
 }
 
}

```

Then we update the area and move the i and j. It's not helpful to move the larger number in this case, so we only move the lower number. 

```

function maxWater (array) {
 let i = 0
 let j = array.length - 1
 let area = 0

 while (i < j) {
   const temp = (j - i).Math.min(array[j], array[i])
   area = Math.max(temp, area)
   if (array[i] > array[j]) {
    array[j]-=1
   } 
     else {
   array[i]+=1
  }
 }
 return area
}

```
How I went from living from day to day to saving and investing my money
Tags: motivation
Published: 2022-03-20 16:35:49

Three years ago, I started to worry about my money.

😞 I used to live day to day, I had no savings, I didn't invest.

✌️ Now I can go 4-5 months without income and nothing would happen.
 
I'll tell you how I made the change 👇.

The first thing I did was to SEE how I spend my money.

At first, I did it with a crappy excel and entering my two bank accounts in a very manual way and wasting a lot of time.

Now I do it with [monse.app](monse.app), and I will tell you how.

After creating the account, the first thing I do is to connect my two banks.

Automatically, I start to see the transactions on the web and start assigning categories.

![Categorize each expense and income](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/otlwrly3yph9th03v7bw.png)

At first, it can be a bit tedious, there are a lot of transactions, but monse learns to assign categories automatically, and then you will only have to do it manually once in a while.

We do this to get important data about our spending.

## 🤑 How do you spend your money?

There are three fundamental charts that monse gives me.

1️⃣ Month to month evolution: my wealth, month to month, is increasing or not. Am I closer or further away from FI?

2️⃣ How much money do I earn, and how much do I spend each month?

3️⃣ How do I spend money?

![See how do you spend your money](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pm3qt8nbfky5948cpdj0.png) 

Now that we know how we spend our money and how much, let's get down to the basics: paying you first.

When my paycheck comes in, I have 3 automatic transfers:

➡️ a savings account.

➡️ another to an investment fund (in my case, [Indexa Capital](https://indexacapital.com/t/QUFQZ8)).

➡️ and one to a daily expense account (debit card).

It is crucial that they are automatic, if you have to do them manually you won't do them.

They should also be immediately upon receipt of your salary. It is money that you should not count on for other expenses.

The amount is up to you. How much you can save.

In my case, I also allocate some of my money to cryptocurrencies, but I'll leave that for later.