teleren/devto huggingface dataset:
Infinite Loops Inside useEffect
Tags: react, javascript, webdev
Published: 2020-06-20 16:47:00

Recently, I came across a bug when using the `useEffect` hook. I intended to utilize the functionality of the lifecycle method `componentDidMount`, but `useEffect` doesn't work precisely the same way.  

#### The Bug
```js
useEffect(()=> {
  fetch("http://localhost:3000/categories")
    .then(resp => resp.json())
    .then(categoriesArray => {
       this.setState({
         categories: categoriesArray
       })
    })
})
```

Whenever we ran the application, the fetch was successful but continued to fetch infinitely.

#### The Solution
After a few minutes of google searching the problem, we came across a StackOverflow post that gave us a simple solution.

```js
useEffect(()=> {
  fetch("http://localhost:3000/categories")
    .then(resp => resp.json())
    .then(categoriesArray => {
       this.setState({
         categories: categoriesArray
       })
    })
},[])
```
A user suggested that adding empty brackets as a second argument will fix the infinite fetching.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/n4ggvp20cju5q0q3d5f9.gif)

#### A Bit About useEffect
`useEffect` lets you perform side effects in function components. Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects. To put it simply, `useEffect` is like a combination of `componentDidMount`, `componentWillUnmount`, and `componentDidUpdate`.

So what's happening when we run our broken code? When the component first renders and mounts, the fetch is called and then sets the state for categories that cause the component to render again. This blog post that [Andrew Myint](https://medium.com/@andrewmyint/infinite-loop-inside-useeffect-react-hooks-6748de62871) wrote explains this pretty well. 

The second argument will tell `useEffect` not to render unless the said variable changed between renders. Andrew Myint's post uses a variable inside brackets as the second argument. I think the empty brackets also work because there is no trigger to run `useEffect` again, it'll run only once, after the component mounts.
Expose local server over SSL? (Messenger bot)
Tags: javascript, networking, help, discuss
Published: 2020-06-20 16:34:22

Hi!

In the past I've been working on a chatbot and now I want to continue development but I can't seem to find a solution to expose my local server over HTTPS. Facebook messenger API only works over HTTPS.

I've read some articles about ngrok but it recently changed plans so the free plan no longer works (no static address which makes development possible but uneasy). 

Also I've found another service called serveo.net whichs looked promising but it seems like HTTPS is not supported.

Any suggestion? 

Thanks!
linux : bash script
Tags: bash, cli, linux
Published: 2020-06-20 16:16:14

We can run the bash script directly in the terminal.

```markdown
$ echo "This is a bash script."
This is a bash script.
```

We also can store the script in a file, so that we can run it every time we want without typing the script in terminal.

```markdown
# !/bin/bash
echo "This is a bash script." 
```

We need to update the file permission if we want to run the bash file. We can run this command, and specify the file permission

```markdown
$ chmod 700 FILE
$ ./FILE
This is a bash script.
```

We can run linux command in bash file and run the bash script in the cli.

---

 

The bash file will very useful if we want to use some variable or put logics in the script.

---

## VARIABLE

- Positional Parameter Variable

```markdown
# !/bin/bash
echo "This is a $1 $2." 
```

we can give a value for `$1` and `$2` after the run command.

```markdown
$ ./FILE bash script
```

- User Defined Variable

```markdown
# !/bin/bash
# define a string value, print as is
print1='script'

# define a string value, we can add variable inside the double quotes
print2="bash $print1"

# define a number
print3=3

# define a command
print4=`clear`

echo $script
```

- Environment Variable

Usually we use `.env` file to store the environment variable

```markdown
PORT=80
ENV=development
```

operation for variable

```markdown
# using let
let sum=$number1+$number2

# using expr
sum=`expr $number1 + $number2`
length=`expr length $string`
```

declaring variable type

```markdown
# declare an intrger
declare -i number
number=100
```

---

## IF STATEMENT

```bash
if [ CONDITION ]; then
	TRUE_COMMANDS
else
	FALSE_COMMANDS
fi
```

---

## WHILE LOOPING

```bash
while [ CONDITION ]
do
	COMMANDS
done
```

---

## FOR LOOPING

```bash
for VARIABLE in LIST
do
	COMMANDS
done
```
CSS hacks 101
Tags: webdev, showdev, css, react
Published: 2020-06-20 16:14:12

---
title: CSS hacks 101
published: true
description: collections of CSS common use case
tags: #webdev #showdev #css #react
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/k1bxfuny0eqc0bdewzow.png
---

I've collected some Common CSS trick which can help you solve your problem, you may have faced these problems or will be. Please feel free to share your code, trick, and even thoughts I'm all ears!

# Center Layout

keeping your App layout on center when the user's client exceeds the limit, so this is how you can center your App easily... like Github, Dev.to

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/k1bxfuny0eqc0bdewzow.png)


# Center Fixed Position

This code you help you to center your fixed positioned layout like ModelBox, PopUp... You may use these in your daily work if you didn't notice. different dev uses different code

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ivvgad92pcqceg6f7obj.png)


# Scroll Up/Down in fixed Position

let's say, you have a signup page before the user enters to the dashboard you want to show user agreement on fixed Position as you know agreement can be lengthy and on a fixed position, we can't scroll. to add scrolling on a fixed position

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/qq5cw4yr0mb33zntkmxk.png)

# Hide Scroll bar

This happens in the above example when the agreement becomes long, we don't want to show scroll bar. This is very useful in some cases like responsive Table, custom Tab and so on, and even scroll bar makes our layout worse or we can make our own scroll bar

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gzl0g5lovx4whqo5ukz7.png)

# Click every Where

In your SPA, when a user clicks on the list, you need to redirect, or show something. the first solution is to wrap the entire list in `<a> || <Link>` and second is by CSS.
This is going to be mind-blowing, the code we already familiar with it, but the use case we don't know. When I learn this trick, I shocked btw.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/a37k4gvc7u07nvkw071w.png)


# Thanks
I hope you enjoy this Article, Feel free to share your thoughts, tricks, solutions with us, we'll happy to learn something new from you guys, Have a Great Day!
Como configurar chaves SSH para duas ou mais contas no Github
Tags: ssh, autenticação, ptbr, braziliandevs
Published: 2020-06-20 16:05:09

---
title: Como configurar chaves SSH para duas ou mais contas no Github
published: true
description: Está contribuindo com um projeto que precisa que você utilize outra conta no Github/Bitbucket/Gitlab, configurou SSH e o clone não está indo? Chega aí. Imagem de capa de [@chunlea](https://unsplash.com/@chunlea)
tags: ssh,autenticação,ptbr,braziliandevs
cover_image: https://i.ibb.co/QjTdmdS/chunlea-ju-8fs1-X0-JFg-FE-unsplash.jpg
---

Imagino que você já tenha sua primeira conta configurada e está fazendo/já fez o [processo de autenticação SSH](https://help.github.com/en/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account) para a segunda conta, criando uma segunda chave e adicionando ao Github/Bitbucket/Gitlab/Outro da sua escolha e deu merda na hora de fazer o `git clone` do projeto.

## Como resolver

Dentro da pasta que guarda suas chaves, geralmente `~/.ssh` você vai criar um arquivo `config`.

Supondo que você quer deixar a chave que já está funcionando como default e quer que essa segunda chave funcione apenas para casos especiais, como esse repositório ou alguns repositórios que você vai fazer clone em seguida. Você vai adicionar uma regra no arquivo `~/.ssh/config` para esses repositórios:

```
Host caso-especial
  HostName github.com
  IdentityFile ~/.ssh/segundachave_id_rsa
```

Ao clonar o repositório, ao invés de usar o comando que o Git sugere, você vai usar algo como: `git clone git@caso-especial:organizacao-dono-do-repo/repo.git`. E tchana nana na.

![gif](https://media.giphy.com/media/l4FGIdh6jzW3MSszC/giphy.gif)
linux : package and service management
Tags: linux, cli
Published: 2020-06-20 16:03:29

# Package management

- First, we need to update our repository

```markdown
$ apt-get update
```

- Install a package

```markdown
$ apt-get install APPNAME
```

- Check if a package is already installed

```markdown
$ dpkg -l | grep APPNAME
```

- Remove a package

```markdown
$ apt-get remove APPNAME
```

- Search packages by a keyword

```markdown
$ apt-cache search “KEYWORD”
```

---

# Service management

- Check if a service is running

```markdown
$ systemctl status APPNAME
```

- Start a service

```markdown
$ systemctl start APPNAME
```

- Stop a service

```markdown
$ systemctl stop APPNAME
```

- Restart a service

```markdown
$ systemctl restart APPNAME 
```

- Check autostart enable

```markdown
$ systemctl is-enabled APPNAME 
```

- Enable autostart

```markdown
$ systemctl enable APPNAME 
```

- Disable autostart

```markdown
$ systemctl disable APPNAME 
```
Pempaltes: bootstrap your dev environment
Tags: showdev, javascript, svelte, webdev
Published: 2020-06-20 16:01:47

### About
[Pemplates](https://spicysalmon.tech/) allows you to search for project templates on github, bootstraping your productivity from "I have to setup everything from scratch" to "This is template I need, so I can start working on my project".

The use case behind this project is: "I want to create a desktop app using Electron and Svelte, but I have no idea how to setup everything". I went online and found a really good project that served as the starting point for Electron and Svelte app. But it took sometime to find it, so I decided to create Pemplates: a search engine for starter-kits, templates, ecc.

### How it works

- Choose what you want to search (templates, biolerplate, starter-kit)
- Enter keywords (ex: react electron)
- Press enter or click search button
- Choose the template from the list (list is ordered by stars count)
- Choose between git clone or degit
- By clicking on one of those the command will be copied tou your clipboard.
- Open terminal and execute the copied command in order to create a project.
- Start developing


### Final words

[Pemplates](https://spicysalmon.tech/) is free to use and open source (made wit [Svelte3](https://svelte.dev/), [source code is on github](https://github.com/OleksandrDemian/pemplates_lite_web)). I hope you can find it useful.
Sequencing Fibonacci numbers
Tags: javascript, challenge, code, algorithms
Published: 2020-06-20 16:01:39

>By definition, the first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.

The Fibonacci series is an ordering of numbers where
each number is the sum of the preceding two.

Here is an example of the Fibonacci Sequence 
>0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ….

###Challenge
```
Print out the n-th entry in the Fibonacci series.
For example, the sequence [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] forms the first ten entries of the Fibonacci series.
Example:
fib(4) === 3
```
How Fibonacci works is to look at two previous numbers and add them together. Since we know we are starting with zero and one, the best way would be to just manually insert 0 and 1 into the result set.
```javascript
function fibonacci(n) {
  const result = [0,1];
}
```
Now we will use a for loop to start from a number that is on [2] and iterate all the way to the n number.
```javascript
function fibonacci(n) {
  const result = [0,1];
 for (let i = 2; i <= n; i++) {
  }
}
```
In the for loop, we will need to pull previous two number that is in `const result ` and we will add them together and push back to `const result`.
```javascript
function fibonacci(n) {
  const result = [0,1];
 for (let i = 2; i <= n; i++) {
   const a = result[i - 1];
   const b = result[i - 2];
  }
}
```
We will add these two numbers together and push it to `const result` and return entry (n) from result.
```javascript
function fibonacci(n) {
  const result = [0,1];
 for (let i = 2; i <= n; i++) {
   const a = result[i - 1];
   const b = result[i - 2];
   
   result.push(a + b);
  }
  return result[n];
}
```


Let's solve this problem using a recursive solution.
 
```javascript
function fibonacci(n) {
  if (n < 2) {
     return n
   }
  return fib(n - 1) + fib(n - 2);
}
```
This would be exponential runtime, the fibonnaci function is being called multiple times with the same exact arguments. 

To improve the runtime, we can use *memoization*. 
**Memoization** - store the arguments of each function call along with the result. If the function is called again with the same arguments, return the precomputed result, rather than running the function again. 
```javascript
var cache = {};

function fibonacci(number) {
    
    if (number < 1)
        return 0;

    if (number <= 2)
        return 1;
    
    if (number in cache)
        return cache[number];
    
    var value = fibonacci(number- 1) + fibonacci(number - 2);
        
    cache[number] = value;

    return value;
}
```
Using a variable `var cache` will remember function execution result and if the arguments for the future function execution are already in the cache we will simply return this value. 

Memoization will assure us that for each number Fibonacci function will only be executed once.
Writing posts with interactive code snippets is awesome
Tags: javascript
Published: 2020-06-20 15:59:28

---
title: Writing posts with interactive code snippets is awesome
published: true
description: Nothing to see here, it's just me sharing some links
tags: #javascript 
//cover_image: https://direct_url_to_image.jpg
---

I've been putting some of my content in [observablehq](https://observablehq.com/) notebooks and it has been fun. You can play around with every code snippet (even the one that are "hidden").

This one was specially fun because there is form involve in the proccess.
 - [Using the Maybe type in js](https://observablehq.com/@vonheikemen/using-the-maybe-type-in-js)

Anywho, this what I got so far:
- [(Array) Reduce: How and when](https://observablehq.com/@vonheikemen/reduce-how-and-when)
- [Partial application in javascript](https://observablehq.com/@vonheikemen/partial-application-in-javascript)
- [Composition techniques](https://observablehq.com/@vonheikemen/composition-techniques-in-js)
- [About Functors](https://observablehq.com/@vonheikemen/about-functors)
- [Tagged unions and Fantasy Land](https://observablehq.com/@vonheikemen/tagged-unions-and-fantasy-land-in-js)
Algorithms Problem Solving: Odd in Matrix
Tags: algorithms, python, computerscience, interview
Published: 2020-06-20 15:36:21

---
title: Algorithms Problem Solving: Odd in Matrix
published: true
description: Solving algorithms problems with TK
tags: algorithms, python, computerscience, interview
cover_image: https://raw.githubusercontent.com/leandrotk/tk/master/series/algorithms-problem-solving/assets/matrix.jpg
canonical_url: https://leandrotk.github.io/tk/series/algorithms-problem-solving/odd-in-matrix
series: Algorithms Problem Solving Series
---

This post is part of the [Algorithms Problem Solving](https://leandrotk.github.io/tk/series/algorithms-problem-solving/index.html) series.

## Problem description

This is the [Odd in Matrix](https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/) problem. The description looks like this:

Given `n` and `m` which are the dimensions of a matrix initialized by zeros and given an array `indices` where `indices[i] = [ri, ci]`. For each pair of `[ri, ci]` you have to increment all cells in row `ri` and column `ci` by 1.

Return *the number of cells with odd values* in the matrix after applying the increment to all `indices`.

## Examples

```python
Input: n = 2, m = 3, indices = [[0,1],[1,1]]
Output: 6

Input: n = 2, m = 2, indices = [[1,1],[0,0]]
Output: 0
```

## Solution

- Initialize the matrix with all elements as zero
- For each pair of indices, increment for the row, and increment for the column
- Traverse the matrix counting all the odd numbers
- Return the counter

```python
def init_matrix(rows, columns):
    return [[0 for _ in range(columns)] for _ in range(rows)]

def odd_cells(n, m, indices):
    matrix = init_matrix(n, m)

    for [ri, ci] in indices:
        for column in range(m):
            matrix[ri][column] += 1

        for row in range(n):
            matrix[row][ci] += 1

    odds = 0

    for row in range(n):
        for column in range(m):
            if matrix[row][column] % 2 != 0:
                odds += 1

    return odds
```

## Resources

- [Learning Python: From Zero to Hero](https://leandrotk.github.io/tk/2017/09/learning-python-from-zero-to-hero/index.html)
- [Algorithms Problem Solving Series](https://leandrotk.github.io/tk/series/algorithms-problem-solving/index.html)
- [Stack Data Structure](https://leandrotk.github.io/tk/2020/01/stack-data-structure/index.html)
- [Queue Data Structure](https://leandrotk.github.io/tk/2020/01/queue-data-structure/index.html)
- [Linked List](https://leandrotk.github.io/tk/2020/02/linked-list/index.html)
- [Tree Data Structure](https://leandrotk.github.io/tk/2020/02/tree-data-structure/index.html)
6 very useful hooks from react-use library
Tags: javascript, react, reactnative
Published: 2020-06-20 15:35:22

If you're a ReactJS developer, even if you're learning the library, there are some hooks that almost every app needs and it's a little bit frustrating re-write every time. React-use is a collection of hooks perfect for this kinda a situation, and you'll never drop it after use it 

👉🏻 Check the entire post on Instagram: https://devinda.house/2020-06-20
⠀⠀⠀⠀⠀⠀⠀⠀⠀⁣⁣⁣
Liked this post? 💬 Comment 🤝 Share on your Instagram stories and mark us 💙 Like it and 👉🏻 Follow us to daily content of #programming, #javascript, #reactjs and more 🙏🏻⁣⁣⁣
⠀⠀⠀⠀⠀⠀⠀⠀⠀⁣⁣⁣
📨 Send us your feedback, if you want to make a partnership or have something to talk, please send us an email to talk@devindahouse.com⁣⁣⁣
User-defined Exception in Python
Tags: python
Published: 2020-06-20 15:32:03

You are going to learn how to create a Python user defined exception.

There's all kinds of exceptions like ZeroDivisionError, IndexError, ImportError, TypeError and more. 

Python is packed with several built-in exceptions like 

* **ZeroDivisionError**
* **ImportError**
* **TypeError** 
* **ModuleNotFoundError**

## Exceptions

Python will show those exceptions when something goes wrong like:

```python
>>> x = 1 / 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
```

or loading a non existing module

```python
>>> import life
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'life'
```

## Custom Exceptions

However you can **Create your own personalized exceptions** Python allows us to create our exception from the exception base class.

Python usually throws exceptions in the <a href="https://pythonbasics.org/try-except/">try-except</a> statement.    
    
```python
    try:
        #statement or line of code
    except customError:
        #statement or line of code
```    

All kinds of exceptions can be <a href="https://gitpress.io/u/1282/exceptions">raised</a>. So how do you make your own exception type? 

You create a <a href="https://pythonspot.com/objects-and-classes/">class</a> that <a href="https://pythonprogramminglanguage.com/inheritance/">inherits</a> from the exception class

```python
>>> class CustomException(Exception):
...     def __init__(self, statement, s):
...         self.statement = statement
...         self.s = s
...         print(self.statement)
... 
```

You can also add a <a href="https://python-commandments.org/python-pass-statement-keyword/">pass</a> statement instead of a <a href="https://pythonprogramminglanguage.com/constructor/">constructor</a>.

Then you can raise your own exceptions:

```python
>>> raise CustomException("went wrong", 3)
went wrong
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.CustomException: ('went wrong', 3)
>>> 
```
A journey to System Design
Tags: webdev, learning, programming, backend
Published: 2020-06-20 15:27:37

## Hello there, coders! 
I hope you are all doing great during COVID times. Nowadays, many of us have found ourselves with much more time on our hands. Many of us utilize this extra time by learning something new, picking up a new hobby, going on a reading spree, or the good old fashioned path of playing video games. I am no different. I have picked the first and the last. I'll be learning Back-end Engineering and System Design, whereas I'll be playing League of Legends and Valorant on the side.

###A little about me
Until now, I have mainly worked with front-end technologies like Flutter and roughly just for six months on back-end technologies like Java Spring. The reason I shifted was because of my previous internship requiring me to work on Spring Boot. But I feel that I never learned the art of back-end inside out. Instead, I quickly went over stuff in an attempt to get work done for my internship. Hence I have decided to use my free time with learning back-end engineering from the start, reaching up to the point of being able to design highly available, reliable, and scalable systems.

###Why am I sharing this?
*"If you can't explain it simply, you don't understand it well enough."*
*- Albert Einstein*

I feel sharing my learning here helps us both -
- Be a part of this journey and learn something new. If you are already in this domain, you can guide people like me, so we grow as a community.
- Writing will help me understand better. I'll be able to find loopholes in my concepts.
- You can correct me if I am wrong about anything, that way we both learn together.

That's it for this post. I plan to post at least once every week. So stay tuned for the upcoming topics.