teleren/devto huggingface dataset:
REST vs. SPREAD
Tags: react, javascript, webdev
Published: 2021-11-14 10:23:54

### The ***Rest parameter*** and ***Spread Syntax*** were added in JavaScript ES6 (ECMAScript 6) despite the fact that their symbols are the same they work differently.

> NOTE: 
>- Parameters are value passed inside the function definition :
>
>    function add(paramter){ }
>- Arguments are value passed while calling the functions
>
>      add(arguments)
>

#### Let's discuss about them using the explanation and examples.

***
## **Rest Parameter**

 Sometimes while creating the  function we face the situation where the value of number of arguments to be passed are unknown to us. There comes the ***Rest Parameter*** to our rescue.

```
<--- Without Rest parameter --->

function add(a, b) {
  console.log(a + b);
}

add(5, 6) // 11
add(5, 6, 2, 3) // 11, It will just ignore the rest of the arguments except(2,3) because we have given only 2 parameters

```

```
<--- With Rest Parameter --->

function add(...args) {
  let sum = 0;
  for (let arg of args) {
    sum += arg;
  }
  return sum;
}

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9]

console.log(add(2, 3)) // 5
console.log(add(2, 3, 6)) // 11
console.log(add(2, 3, 7, 4, 2, 5)) // 23

```
### **Point to Remember**

 1. The rest parameter is always used at the end of the function parameters 
```
function add(a, b, ...rest){}
```
***

## **Spread Syntax**

Sometimes we need to add the an array of values as the arguments to the functions because adding each value to the arguments will not be good practice. There comes the **Spread Synatx** for our rescue.

```
<--- Without Spread Sytax --->

console.log(Math.max(1,3,4,6,7,9,98,74,56,32,12,36)) // 98
```
```
<---With Spread Syntax --->

let arr = [1,3,4,6,7,9,98,74,56,32,12,36];

console.log(Math.max(...arr)) // 98 



let arr1 = [1, -2, 3, 4];
let arr2 = [8, 3, -8, 1];

console.log(Math.max(1, ...arr1, 2, ...arr2, 25)); // 25
```

### **Point to Remember**

Unlike **rest parameter**, **spread syntax** can be used anywhere in the function arguments.

```
console.log(Math.max(1, ...arr1, 2, ...arr2, 25));
```
***
### **Difference**
| Rest Parameter 	| Spread Syntax 	|
|---	|---	|
| When {...} appears in the<br>function definition it is called Rest Parameter 	| When {...} appears in the<br>function call it is called Spread Syntax. 	|
| function add(...restParameter){<br><br>// code<br>  <br> } 	| let arr= [1,2,3,4,5,6,7,8,9]<br> <br>add(...spreadSynatx) 	|
 
***
Connect: 
[Twitter](https://twitter.com/Vanshsh2701)
[Reference](https://javascript.info/rest-parameters-spread)
The Missing Semester
Tags: beginners, career, computerscience
Published: 2021-11-14 10:20:08

I'm happy to announce I had published my first (only?) book!

Software Development Engineering is a fast-paced industry. While the university curriculum tends to teach its attendants a vast number of concepts, ideas, and technologies, there still exists a gap to be bridged.

The Missing Semester aims to conquer this gap by providing insight into what it takes to be a #softwaredevelopment #engineer in the current #work marketplace. The book presents topics like teamwork, advice for technical growth, better #coding skills, system architecture, design principles, #career growth, #mentalhealth, and many more.

The topics discussed in this book are very prone to debate, so the book itself should be read with this in mind. The opinions presented are just that - opinions.

It's written in a concise, easy-to-read format and is a great starting point for anyone embarking on this industry. It's available on Amazon for anyone who finds this interesting and/or useful.
"El Futuro del Desarrollo Web: ¿Qué nos deparará la tecnología?"
Published: 2021-11-12 20:49:36

El desarrollo web ha experimentado un rápido crecimiento en los últimos años, gracias a la evolución de la tecnología y a la creciente demanda de aplicaciones y sitios web. Pero, ¿qué nos deparará el futuro en cuanto a desarrollo web y tecnología?

La tecnología está en constante evolución y es importante estar al tanto de las tendencias y avances que influyen en el desarrollo web. Uno de los avances más recientes en el campo de la tecnología es la inteligencia artificial (IA). La IA está transformando la forma en que desarrollamos aplicaciones y sitios web, permitiéndonos crear experiencias más personalizadas y entretenidas para los usuarios.

Otra tendencia en el desarrollo web es la popularidad de los sitios y aplicaciones móviles. Cada vez más personas acceden a internet a través de sus dispositivos móviles, lo que ha llevado a un aumento en la demanda de sitios y aplicaciones móviles de alta calidad. Es importante que los desarrolladores de sitios web se enfoquen en la experiencia de usuario móvil y en la optimización de la velocidad y la funcionalidad de sus sitios y aplicaciones móviles.

El diseño de sitios web también está evolucionando. Los sitios web modernos deben ser atractivos y fáciles de navegar, pero también deben ser accesibles y respetar los estándares de la industria. Además, el uso de realidad aumentada y virtual está ganando popularidad en el diseño de sitios web, permitiendo a los usuarios interactuar de manera más interesante y significativa con el contenido.

Además de la IA, los avances en la tecnología de la nube están transformando el desarrollo web. La nube permite a los desarrolladores de sitios web alojar y acceder a sus aplicaciones y sitios web desde cualquier lugar, lo que les permite ser más eficientes y flexibles. También permite a los usuarios acceder a sus aplicaciones y sitios web desde cualquier dispositivo con conexión a internet.

En conclusión, el futuro del desarrollo web promete ser emocionante y lleno de avances tecnológicos. Desde la IA hasta la popularidad de los dispositivos móviles y la tecnología de la nube, los desarrolladores de sitios web tienen muchas oportunidades para crear experiencias en línea.
Using google storage to store media files in strapi
Tags: webdev, programming, javascript, tutorial
Published: 2021-11-14 09:59:27

This is the fourth blog post on the series of blog post I am posting about strapi,nextjs, and tailwind. We are recreating my portfolio/blogpost page that along the way we'll learn the fundamentals of strapi,nextjs, and tailwind. You can check it out at [myportfolio](https://myportfolioandblog.vercel.app/) If you know the basics of javascript and react then you should be good to follow this blog post and coming blog post on the series. I hope you'll get something out of this series.

In this blog post, we're going to set up google bucket to store our media files. 
So go ahead and install a plugin

 ```
 yarn add strapi-provider-upload-google-cloud-storage
 or 
 npm i strapi-provider-upload-google-cloud-storage
 ```
 
Now we've to create a google cloud bucket and generate the service account for that
I'm using the firebase project which makes it very easy to create a google bucket and generate the service account You can create a google bucket through google cloud console too. If you're using firebase then go to project settings and service account. Click the Generate a new private key. This will download a simple file with JSON data on it. We've to copy that JSON data and stringify it and put it as an environment variable in our strapi app.
![json](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gy5wkoceda0luccrvvd9.png)
 
 Let's create the env file with GCP_SERVICE_ACCOUNT !
![env file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e27l30nhq8478agn8vsx.png)
 After that create a plugins.js file in the config and add the following code 
 ```
 module.exports = ({ env }) => ({
  upload: {
    provider: "google-cloud-storage",
    providerOptions: {
      bucketName: "yourbucketnamehere",
      publicFiles: true,
      uniform: false,
      basePath: "",
      serviceAccount: env.json("GCP_SERVICE_ACCOUNT"),
    },
  },
});
 ```
 

And that's it now we should be uploading files to the google bucket instead of a local file system. Now you can upload any media file and it will end up in your google bucket as:
![Google cloud console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2z910s0ebcsj1uc27ruo.png)
You can see it creates a bunch of files and folders when uploading files as it creates a different responsive version of the images that you upload. you can change this setting from within strapi admin as
![Strapi Admin Dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xremjncae9f192m3fr1k.png)
***And that is it about using google Buckets to store media files in strapi. The process for uploading to other providers is also pretty similar. In another blog post, we'll create our landing page. If you have any problem with this setup and then let me know in the discussion.***
[Solved] err_http2_protocol_error
Tags: python, programming, codenewbie, tutorial
Published: 2021-11-26 21:48:36

---
title: [Solved] err_http2_protocol_error
published: true
date: 2021-11-14 09:58:53 UTC
tags: #python #programming #codenewbie #tutorial
canonical_url: https://itsmycode.com/solved-err_http2_protocol_error/
---

ItsMyCode |

The err\_http2\_protocol\_error occurs for various reasons while using Ng, and it’s one of the most annoying errors that appear all of a sudden either on your browsers such as Chrome, Firefox, etc. It can happen when you make HTTP calls from your code using react, .net, node.js, etc.

## Solution err\_http2\_protocol\_error

Let’s look at the typical use case and the solution for each of the different use cases.

## Scenario 1: Low Disk Space

If your webserver runs on very low disk space, you will get **_`err_http2_protocol_error `_** while making HTTP calls. The error won’t be logged anywhere sometimes as there is no space left out on the disk. 

The webservers like Nginx, apache webservers will be unable to send all the responses and usually drop the request after the first chunk is sent. This would result in the content-length header not matching the actual content received and resulting in `err_http2_protocol_error`.

**Solution:**  Check the disk space on your webserver, free up space, and check if this resolves the issue.

## Scenario 2: Gzip double compression

If you are running Node.JS on an Nginx server, then there are high chances that the files like CSS, js, etc are getting double compressed, and due to which err\_http2\_protocol\_error is thrown.

The first compression happens on the Node.JS server for the static files, and then even the Ngxinx also does Gzip conversion. 

Solution **:**  Turn off the gzip compression on the Nginx config as shown below. Always ensure the gzip compression happens only once on the server-side.

```
 server {
  ...
  ...
  gzip off;
  proxy_max_temp_file_size 0;
  location / {
    proxy_pass http://127.0.0.1:3000/;
  ....
```

Also, it can cause because of the header size issue. Increase the value of http2\_max\_field\_size and http2\_max\_header\_size to resolve the issue.

```
http2_max_field_size 64k;
http2_max_header_size 512k;
```

## Scenario 3: Failed to load resource: net::ERR\_HTTP2\_PROTOCOL\_ERROR after upgrading to VS 2019 16.10.0 (and 16.10.1)

The issue can happen if you are running ASP.Net 3.1 + React JS app after a windows update.

It is an official bug from Microsoft Windows, and it’s confirmed by Microsoft [officially](https://developercommunity.visualstudio.com/t/Failed-to-load-resource:-net::ERR_HTTP2_/1446262?viewtype=all).

**Solution** : Uninstalling a recent Windows patch,  **KB5003637 ** resolves the issue, or you can upgrade to the latest version of the Windows patch.

The post [[Solved] err\_http2\_protocol\_error](https://itsmycode.com/solved-err_http2_protocol_error/) appeared first on [ItsMyCode](https://itsmycode.com).
Create Cookie banner in React
Published: 2021-11-14 09:51:57

In this article, we'll see that how can we create cookie banner in react.

## The Architecture

> This is going to be sort and sweet and assuming that you already know that what is cookie banner, react, etc

## The Architecture

The Architecture is simple, we are going to have a `CookieBanner` component which will have it's own state. It'll show a banner on the UI and when user clicks on the accept or close buttton, the banner will gets removed.


## Implementing this in Reach + Chakra-UI
```js
import { useState, useEffect } from "react";
import { BellIcon } from "@chakra-ui/icons";
import {
  Box,
  HStack,
  Icon,
  Stack,
  Text,
  useColorModeValue,
  Button,
} from "@chakra-ui/react";
import { getLocalStorage, setLocalStorage } from "@src/util";

export default function Banner() {
  // by default do not show this banner
  const [isCookieEnabled, setIsCookieEnabled] = useState(true);

  useEffect(() => {
    const isCookie = getLocalStorage("cookie-enabled");
    setIsCookieEnabled(Boolean(isCookie));
  }, []);

  return isCookieEnabled ? null : (
    <Box as="section" pt="8" pb="12" pos="fixed" bottom={"-50px"} w="100%" zIndex={10}>
      <Stack
        direction={{ base: "column", sm: "row" }}
        justifyContent="center"
        alignItems="center"
        py="3"
        px={{ base: "3", md: "6", lg: "8" }}
        color="white"
        bg={useColorModeValue("blue.600", "blue.400")}
      >
        <HStack spacing="3">
          <Icon as={BellIcon} fontSize="2xl" h="10" />
          <Text fontWeight="medium" marginEnd="2">
            By using our website, you agree to the use of cookies as described
            in our cookie policy
          </Text>
        </HStack>
        <Button
          w={{ base: "full", sm: "auto" }}
          flexShrink={0}
          colorScheme="green"
          onClick={() => {
            setLocalStorage("cookie-enabled", true);
            setIsCookieEnabled(true);
          }}
        >
          Accept
        </Button>
      </Stack>
    </Box>
  );
}
```
## Desktop
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qxgofhr593nuipthxqmj.png)

## Mobile
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9slv8gdvxh4tufqwnxn9.png)
To see this in action open [this](www.dsabyte.com) page.

## Thank You
Plotly Dash journey #1
Tags: plotly, dash, python
Published: 2021-11-14 09:25:26

One week into the plotly dash journey. I follow the Udemy course which is great. Gotten familiar with Atom as an IDE instead of Jupyter notebooks. Progress is a little slow as I’m on parental leave with my son who’s only 10 months old and keeps me awake at night. But at least I can now produce line charts with multiple traces based on random numbers generates with Numpy. Child’s stuff, I know. But I’ll get there.
How to enable passwordless sudo in Linux
Tags: linux, ubuntu, debian
Published: 2021-11-14 09:22:33

<h5>I can show you many steps to configure passwordless sudo for specific user: </h5>

1.open your terminal and type this to add new user:
```yml
$ sudo adduser ansible
Adding user `demo' ...
Adding new group `demo' (1004) ...
Adding new user `demo' (1004) with group `demo' ...
Creating home directory `/home/demo' ...
Copying files from `/etc/skel' ...
New password: 
Retype new password: 
passwd: password updated successfully
Changing the user information for demo
Enter the new value, or press ENTER for the default
	Full Name []: 
	Room Number []: 
	Work Phone []: 
	Home Phone []: 
	Other []: 
Is the information correct? [Y/n] y
```

2.after that type:

```yml
$ sudo visudo
```

3.go down to the bottom, then add this to assign a new user become sudo:
```yml
ansible ALL=(ALL) NOPASSWD:ALL
```
4.done, now you have new user, that will able to execute sudo command without providing a sudo password.

N/B: in Debian you must install sudo:

```yml
$ apt install sudo

```
Week 3 aka Halfway through
Tags: codeofafrica, awesomitylab, taskforce
Published: 2021-11-14 09:19:45

How time flies, feels like just yesterday when I saw the task force backend challenge and started working on it right away it is crazy to think it's been over a month now. Anyways new week new learnings new challenges so let's get into it.

this week's theme was ERD(Entity Relationship Diagram).this is a very crucial part of backend engineering as the database is the part of the design you don't want to get wrong and it is built from the ERD so every technical session this week was geared towards that. 

Also worth mentioning is how one of the perks of being surrounded by engineers of different backgrounds is there is a tool for everything...want to design an ERD? here is a tool that makes it easier, want to design good slides for presentation? here, use this tool, want to get to the main road faster from the office? here is a shortcut...ok that's a joke but seriously there is! This is how I find myself learning something new every other hour or so and I am so here for it.

If you have been reading the task force weekly journals you know how important soft skills are in this program and this week was no different with sessions about communication and cultural awareness which I personally consider needed in today's age where more and more organizations especially in the tech space (CoA , Awesomity ;) are adopting the hybrid work model.

fun week overall and week 4 can not come soon enough!!
How to make a loading screen for an iframe using functional components in React
Tags: react, tutorial
Published: 2021-11-14 09:11:57

This article already exists! Well.. [almost](https://medium.com/@josh.j.pearson/handling-iframe-loading-in-react-57f044a9d0fa). It's a recurring annoyance of mine, to find tutorials explaining just what I want, only to find class-based React code instead of the more modern functional components.

So lets get to business:

Vanilla HTML elements in React with JSX are more powerful than their framework-less counterparts. Here, we can use the mighty `onLoad` prop in an iframe:

```jsx
<iframe
    src="https://dev.to/"
    onLoad={/* some function here */}
/>
```

When I was searching for this, that's all I would have needed to solve my problem! I had this inhibition that prevented me from trying the obvious; I thought that there was no way an iframe could have an `onload` event. I should have just tried it anyway! Well, I did... but not before wasting my own time trying to find a workaround I never needed.

Next we are reminded that ternary expressions work in jsx! How convenient :relieved:

```jsx
{ loading ? <MyLoadingAnimation /> : <></> }
```

Remember that the cryptic looking `<></>` is just jsx's way of saying `null`, or from a UI perspective, _showing nothing_.

So, when `loading` is `true`, we'll see the loading animation. Otherwise we'll see nothing from that bit of code.

The last member of our party today is the `useState` hook:

```jsx
const [loading, setLoading] = useState(true);
```

Here we initialize `loading` to `true`, because when we start out the iframe is not loaded yet.

And its clear now what that `onLoad` prop should actually do!

```jsx
<iframe
    src="https://dev.to/"
    onLoad={() => setLoading(false)}
/>
```

Finally, we bring it all together, using whatever kind of loading screen or animation you want, represented here simply as the a component called `MyLoadingAnimation`

```jsx
const [loading, setLoading] = useState(true);

return (
    <>
        { loading ? <MyLoadingAnimation /> : <></> }
        <iframe
            src="https://dev.to/"
            onLoad={() => setLoading(false)}
        />
    </>
)
```

It's probably a good idea to style `MyLoadingAnimation` to have `position: absolute`, to prevent the iframe from moving around when it finishes loading.

```jsx
<MyLoadingAnimation
    style={{
        position: "absolute"
    }}
/>
```

It's probably also a good idea to style `MyLoadingAnimation` to be in the center of whatever space your iframe takes up, but thats a design choice!

Hope this was useful :v:
When() in laravel
Tags: php, laravel, programming, beginners
Published: 2021-11-14 09:03:19

Let's get started quickly
Sometimes you may want certain query clauses to apply to a query based on another condition
```php
$role = $request->input('role');
$users = DB::table('users')
                ->when($role, function ($query, $role) {
                    return $query->where('role_id', $role);
                })
                ->get();
```
Laravel Eloquent when method will execute the given callback when the first argument given to the method evaluates to true
```php
$collection = collect([1, 2, 3]);

$collection->when(true, function ($collection) {
    return $collection->push(4);
});

$collection->when(false, function ($collection) {
    return $collection->push(5);
});

$collection->all(); // [1, 2, 3, 4]
```
With use()
```php
->when($request->user_id, function ($query) use ($request) {
        return $query->where('user_id', $request->user_id);
})->get();
```
I hope you enjoy the code.
Day 4; Basic Python Collections(Python 30 Day challenge)
Tags: python, cloudengineering
Published: 2021-11-14 09:00:32

#1. **Lists**
Lists are created by having characters inside square brackets, separated by commas, with each value inside quotation marks
The code below also shows how to access items within a list
**List rules**
1. Can only add a list to another list
2. Can only use these *, + operators
![Lists and how to access them](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p6nw3cmzaarivy2vzmkn.png)

##**Adding items to a list** 
###using the .append() method
![adding items to a list using the append method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zhe29ur868zhlzs45aof.png)
###using the + operator
![adding items to a list using the + operator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wwlxu37b3zfz148s047c.png)
###using the .extend() method
![adding items to a list using the extend method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xagrkbze1qs6yh1qxll9.png)
###using the .insert() method
![adding items to a list using the insert method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gecppprqzad0j5wztq8e.png)

##**Removing items from a list** 
###using the .remove() method
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9to8d3e12hx27lfyeh07.png)
###using the del
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v3v9fqkhm1eklfz8cbh1.png)
###using the .pop() method
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5s3ixe03lecepucg3pi1.png)
###using the .clear() method
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oev2h7rvhq7xniwapph8.png)

#2. **Tuples**
Tuples are immutable i.e once created they cannot be changed
But they can be nested inside lists, where they are easily accessible using their index
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/89t93dfl51d8j1pjgm1y.png)

#3. **Maps/Dictionary**
A combination of tuples and lists that can be accessed with a key and a value.
Contains curly brackets , and the key-value pair is separated with a colon, and separated with single quotes
Cannot join maps with the '+' operator

#4. **Exercise day 4 code**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bugs69bs4urpaasugnqf.png)
Blockchains for the Barely Interested
Tags: blockchain, beginners, tutorial, serverless
Published: 2021-11-14 08:31:49

Blockchains, smart contracts, these things come off as either useless or too convoluted for many programmers. This is not true. They are both useful (beyond just cryptocurrencies) and easy (smart contracts are just like normal programs that we write day-to-day).

In [Let’s Make a Coin -
An ELI-5 introduction to blockchains and smart contracts](https://ethsgo.com) we try to remove these stumbling blocks. The intention is to get people interested and started – once you see how easy this is, and can start imagining some of the use cases it has beyond just money – you'll be well on your way. We end with some pointers to places where you can continue your journey.