teleren/devto huggingface dataset:
ReScript: Using useReducer in rescript-react
Tags: rescript, react
Published: 2021-01-27 11:06:22

React's `useReducer` is great when the states get more complex than a simple value. rescript-react `useReducer` is even better with ReScript's [variants](https://rescript-lang.org/docs/manual/latest/variant).

Let's update the code from our [`useState`](https://dev.to/believer/rescript-using-usestate-in-reasonreact-ong-temp-slug-8985734)implementation step by step to use `useReducer`.

```rescript
type state = DisplayValue | HideValue

type action = Toggle
```

These types define the state and actions of our reducer. Since we only want to toggle a value, we'll use a variant for the state with two possible values, `DisplayValue` or `HideValue`. We then define the actions we can dispatch to update the state. In this case, we only need one action to `Toggle` the `state`.

```rescript
let (state, dispatch) = React.useReducer((state, action) => {
  switch action {
  | Toggle =>
    switch state {
    | DisplayValue => HideValue
    | HideValue => DisplayValue
    }
  }
}, HideValue)
```

We replace the `useState` hook with this `useReducer` hook. The reducer uses [pattern matching](https://rescript-lang.org/docs/manual/latest/pattern-matching-destructuring#switch-based-on-shape-of-data)on the action and toggles the state depending on the current state.

The types of `state` and `dispatch` are inferred from the usage as our `state` type and `action => unit` respectively.

```rescript
<div>
  {switch state {
  | DisplayValue => React.string("The best value")
  | HideValue => React.null
  }}
  <Button onClick={_ => dispatch(Toggle)}> {React.string("Toggle value")} </Button>
</div>
```

The updated view part uses another pattern match on the `state` to either display the value or display nothing. The `onClick` function now uses `dispatch` to pass the `Toggle` action to the reducer.

The complete code would look like this

```rescript
type state = DisplayValue | HideValue

type action = Toggle

@react.component
let make = () => {
  let (state, dispatch) = React.useReducer((state, action) => {
    switch action {
    | Toggle =>
      switch state {
      | DisplayValue => HideValue
      | HideValue => DisplayValue
      }
    }
  }, HideValue)

  <div>
    {switch state {
    | DisplayValue => React.string("The best value")
    | HideValue => React.null
    }}
    <Button onClick={_ => dispatch(Toggle)}> {React.string("Toggle value")} </Button>
  </div>
}
```

This is a simple example that achieves the same thing as our `useState` component did but in a more complex manner. However, if we wanted to add a dedicated `Display` or `Hide` action the compiler would be able to help us so that we don't miss handling any cases in our implementation.
ReScript: Using useState in rescript-react
Tags: rescript, react
Published: 2021-01-27 11:06:14

React has a `useState` hook that's great for keeping track of some simple state. rescript-react also has this hook, but the API is a bit different in that it only contains the function variations of `useState`. Here's a basic example that extends the example we [created previously](https://dev.to/believer/rescript-using-react-components-4p58-temp-slug-3842775).

```rescript
@react.component
let make = () => {
  let (displayValue, setDisplayValue) = React.useState(() => false)

  <div>
    {displayValue ? React.string("The best value") : React.null}
    <Button onClick={_ => setDisplayValue(displayValue => !displayValue)}>
      {React.string("Toggle value")}
    </Button>
  </div>
}
```

`React.useState` takes a function where the return value is our initial state. In return, we get a [`tuple`](https://rescript-lang.org/docs/manual/latest/tuple) of the current state and a setter. The types for the return values are inferred from the initial state. In this case the types are `bool` for `displayValue` and `(bool => bool) => unit` for `setDisplayValue`.

We could then use the value, defined as `displayValue` in our example, to conditionally display a text. Both sides of the ternary need to have the same type so we use `React.null`, which maps to `React.element` like `React.string`does, when we don't want to display anything.

To update the value we call the setter function, defined as `setDisplayValue` in our example. In this case, we toggle the `displayValue` based on the previous value.

The [bindings for `useState`](https://github.com/reasonml/reason-react/blob/master/src/React.re#L192) to the React implementation acknowledges that the API isn't the best, but the only way to implement the state with type safety. The recommendation is to [use `useReducer`](https://willcodefor.beer/posts/using-usereducer-in-reasonreact/) whenever possible.
ReScript: Adding a third-party library
Tags: rescript
Published: 2021-01-27 11:06:07

Sometimes we want to include a library that extends our code. To add a third-party library to our ReScript code we use `npm` as we would in a JavaScript project, but after installing we need to adjust our ReScript configuration to include the new code.

We start by installing the library using `npm` or `yarn`. For this example, I'll be using [`@opendevtools/rescript-telefonnummer`](https://github.com/opendevtools/rescript-telefonnummer).

```shell
npm install --save @opendevtools/rescript-telefonnummer
```

After the installation is complete we need to add the library name in our `bsconfig.json` in the `bs-dependencies` array.

```json
// bsconfig.json
{
  ...
  "bs-dependencies": [
    ...,
    "@opendevtools/rescript-telefonnummer"
  ]
}
```

After saving, the compiler will pick up that a change has been made in the configuration and build the library. We're now ready to start using the library in our code.
ReScript: Using React components
Tags: rescript, react
Published: 2021-01-27 11:05:51

In [the previous post](https://dev.to/believer/rescript-creating-a-react-component-mbi), we learned how to create React components in ReScript. In this post, we'll learn how to import and use them in other components. We'll start by making some adjustments to the `<Button>` we created.

```rescript
// Button.res
@react.component
let make = (~children, ~onClick) => {
  <button onClick> children </button>
}
```

We have changed the button child from `React.string("Click me")` to `children`and added a prop for `~children` in the component function. This way we can reuse the button with different contents. The type of the `children` prop is inferred as`React.element` and it is **required**.

```rescript
// App.res
@react.component
let make = () => {
  <div> <Button /> </div>
}
```

Here we use our `<Button>` component inside another component called `<App>`. As we saw in the last post, all files are modules and globally available in ReScript. Therefore we can add the `<Button>` to our JSX without having to import any files beforehand.

If we save now, we get an error in the compiler that we are missing the required properties for the `<Button>`.

```reasonml
  1 │ @react.component
  2 │ let make = () => {
  3 │   <div> <Button /> </div>
  4 │ }

  This has type:
    (~children: 'a, ~onClick: 'b) => {"children": 'a, "onClick": 'b}
  Somewhere wanted:
    {"children": React.element, "onClick": ReactEvent.Mouse.t => unit}
```

Let's add the props to satisfy the compiler.

```rescript
@react.component
let make = () => {
  <div>
    <Button onClick={_event => ()}> {React.string("Click me")} </Button>
  </div>
}
```

`onClick` gets a function defined as `_event => ()`. The underscore before`event` tells the compiler that the variable is unused and we return a [unit](https://rescript-lang.org/docs/manual/latest/primitive-types#unit), `()`, which compiles to JavaScript's `undefined`.

Lastly, we re-add the button text from before as a child to `<Button>`, and we have successfully used our `<Button>` component!
ReScript: Creating a React component
Tags: rescript, react
Published: 2021-01-27 11:05:41


One great part of the [ReScript](https://rescript-lang.org/) ecosystem is the bindings to React. These bindings live in a project called [rescript-react](https://rescript-lang.org/docs/react/latest/introduction). This is an introductory post on how to create a React component.

```rescript
// Button.res
@react.component
let make = (~onClick) => {
  <button onClick>{React.string("Click me")}</button>
}
```

Let's step through the code line-by-line and see what's happening.

`@react.component` is a decorator that tells rescript-react that you're writing a component and it creates some code behind the scenes to get the props setup correctly.

`let make = (~onClick) => {` defines the start of our component function. The name of the function needs to be `make` for everything to work correctly. `make` is also a convention for the "main" function of a module and every file in ReScript is a module. `onClick` is a _named argument_ – it can be compared to props defined as `... = ({ onClick }) =>` in JavaScript React – and in this case, it is our only prop to this component.

`<button onClick>` is the start of our JSX and it works just like regular React. The difference is in the `onClick` prop we send to the button. In React we would need to do `onClick={onClick}`, but rescript-react JSX has [punning](https://rescript-lang.org/docs/manual/latest/jsx#punning). This works like objects in JavaScript that allows you to do `return { onClick }` instead of `return { onClick: onClick }`.

The type of `onClick` is inferred by its usage as `ReactEvent.Mouse.t => unit`so we don't need to define the type of the prop ourselves. The type also indicates that the prop is **required**.

To display a text inside the button, we use `React.string("Click me")`. ReScript needs every JSX child to have the same type, `React.element`. `React.string` converts the regular `"Click me"` string to a `React.element`. rescript-react has helper methods for converting most primitive values like `int`, `float`, `string`, and `array` to React elements.

This is the resulting generated (ES6) code:

```js
// Generated by ReScript, PLEASE EDIT WITH CARE

import * as React from 'react'

function Test(Props) {
  var onClick = Props.onClick
  return React.createElement(
    'button',
    {
      onClick: onClick,
    },
    'Click me'
  )
}

var make = Test

export { make }
/* react Not a pure module */
```
Merging array tables in JS
Tags: javascript, algorithms
Published: 2021-01-27 11:01:47

###Problem

We need to merge all this arrays into one big object.
First line of every array is the table headings, followed by users data.


```js
  const arr1 = [
    ["name", "id", "age", "weight", "Cool"],
    ["Susan", "3", "20", "120", true],
    ["John", "1", "21", "150", true],
    ["Bob", "2", "23", "90", false],
    ["Ben", "4", "20", "100", true],
  ];
  
  const arr2 = [
    ["name", "id", "height"],
    ["Bob", "2", "50"],
    ["John", "1", "45"],
    ["Ben", "4", "43"],
    ["Susan", "3", "48"]
  ];
  
  const arr3 = [
    ["name", "id", "parent"],
    ["Bob", "2", "yes"],
    ["John", "1", "yes"]
  ];
```


###My proposal:

```js
const data = {};

function addData(arr, uuid = 'id'){
    const [headings, ...body] = arr;
    for(const elem of body){
        let id;
        let person = {};
        for(const [index, heading] of headings.entries()){
            if(heading === uuid){
                id = elem[index];
            }
            person[heading] = elem[index];
        }
        data[id] = {...data[id], ...person};
    }
}

addData(arr1);
addData(arr2);
addData(arr3);
console.table(data);
```
Can you improve it? Do you have a different solution? 
Let me know in comments!
Day 24:100DaysOfCode
Tags: 100daysofcode, programming, productivity, java
Published: 2021-01-27 11:01:33

Studied more about maven in spring boot - local , central and remote repositry..

div3 on codeforces - solved 2 ques (due to server issues contest was unrated).
leetcode ques on greedy algos..

.
.
.
EOD


You can Follow me->
https://github.com/singhtaran1005
https://www.linkedin.com/in/taranpreet-singh-chabbra-27517918a/
10 resources to learn HTML and CSS for Free
Tags: html, css, webdev, codenewbie
Published: 2021-01-27 11:00:29

## 1. CSS-Tricks - "HTML & CSS – The VERY Basics"

➡️This video is the VERY basics of what HTML and CSS is, for the absolute beginner.

Link🔗 - https://css-tricks.com/video-screencasts/58-html-css-the-very-basics/


## 2. FreeCodeCamp - Responsive Web Design Certification (300 hours)

➡️You'll go from learning the basics of HTML and CSS to building your first website.

Link🔗 - https://www.freecodecamp.org/learn/responsive-web-design/basic-html-and-html5/


## 3. W3schools - HTML and CSS section

➡️These free tutorials cover a wide range of HTML and CSS uses. This is a must-see resource.

Links 🔗 - https://www.w3schools.com/html/

## 4. Learn HTML5 and CSS3 From Scratch - Full Course

➡️In this free 12 hours YouTube course you'll go from scratch to building your projects.

Link🔗 - 
https://www.youtube.com/watch?v=mU6anWqZJcc

## 5. Learn HTML5 and CSS3 For Beginners - Crash Course

➡️In this awesome 4 hours creative course you'll go from 0 HTML and CSS knowledge to building your first 3 awesome projects.

Link🔗 - 
https://www.youtube.com/watch?v=vQWlgd7hV4A

## 6. Building 10 Websites - From Design to HTML and CSS by @florinpop1705

➡️If you enjoy learning by building this YouTube course is for you. I can't recommend it enough.

Link🔗 - 
https://www.youtube.com/watch?v=Rz-rey4Q1bw

## 7. HTML and CSS Crash Course for Absolute Beginners

➡️These 2 are the courses I took when first learning HTML and CSS and I can only say that you can't find a better free course online.

Links🔗 - https://www.youtube.com/watch?v=UB1O30fR-EE - 
https://www.youtube.com/watch?v=yfoY53QXEnI&t=3s

## 8. HTML and CSS: Design and Build Websites by Jon Duckett

➡️If you enjoy learning from books this is the best resource for you.

Link🔗 - http://www.htmlandcssbook.com/

## 9. The HTML and CSS Handbook 

➡️These are 2 awesome books for learning almost everything about HTML and CSS. I still read these books from time to time.

Links🔗 - https://flaviocopes.com/page/html-handbook
- https://flaviocopes.com/page/css-handbook

## 10. Frontend Masters Bootcamp

➡️Even though this course contains JavaScript too, I still recommend it because it's a 21 hours high-quality, valuable course.

Link🔗 - https://frontendmasters.com/bootcamp/?utm_source=css-tricks&utm_medium=website&utm_campaign=css-tricks-blog-post

## End

Thanks for reading. I hope you found it valuable and if you did make sure you follow me on  [Twitter](https://twitter.com/VladPasca5) because there I post more about web development.
Build a User Profile Avatar Generator with JavaScript 🧑👩‍💻
Tags: javascript, html, webdev
Published: 2021-01-27 10:45:13

Let's take a look at how to generate user avatars for the web using some client-side JavaScript. The tools for the job include HTML5 canvas and data URLs 🙂

**This will reduce the amount of requests you have to the server side and as a result speed up your load times** ⚡

## Video Tutorial
As usual with my posts, if you prefer to watch a video tutorial of this, give it a watch on my YouTube channel, **dcode**:
{% youtube bUlK9yNJ3js %}

## Source Code
If you prefer to follow a long with code, here it is:
{% codepen https://codepen.io/twhite96/pen/RwGXdMM %}

## Writing the HTML
For the HTML, we only need a single image tag which will (eventually) hold the avatar.

```html
<img id="avatar" alt="Avatar">
```

## And the JavaScript...
This will work on a single function which takes in a couple of options including the text to display, a foreground color and background color.

```javascript
function generateAvatar(text, foregroundColor, backgroundColor) {
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");

    canvas.width = 200;
    canvas.height = 200;

    // Draw background
    context.fillStyle = backgroundColor;
    context.fillRect(0, 0, canvas.width, canvas.height);

    // Draw text
    context.font = "bold 100px Assistant";
    context.fillStyle = foregroundColor;
    context.textAlign = "center";
    context.textBaseline = "middle";
    context.fillText(text, canvas.width / 2, canvas.height / 2);

    return canvas.toDataURL("image/png");
}
```

In the first chunk of code we're doing standard procedure for canvases, creating a new canvas to work on and getting the 2D context to draw.

Next we set the width and height to the same value.

After this we draw the background by firstly setting the active fill color on the context, followed by a full-width rectangle to represent the background.

Next up is the text, and for this one we simply set the font family as well as instruct the text to be in the center, vertically and horizontally. It's then drawn on the canvas using `fillText`.

And lastly, we return a data URL of a PNG image for the canvas itself. We can then place the data URL in the `src` attribute of our `<img>` tag once calling the function:

```javascript
document.getElementById("avatar").src = generateAvatar("SP", "white", "#009578");
```

And here's what we get:
![Avatar Image Example](https://dev-to-uploads.s3.amazonaws.com/i/i3cbigqdxc29wcb075is.jpg)

Easy done. You can now generate avatar images on the client-side 😎
Can't connect my mern todo app with netlify , i miss the netlify server settings  
Published: 2021-01-27 09:42:54

I am new in MERN fullstack development. I like it very much though, coming from java programming, since 1985. 
I have created a very nice application following this site,
https://codingthesmartway.com/the-mern-stack-tutorial-building-a-react-crud-application-from-start-to-finish-part-1/ (parts 1 to 4)
However after some permutations, app it works fine, on my localhost whenever i open my server in my backend directory,  using npm start. 
I have deployed my project on netlify at the address:
mernfullstack.netlify.app
It also works fine on that web address when i have my local server up, running without problems. 
When the server shuts down, MongoDb is dead.
Following  is my github:
https://github.com/cca2013/myherokuapp 
HEAD master
Am I missing something in order to connect with the internal netlify web server and get access to my db with my mongodb uri?

Great Thanks with regards.
Better colors for `ls` in dark terminals
Tags: term, trick, dircolors, dark
Published: 2021-01-27 09:17:50

I'm using a dark theme in my terms but `ls --color` shows a dark blue color for directories, that make it difficult to read. In [How to Change Colors on LS in Bash
](https://linuxhint.com/ls_colors_bash/) but I didn't want to mess with each color, I was looking for something like a 'schema', so I discovered [dircolors](https://www.gnu.org/software/coreutils/manual/html_node/dircolors-invocation.html) and the [dircolors solarized][https://github.com/seebi/dircolors-solarized] repo. 

Mainly, you can clone the repo `git clone https://github.com/seebi/dircolors-solarized` and then follow these instructions:

> General Instructions

...
> ``eval `dircolors /path/to/dircolorsdb` ``

> To activate the theme for all future shell sessions, copy or link that file to ~/.dir_colors, and include the above command in your ~/.profile (for bash) or ~/.zshrc (for zsh).

You are going from this:

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

to this:

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

And some more things, of course. But this is all what I wanted. A small difference that will help me to see things again.
How to Setup Nginx with Let's Encrypt on Ubuntu 20.04
Published: 2021-01-29 21:34:18

---
title: How to Setup Nginx with Let's Encrypt on Ubuntu 20.04
published: true
date: 2021-01-27 09:09:09 UTC
tags: 
canonical_url: https://boobo94.github.io//devops/setup-letsencryp-nginx-ubuntu/
---

Prerequisites:

- Ubuntu 20.04 Server Installed with Nginx and Hosted Website

## Install Certbot on Ubuntu

> Certbot is an open-source tool that simplifies and automates the process of obtaining and renewing certificates from Let’s Encrypt. We are going to install Certbot by using the Snap deployment system. Snap is pre-installed on Ubuntu 20.04.

### Update snapd

Run the following commands to update snapd.

```
$ sudo snap install core
$ sudo snap refresh core

```

### Install certbot snap

Note: If you have previously installed Certbot by using the standard apt command, then run the following command first to remove it. This will ensure that the Certbot snap works correctly.

```
$ sudo apt-get remove certbot

$ sudo snap install --classic certbot
certbot 1.11.0 from Certbot Project (certbot-eff✓) installed

```

### Enable certbot command

```
$ sudo ln -s /snap/bin/certbot /usr/bin/certbot

```

## Obtain your Certificate

When you run the command below, certbot will guide you through the process. Certbot also updates your NGINX configuration automatically to activate HTTPS.

```
$ sudo certbot --nginx

```

## Certificate Renewal Process

Certificates issued by Let’s Encrypt are valid for 90 days. During installation, certbot creates a scheduled task to automatically renew your certificates before they expire. As long as you do not change your web server configuration, you would not have to run certbot again.

Run the following command to test the automatic renewal process.

```
$ sudo certbot renew --dry-run

```

!Note: Source post [https://linoxide.com/ubuntu-how-to/setup-nginx-with-lets-encrypt-on-ubuntu-20-04/](https://linoxide.com/ubuntu-how-to/setup-nginx-with-lets-encrypt-on-ubuntu-20-04/)
Unable to create directory wp-content/uploads/ hosted on Linux with Nginx/Apache
Published: 2021-01-29 21:34:23

---
title: Unable to create directory wp-content/uploads/ hosted on Linux with Nginx/Apache
published: true
date: 2021-01-27 09:09:09 UTC
tags: 
canonical_url: https://boobo94.github.io//devops/wordpress-upload-permissions-linux/
---

This may indicate a permissions problem with your WordPress uploads directory.

Firstly please make sure that you have the right permissions on /uploads folder.

```
$ sudo chmod -R 755 uploads/

```

Then if still nothing happens, please check the owner permissions.

```
$ ls -l
total 24
-rw-r--r-- 1 root root 28 Jan 26 13:44 index.php
drwxr-xr-x 16 root root 4096 Jan 26 14:50 plugins
drwxr-xr-x 7 root root 4096 Jan 26 13:44 themes
drwxr-xr-x 2 root root 4096 Jan 26 13:44 upgrade
drwxr-xr-x 11 root root 4096 Jan 26 13:44 uploads

```

Let’s offer the right permissions. As we can see the uploads folder has the `root` owner. The owner of Nginx/Apache [servers](https://cmevo.com/website-development-services/) is `www-data`

```
$ sudo chown -R www-data:www-data ./uploads/

```

Now if you check again, the owner is changed and the permissions 755 are set.

```
$ ls -l
total 24
-rw-r--r-- 1 root root 28 Jan 26 13:44 index.php
drwxr-xr-x 16 root root 4096 Jan 26 14:50 plugins
drwxr-xr-x 7 root root 4096 Jan 26 13:44 themes
drwxr-xr-x 2 root root 4096 Jan 26 13:44 upgrade
drwxr-xr-x 11 www-data www-data 4096 Jan 26 13:44 uploads

```

That’s it!