teleren/devto huggingface dataset:
Day 14 of #100DaysOfCode: Redux (use useSelect and useDispatch instead of connect)
Tags: 100daysofcode, react, redux, javascript
Published: 2020-05-09 15:21:21

## Introduction
We have learned Redux on Day 12 (useSelect and useDispatch). 
However, it's complex to connect the child component with actions and states. We can use *useSelect* and *useDispatch* to connect the child component with global states.   

## Roles
1.Reducer and actions
* As same as Day 12
```javascript
const { combineReducers } = Redux;

//types
const GET_PRODUCTS = 'GET_PRODUCTS';

//reducer
const initState = {
    products: [],
}

const ShoppingCartReducer = (state = initState, action) => {
    switch(action.type) {
        case GET_PRODUCTS:
            return {
                ...state,
                products: action.payload
            }
        default:
            return state; 
    }
} 

const rootReducer = combineReducers({
    products: ShoppingCartReducer
});

//action
const getProducts = () => ({
    type: GET_PRODUCTS, 
    payload: [{
        category: 'food',
        name: 'noodles',
        size:'large',
        price:100      
    },{
        category: 'food2',
        name: 'noodles',
        size:'small',
        price:50      
    },{
        category: 'food',
        name: 'rice',
        size:'large',
        price:120      
    }]
});

```
2.store
* As same as Day 12
```javascript
const { createStore } = Redux;

//store
const store = createStore(
    rootReducer
);
```

3.Provider and the parent component
* As same as Day 12
```javascript
const { Provider} = ReactRedux;

const app = (
    <Provider store={ store }>
        <ContentContainer/>
    </Provider>
);
```

4.The child component and useSelect, useDispatch
```javascript
const { useDispatch, useSelector } = ReactRedux;
const selectProducts = (rootState) => rootState.products.products;

//child component
const Content = () => {
    const disPatch = useDispatch();
  disPatch(getProducts());
    return (
        <Menu/>
    )
}

const Menu = () => {
   const products = useSelector(selectProducts);
   return (
        <div className="container menu-container">
            <div className="row">
                {products.map(product => (
                    <MenuItem product = {product}/>
                ))}
            </div>
        </div>
    )
}

```

## Implementations

{% codepen https://codepen.io/JenHsuan/pen/LYpmVbo %}  

## Articles
There are some of my articles. Feel free to check if you like! 
* My blog-posts for software developing: https://medium.com/a-layman
* My web resume: https://jenhsuan.github.io/ALayman/cover.html
* Facebook page: https://www.facebook.com/imalayman
[REMINDER-6] Object.assign/setPrototypeOf
Tags: javascript, vue
Published: 2020-05-09 15:04:10

## ASSIGN

`this method copies all the enumerable own properties of one or more objects into another`

It mean's values are cloned, and objects references are copied live for vuejs < 3 (I didn't check for vue 3 reactivity but it's different normally).

example:

```js
const original = {
  name: 'Fiesta',
  car: {
    color: 'blue'
  }
}

const copied = Object.assign({}, original)

original.name = 'Focus'
original.car.color = 'yellow'

copied.name //Fiesta
copied.car.color //yellow
```

Name doesn't change everywhere because it's not an object. For car yes and no matter if you change the copied object or the orignal one.


IMPORTANT: Spread operator does the same because it uses Object.assign behind the scene

```js
const original = {
  name: 'Fiesta',
  car: {
    color: 'blue'
  }
}

const copied = {...original}

original.name = 'Focus'
original.car.color = 'yellow'

copied.name //Fiesta
copied.car.color //yellow
```

## setPrototypeOf

Copy all proto values from an object to another one.

```js

const animal = {
  isAnimal: true
}
const mammal = {
  isMammal: true
}

// mammal.__proto__ = animal
Object.setPrototypeOf(animal, mammal). // Same as doing before
```
Git Line Endings
Tags: git
Published: 2023-01-06 01:23:35

---
title: Git Line Endings
published: true
date: 2020-05-09 15:01:21 UTC
tags: Git
canonical_url: https://brandonrozek.com/blog/gitlineendings/
---

if you have worked with a team that has a mix of Windows and Linux developers, you might have noticed pull requests where Git reports changes in a file that is not visible. One explanation is that the line endings might have changed.

Due to historical reasons Windows uses a line ending called CRLF which stands for carriage return + line feed. This dates back to type writers where once you hit the line feed button to push the paper up, you need to press the carriage return button to move back to the left side of the paper. [Wikipedia](https://en.wikipedia.org/wiki/Carriage_return) has more of a history if you want to learn more.

Meanwhile, Linux only uses LF or line feed for its ending. We can configure a repository with a `.gitattributes` file to automatically convert CRLF to LF line endings in order not to see these frivolous changes in our repository.

The `.gitattributes` file looks like this

```
# Automatically convert CRLF->LF on files git thinks are text
* text=auto

# Explicitly declare what are text files
*.py text
*.js text

# Denote files that are binary and should not be modified.
*.png binary
*.jpg binary

```

Make sure that you don’t have any working changes that need to be committed as the following commands will convert all the line endings for text files in your repository to LF.

First let us commit the git attributes file

```
git add .gitattributes
git commit -m "Added gitattributes file"

```

Then let us convert all the line endings to LF

```
git add --renormalize .
git commit -m "Convert line endings to LF"

```

Then tell your coworkers to expect a large commit which only line ending changes….
Auto Deploy reason-react projects on Netlify
Tags: reason, react, netlify
Published: 2020-05-09 14:57:52

Auto deploy your Reason React project from Github to Netlify. When you push to Git, Netlify will auto deploy your project.

![Reason with Netlify](https://res.cloudinary.com/bodhi/image/upload/v1589035939/blogs/09-05-Auto%20Deploy%20reason-react%20projects%20on%20Netlify/1_CBtMXuN2P2uIM-d5FOWadw_aujucf.png)

If you don’t have a project, you can get the basic setup instruction in  [reason react official documentation](https://reasonml.github.io/reason-react/docs/en/installation).

**Steps:**

### 1. Login/sign-up to  [https://netlify.com](https://www.netlify.com/)

### 2. Click on “New site from Git” button

![Netlify Dashboard](https://res.cloudinary.com/bodhi/image/upload/v1589035939/blogs/09-05-Auto%20Deploy%20reason-react%20projects%20on%20Netlify/1_0YshPY2e97MkJBwWX2V7ig_tvzzqq.png)

### 3. Choose the Git provider where your site’s source code is hosted

![Create Site](https://res.cloudinary.com/bodhi/image/upload/v1589035941/blogs/09-05-Auto%20Deploy%20reason-react%20projects%20on%20Netlify/1_V8aW25KGIpkDcUUxZbGIsA_erbiqp.png)

### 4. Choose the repository you want to link to your site on Netlify.

![Create a netlify site](https://res.cloudinary.com/bodhi/image/upload/v1589035942/blogs/09-05-Auto%20Deploy%20reason-react%20projects%20on%20Netlify/1_6MTGBq1plsZ_KCFvhl7-SA_wahj9c.png)

### 5. Choose the branch to deploy and give the build commands and publish directory.

![Deploy](https://res.cloudinary.com/bodhi/image/upload/v1589035944/blogs/09-05-Auto%20Deploy%20reason-react%20projects%20on%20Netlify/1_fr4mgLRwiW95OA91uiNqfw_mtrbfd.png)

## Build command

```
npm run clean && npm run build && npm run webpack:production
```

## Publish directory
```
build
```

Fill-in the details and click “Deploy Site” button.

Your site will get deployed in 5 mins, All other commits you make to the branch you select will get auto deployed to Netlify :D
What’s your alternative solution? Challenge #39
Tags: challenge, javascript, codenewbie, learntocode
Published: 2020-05-09 14:52:09

# About this series

This is series of daily JavaScript coding challenges... for both beginners and advanced users.

Each day I’m gone present you a very simple coding challenge, together with the solution. The solution is intentionally written in a didactic way using classic JavaScript syntax in order to be accessible to coders of all levels.

Solutions are designed with increase level of complexity.

## Today’s coding challenge

```
Create a function that will return an array with words inside a text

```

(scroll down for solution)

## Code newbies

If you are a code newbie, try to work on the solution on your own. After you finish it, or if you need help, please consult the provided solution.

## Advanced developers

Please provide alternative solutions in the comments below. 

You can solve it using functional concepts or solve it using a different algorithm... or just solve it using the latest ES innovations.

By providing a new solution you can show code newbies different ways to solve the same problem.

## Solution

```javascript
// Solution for challenge34

var text = "Create a function, that will return an array (of string), with the words inside the text";

println(getWords(text));

function getWords(text)
{
    let startWord = -1;
    let ar = [];
    
    for(let i = 0; i <= text.length; i++)
    {
        let c = i < text.length ? text[i] : " ";

        if (!isSeparator(c) && startWord < 0)
        {
            startWord = i;
        }
        
        if (isSeparator(c) && startWord >= 0)
        {
            let word = text.substring(startWord, i);
            ar.push(word);
            
            startWord = -1;
        }
    }

    return ar;
}

function isSeparator(c)
{
    var separators = [" ", "\t", "\n", "\r", ",", ";", ".", "!", "?", "(", ")"];
    return separators.includes(c);
}

```


To quickly verify this solution, copy the code above in this coding [editor](https://codeguppy.com/code.html) and press "Run".

> Note: The solution was originally designed for [codeguppy.com](https://codeguppy.com) environment, and therefore is making use of `println`. This is the almost equivalent of `console.log` in other environments. Please feel free to use your preferred coding playground / environment when implementing your solution.
[REMINDER-5] Promise.race()
Tags: javascript, vue
Published: 2020-05-09 14:44:15

`Promise.race() runs as soon as one of the promises you pass to it resolves, and it runs the attached callback just once with the result of the first promise resolved.`

example:
```js
const promiseOne = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, 'one')
})
const promiseTwo = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'two')
})

Promise.race([promiseOne, promiseTwo]).then(result => {
  console.log(result) // 'two'
})
```

More important here is to know a use case. I don't have really use case for that.. But in case you want to execute a function as soons as possible or maybe if you are implementing a rendering and call an api at the same time. If the rendering fail at some point. The api call will stop too.

That's it for this reminder
Javascript Numbers
Tags: javascript, beginners, webdev, tutorial
Published: 2020-05-09 13:44:59

This post will cover topics related to assignment, condition and type checking of Numbers.

Assigning integer and float value to a number.
----------------------------------------------
```javascript
var salary = 25000; //this is integer value
var average = 2.569; //this is float value 
```
typeof Reserved Word
--------------------

Using `typeof` is a reserved word that used to get the type of variable whether it may be integer, float, object, array and strings etc.
```javascript
var name = "John";
var age = 21;
var total_marks = 456.26;

console.log(typeof name);
console.log(typeof age);
console.log(typeof total_marks);
```
![JavaScript Numbers using type of keyword](http://thecodelearners.com/wp-content/uploads/2020/04/JavaScript-Number-Example-1-300x249.jpg)

NaN reserved word
-----------------

NaN means Not a Number, these cannot be used to perform the mathematical operation.
```javascript
var fruit = "orange";
fruit=fruit*2;
```
![JavaScript Number multiplying strings with numbers](http://thecodelearners.com/wp-content/uploads/2020/04/JavaScript-Number-Example-2-300x175.jpg) By using with if conditions.
```javascript
var fruit = "orange";
if(isNaN(fruit)){
    console.log("This is not a number");
}else{
    console.log("This is a number");
}

//Console Output
This is not a number
```
Using `===` equal to operator
-------------------------------

Using `===` will not only check if the value is equal but also check if is of equal type.

## using `==` equal to operator.
```javascript
x = "10";
y = 10;
if(x==y){
    console.log("Value of x is equal to y");
}else{
    console.log("Value of x is not equal to y");
}

//Console Output
Value of x is equal to y
```
## using `===` equal to operator.
```javascript
x = "10";
y = 10;
if(x===y){
    console.log("Value of x is equal to y");
}else{
    console.log("Value of x is not equal to y");
}

//Console Output
Value of x is not equal to y
```
You can find the original post [here](http://thecodelearners.com/javascript-numbers-assignment-type-checking-and-nan/)
CRUD de usuarios en NodeJS: Parte 2
Tags: node, express, mongodb, serverjs
Published: 2020-05-09 13:44:28

Ahora toca ponerse con la base de datos, para ello vamos a usar [MongoDB](https://www.mongodb.com/cloud/atlas). En mi caso utilizo el servicio de cloud y creo que para este proyecto es lo más rápido. Si lo prefieres ejecutar de manera local, [aquí](https://docs.mongodb.com/manual/administration/install-community/) tienes la documentación para instalar y usar según tu SO.

Una vez hayamos configurado todo y tengamos nuestro servicio de MongoDB operativo, vamos a la carpeta de nuestro proyecto, tal y como lo habíamos llamado es rest-server y ejecutamos el siguiente comando en nuestra terminal.

```
    $ npm install mongoose --save
```

Cuando se haya completado la instalación de mongoose vamos a editar el código de nuestro fichero server.js, que está dentro de la carpeta server, añadiendo lo siguiente:

```javascript
    const mongoose = require('mongoose');
    const run = async () => {
        await mongoose.connect(SERVER_BBDD, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useCreateIndex: true,
        });
    };

    run().catch(error => console.error(error));
```

Debes cambiar el **SERVER_BBDD** por tu servidor. Si es local, será algo así *mongodb://localhost:27017/usuarios*, **usuarios** es el nombre de la base de datos que vamos a usar. Si no está creada, se creará automáticamente. En caso de ser en cloud será algo así: *mongodb+srv://FuenRob:<password>@cluster0-nixve.mongodb.net/usuarios?retryWrites=true&w=majority*

Una vez hayamos añadido este código a nuestro fichero server.js, quedará así:
```javascript
    const express = require('express');
    const mongoose = require('mongoose');

    const run = async () => {
        await mongoose.connect(SERVER_BBDD, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useCreateIndex: true,
        });
    };

    run().catch(error => console.error(error));

    app.listen(process.env.PORT, () => {
         console.log(`Escuchando en el puerto 3000`);
    });
```

Si vamos a nuestra terminal y lanzamos en la raíz de nuestro proyecto el comando para levantar el servidor:

```
    $ node server/server.js
```

Veremos en nuestro terminal que, en caso de que no haya sucedido ningún error y de que nos hayamos conectado correctamente a nuestro servidor de base de datos, volveremos a recibir el mensaje de *Escuchando en el puerto 3000*. 

En caso de que tengamos algún problema para conectar con el servidor de base de datos, esta línea de código nos mostrará en nuestro terminal cuál es el error *run().catch(error => console.error(error))*.
How Does HTTP Works ? (Explained with Demo) |  30 Days of API Testing  | Day 4
Tags: testing, tutorial, beginners, webdev
Published: 2020-05-09 13:38:48

In this video, We are going to understand How does HTTP works?,

HTTP is a connectionless text-based protocol. Clients (web browsers) send requests to web servers for web elements such as web pages and images.

After the request is serviced by a server, the connection between client and server across the Internet is disconnected.

[![30 Days of API Testing](https://i.imgur.com/LEgiEiE.png)](https://youtu.be/9raRuaFPJw0 "30 Days of API Testing")


Source. : https://www.ministryoftesting.com/dojo/lessons/30-days-of-api-testing


👉 Master API Testing(Full Course) -  https://www.learnapitesting.com

👉 Become Automation Tester - https://sendfox.com/thetestingacademy

--
Be sure to subscribe for more videos like this!

[![ TheTestingAcademy](https://dev-to-uploads.s3.amazonaws.com/i/r7vcy6wbvyjbk1y1uu0o.png
)](https://www.youtube.com/TheTestingAcademy?sub_confirmation=1 "TheTestingAcademy")
How can I fix the post's cover image on social media
Tags: help
Published: 2020-05-09 13:38:27

---
title: How can I fix the post's cover image on social media
published: true
tags: help
---

I am designing my own post's cover images and adding them using the `cover_image` metadata attribute.

In the question mark help section, It says `The best size is 1000 x 420.` This works perfectly on dev.to but when you share the post on Facebook, Linkedin, or Twitter.

That `1000 x 420` cover image gets cropped around the edges. Is there a way to fix that?
Multi developer environments on AWS using Gitlab + Terraform + Serverless + React
Tags: terraform, serverless, gitlab, aws
Published: 2020-05-09 13:38:20

I've wrote a post on medium about how to have different dev environments on AWS. So if you have some problems when your developers want to have their own environment to run test like and the official one, please check it out.

https://medium.com/dnx-labs/multi-developer-environments-on-aws-using-gitlab-terraform-serverless-react-2f763e11edda?utm_source=devto
Freelancers! How are you holding up?
Tags: webdev, discuss, career
Published: 2020-05-09 13:31:18

---
title: Freelancers! How are you holding up?
published: true
description: Just a quick question
tags: webdev, discussion, career
cover_image: https://images.unsplash.com/photo-1486002113024-43b2ce358eb0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1072&q=80
---

I am wondering how the freelancers of you are doing during this pandemic. While I honestly enjoy a little break from consumerism and taking everything a tad slower I can't help but to feel a little worried. I am a senior Frontend developer with many years of experience and before Corona things went very very smoothly. But since January I hadn't had a single project request that went anywhere and all my own attempts to contact companies have been quite fruitless as well. 

Am I the only one? How are you doing? What are your strategies to get through this economically? Do you think things will normalize again at some point or is this the end of an era?
REST Explained in 5 mins | 30 Days of API Testing | Day 5
Tags: testing, tutorial, webdev, beginners
Published: 2020-05-09 13:26:02

🚀 Mastering API Testing(Full Course) -  https://www.learnapitesting.com

In this video of 30 Days of API Testing Challenge, We are going to understand the REST Explained and API Testing Examples.

> Day 5 Task: Contribute to the list of publicly available APIs.

[![30 Days of API Testing](https://i.imgur.com/VeINfLn.png)](https://youtu.be/WCwofnisiFY "30 Days of API Testing")


Resources : 
- https://jsonplaceholder.typicode.com/
- https://www.programmableweb.com/category/all/apis?keyword=publicly%20available%20APIs

🚀 BONUS VIDEO 🚀

What is REST — A Simple Explanation for Beginners,
https://bit.ly/restapitutorial

--
Be sure to subscribe for more videos like this!

[![ TheTestingAcademy](https://dev-to-uploads.s3.amazonaws.com/i/r7vcy6wbvyjbk1y1uu0o.png
)](https://www.youtube.com/TheTestingAcademy?sub_confirmation=1 "TheTestingAcademy")
My First VSCode Theme -- Dark Lavender
Tags: vscode, theme, dark
Published: 2020-05-09 13:22:02

This is my first VSCode theme -- Dark Lavender, design with material colors.

This is a high color diversity theme, purple is the main color for active item so I name it Dark Lavender. Language keyword is render in italic to make developer can tell from how the code look like.

![dark-lavender](https://raw.githubusercontent.com/t7yang/dark-lavender/master/images/screenshot.png)

If you like my theme, share and star :)

VSCode market: https://marketplace.visualstudio.com/items?itemName=t7yang.dark-lavender

Source Code: https://github.com/t7yang/dark-lavender
What Is the Scope of API Testing in Terms of Job Prospects? | 30 Days of API Testing | Day 6
Tags: testing, tutorial, beginners, webdev
Published: 2020-05-09 13:21:25

🚀Mastering API Testing(Full Course) -  https://www.learnapitesting.com

In this video of 30 Days of API Testing Challenge, I am sharing,y favorite API Testing blogs and also going to discuss What is the scope of API testing in terms of job prospects?

> Day 6 Task: Share API Testing Blogs.

API Testing Resources - https://www.one-tab.com/page/ZXKnBSB_TZWBj3-ReGqCWA

[![30 Days of API Testing](https://i.imgur.com/K7tyXBm.png)](https://youtu.be/1iD9hqqKFgc "30 Days of API Testing")



🚀 BONUS VIDEO 🚀

What is REST — A Simple Explanation for Beginners,
https://bit.ly/restapitutorial

--
Be sure to subscribe for more videos like this!

[![ TheTestingAcademy](https://dev-to-uploads.s3.amazonaws.com/i/r7vcy6wbvyjbk1y1uu0o.png
)](https://www.youtube.com/TheTestingAcademy?sub_confirmation=1 "TheTestingAcademy")
How to become a better Code Reviewer - Part 3 : How to write code review comments?
Tags: codenewbie, computerscience, csharp, java
Published: 2020-05-09 13:03:55

When it comes to writing code review comments do make sure that you are polite ,kind and encourage developers .


------------------

- **<h3><strong>Respect:</strong></h3>**

1) Be kind and helpful to the developer whose code you are reviewing.
2) Make sure that you always comment about the code and not about the developer.

<img src="https://media1.tenor.com/images/8fbbcce8f5a028d11ba58e12c3eafa61/tenor.gif?itemid=12849792" width="4096" />


------------------

- **<h3><strong>Explanation:</strong></h3>**

1) Always make sure to explain why you are making the comment 
2) Try to give a "good/valid" example so that it would help developer to understand. It is always necessary to provide examples.

<img src="https://media1.tenor.com/images/25e7b0e804013a97b35eb2d61e7caad9/tenor.gif?itemid=14522860" width="4096" />

------------------

- **<h3><strong>Guidance:</strong></h3>**

1) Don't provide the solution or write code for developer rather provide useful information so that it is developer's responsibility to fix a change list.
2) Maintain a balance between pointing out the problems and providing a guidance.


------------------

**<h3><strong>Thanks:</strong></h3>**

Thanks all for reading through this series . Hope you will be trying to implement this in real time practices and become a better code reviewer. If you like my post please do give feedback below , i will try to change if there are any mistakes in my future posts.


Banner Image Courtesy : <a href="https://www.freepik.com/free-photos-vectors/business">Business vector created by freepik - </a><a href="http://www.freepik.com">www.freepik.com</a>
4 new challenges
Tags: javascript, webdev
Published: 2020-05-09 13:01:01

Just now I've added four new challenges to the ranked mode. Two medium, a hard and an extreme one.

The hard one is interesting due to its simplicity of string operations.
The extreme one is related to the N queen problem solved using bitwise operations, try to crack the code!

Codr: https://nevolin.be/codr/