teleren/devto huggingface dataset:
async/await in javascript
Tags: javascript, async, await, tips
Published: 2021-08-14 08:27:20

## 1. async keyword

async is a keyword which can be used before of a function definition.

```jsx
async function sayHi() {
  return "Hello There"
}
```

The word `async` means one thing: the function that uses it always returns a promise. Other values other then promises are wrapped as promise and resolved by default.

For example in previous example, it will return a promises with returned string. Lets look at it

```jsx
async function sayHi() {
  return "Hello There!"
}

function log(message) {
  console.log(message)
}

sayHi().then(log) // console > "Hello There"
```

We could also explicitly return a promise, which works the same way

```jsx
async function sayHi() {
  return Promise.resolve("Hello There!")
}

sayHi().then(log) // console > "Hello There"
```

## 2. await keyword

Right now we see how async function works behind the scenes. But there is another keyword which can only be used inside async functions and that is `await`

```jsx
// syntax
async function sayHi() {
	let promise = new Promise((resolve, reject) => { 
	  setTimeout(() => { resolve("Hello There!") }, 3000) 
	})

	// wait until promise is resolved
  let result = await promise

  log(result) // console > "Hello There"
}
```

If we try to use await in a non-async function, there would be a **syntax error**

## 3. error-handling on async functions

Because async functions returns promise, if there was a rejection during function process it throws an error just like `throw` statement.

```jsx
async function logError() {
  return Promise.reject(new Error("Whoops!"))
}

async function logError() {
  throw new Error("Whoops!")
}
```

### 3.1. using try/catch

We can use try/catch statement to handle potential problems in the codebase.

```jsx
async function logError() {
  return Promise.reject(new Error("Whoops!"))
}

async function sayHi() {
  try {
		await logError()
  } catch (error) {
		// catches the error
		// console -> Whoops!
		console.log(error.message)
  }
}
```

## 4. async/await and .then/catch

When we use `async/await`, we rarely need `.then`, because `await` handles the waiting for us. And we can use a regular `try..catch` instead of `.catch`. That’s usually (but not always) more convenient.

## 5. Resources
https://javascript.info/async-await
Support for password authentication was removed on August 13, 2021. - Fixed
Tags: github, git, arjuncodes, passwordauthentication
Published: 2021-08-14 08:09:11

Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.

**If you are getting this error go through this video :**

*For Windows*

{% youtube mpyNlGEuiR8 %}

*For Linux / Mac*

{% youtube ytSoabxSQ6E %}

**Important Note** : To store the token git credential so that you don't have to type token everytime, use this command before pushing.

```git config credential.helper store```
JS Keyboard events
Tags: javascript
Published: 2021-08-14 08:06:52

Mouse events are relatively simple: you've either clicked or moused down, moved or upped etc or you haven't. And we know what it is you did it on because that's what the event listener is on.

Keyboard events are harder.

Let's say you have a calculator in JavaScript. You've got it all working when you click the buttons, but want it to work when you use the keyboard too.

First, you don't put a keyboard event listener on a button, you put it on the document. Why? Because the listener needs to listen to what's in focus and when you use the keyboard, generally one of the calculator buttons won't be in focus. Maybe you require users to click on or tab to something on the calculator before they do anything else, in which case you can put your event listener on the calculator. But that would be a very strange design.

And then you have to work out which button on the keyboard the user pressed. And there are a multitude of ways of doing this. Doing
```
console.log(event);
```
will give you a whole load of information.

If I press "1" I get the following information:
- code: "Digit1"
- key: "1"
- keyCode: 49
- which: 49

In a lot of code you might see something like
```
if (event.keyCode === 49) {
  //do something
}
```
That's because once upon a time, that was the only information we had. These days, this is much easier to read:
```
if (event.key === '1') {
  //do something
}
```

There are other pitfalls. Some keys also do other things: for example the down arrow, page down and space keys will all scroll the page down. And therefore will scroll down as well as also doing whatever you've told them to do. event.preventDefault() is your friend here: but not if there's potential to scroll and your listener is on the document. Your user who wants to scroll with the keyboard will get very frustrated if it doesn't work.

To check exactly how the keys are named, without having to console log every single one, I recommend [JavaScript Event KeyCodes](http://keycode.info/)
How I smashed a bug on the biggest developer community
Tags: devbugsmash, react, storybook, forem
Published: 2021-08-14 08:04:11

In this post I will share my experience on smashing a bug on the [dev.to](https://dev.to/) codebase.

### Open Source Background

I have about 5 years of web development experience but kinda new to open source community.

I started with .NET web applications, then learnt Javascript & react. I fell in love with react and started exploring open source community and all the good tools people are contributing. 

I have to thank [Epic React course by Kent](https://epicreact.dev/) which ignited the spark to everything!

I started following NextJs, Chakra UI and developed [my personal website](http://bharathikannan.com/) to share what I have been working on. Then I was introduced to dev.to by people's blog posts and cross posted some of my posts from the website. 

I received a good amount of attraction and followers in this community which keeps motivating to write more. 

Also, I am very happy to share that one of my blog post was shared by the DEV Community twitter account! 🤯

{% twitter 1411988727195443206 %}


![Shockingly happy Pep guardiola](https://media.giphy.com/media/eeowUvYEP1IfQ0S1rr/giphy.gif)

### About This Bug


{% github https://github.com/forem/forem/issues/13601 %}

It was a bug related to Tab components, happening in the storybook. When you click on a different tab header, the webpage was redirecting the user to the home page ('/') rather than to the selected tab.

### How I Smashed It


{% github https://github.com/forem/forem/pull/14491 %}


### Reflection

I felt happy contributing something that 'I can' to open source.

The bug is really a simple thing to smash, but the learning from it is such a good experience. I now have confidence to clone an open source repo, make it run on my machine, able to reproduce the bug and fix it, raise a PR & follow up with reviewers.

I understood how storybooks are being used in big applications, what are some of good coding practices and standards, and learnt more on accessibility. 

The Forem team has such a wonderful [get started guide](https://docs.forem.com/contributing/forem/) for people like me to start contributing.


### Suggestions for DEV Community Bug Smash

I now have few suggestions to improve forem codebase. Soon, I am going to raise issues with contributing PRs to discuss and fix them. Together we can build a rock solid community! 😀

❤️ Thanks to all the DEV Community members ❤️
Support for password authentication was removed
Tags: github, git, arjuncodes, passwordauthentication
Published: 2021-08-14 08:03:45

Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.

**If you are getting this error go through this :**

*For Windows*

{% youtube mpyNlGEuiR8 %}

*For Linux*

{% youtube ytSoabxSQ6E %}

**Important Note** : To store the token git credential so that you don't have to type token everytime, use this command before pushing.

```git config credential.helper store```
AI: steering wheel console using cardboard 📦🚐
Tags: ai, gamedev
Published: 2021-08-14 07:55:24

Heyho!

I wanna share with you guys about my old project that i made in order to learn more about AI, especially, color tracking.

I try to be more creative by combinate it with car simulator. So here's the result.

 {% youtube qmeolC-y7_w %}

This project was created using Python, OpenCV, SocketIO, and [Udacity Self Driving Car Simulator](https://github.com/udacity/self-driving-car-sim)

In this post, i'll show you how i made that with non-technical explanation. I'll explain to you all the step and flow in general without code pasted here.

**BUT....**

I will put the source code at the end of this post. It's free to learn or contribute.

**🛠️ How I Made It**
Watch these steps casually :)

---

#### DIY Steering  
First, i made my steering wheel from cardboard and put color paper for origin and point.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lu8mf4elqedp5pz6dx67.png)

#### Color Detection  
Using OpenCV, i created new layer for color detection. I change the layer to HSV format, and gives limit for lower range and upper range.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ggjx73dut14ma3ibx58y.png)

So, that was what layer's color look like in HSV format. And for For limitation, this is the simple way.
> *"If color (in hsv) suitable with range that i set, show white. Otherwise, show nothing (in case, black)"*
 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/amgh5zclqgqekuvzv4s4.png)

#### Centroid
So, i need to pointing the centroid area from color that i successfully track on steering wheel (origin & point).

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xnsymibc5cf2o8rz9kwl.png)
 
#### Angle Calculation
When i already have the coordinates of my origin and point color on steering wheel, i can make a calculation for angle easly. This angle is affected by steer spin.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hvnqz8pu4ywgpg787806.png)

#### Emit to Simulator
Then, i have to send every number of angle change to Udacity Simulator using Socket. Yes, i sending the value over http method.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i6saaboirf5956yppavn.png)
 
#### PLAY 🥳
All is setted up. All we need to do is enjoy and get the feel in riding car :)

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pgdx65sk01nx4ga52l74.png)

----

#### Source Code 🎉
{% github mtegarsantosa/ai-steering-sims no-readme %}
JS Polyfills asked in Interviews
Tags: javascript, node, career, webdev
Published: 2021-08-14 07:44:20

## Introduction

As Javascript community keeps adding new methods in Javascript, so all browsers doesn't support new JS methods.  

To make your JS code run on every browser, you need to add it on your own or you can use [Babel](https://sotly.co/IXY6zCbd), [CoreJS](https://sotly.co/40bmc6Bp). Sometimes companies ask in **interview** for Polyfills to know your understanding.  

In this article, I will list out some Polyfills asked by companies.

## 1. Array Flat

This method is used to flat a nested array.

In the below example, we have used [recursion](https://sotly.co/tSFkt02X) to solve this problem. We have created 2 cases:
  - A base case: If depth is reached then push arr in output and return it.
  - A recursion case: Loop over array and check if its an Array or not. If its an array flat it, else push the number in output.

{% replit @abhishekraj2721/Array-Flat-JS %}

## 2. Array Filter

This is a Higher Order Function which takes another function and filters the array on the basis of the function.

In the below example, we have created a higher order function, which takes another function and calls on each element of the array. If it returns *true* then that element is inserted into result.

{% replit @abhishekraj2721/Array-Filter-JS %}

## 3. Array Reduce

This is a Higher Order Function which takes another function and reduces the array to single value/object and returns it.

In the below example, we have created a higher order function, which takes another function and calls on each element of the array. It mutates the result returned by the callback function.

{% replit @abhishekraj2721/Array-Reduce-JS %}

## 4. Function Bind

The bind method is used to pass an execution context to the function.

In the below example, the custom Bind function takes the context and uses apply method to bind the function with the given context.


{% replit @abhishekraj2721/Func-Bind-JS %}

##### For more Awesome polyfills asked in interviews, check out [JSVault](https://sotly.co/2_Dz2uUf)  

Connect Me @ [Linkedin](https://www.linkedin.com/in/abhishekraj272/), [Github](https://github.com/abhishekraj272), [Twitter](https://twitter.com/abhishekraj272), [Youtube](https://www.youtube.com/channel/UCvHn2T8DSJzEWzYDdK3Dt8A) 😇

> Note: I have written all the methods as pure functions, as I have only wanted to show the code. We can also use Prototypal Inheritance.  

> All the URLs in this post are powered by [Sotly.co](https://app.sotly.co/)
Uh Oh! I Cloned without Forking!
Tags: github, git, fork, beginners
Published: 2021-08-14 07:36:57

Last week I cloned a repo without forking it first and only realised my mistake after I had already made some commits to my local copy.

Rookie mistake!  

But there's an easy fix.

#### Step 1: Remove the existing remote from your local repo.

```
git remote remove origin
```

**Note:** You can get a list of configured remotes and their URLs by running:

```
git remote -v
```

#### Step 2: Fork the project and copy the fork's URL
![Copy fork's URL](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/is9brfbn1iuq54lo5rg5.png)

#### Step 3: Add the URL to your local copy.

```
git remote add origin [copied URL]
```

And you're done 😀 ! You can now push your code and it will go to your fork.

Hope this was helpful!

---
Hi, I am Upamanyu! 

If you liked this post maybe you'll like my tweets too. Follow me [@tintin_das 🐦](https://twitter.com/intent/user?screen_name=tintin_das).
QA in Production
Tags: testing, devops, qa, testautomation
Published: 2021-08-14 07:33:24

**How to reduce defects in production?
What kind of QA work can be done in production?**

Nowadays, this is a work mixed with QA & DevOps.

This article from martinfowler.com will guide you through those answers:[QA in Production](https://martinfowler.com/articles/qa-in-production.html).

Apart from that, a collection of articles from TechBeacon Guides named ["Reducing Defects in Production Software"](https://content.microfocus.com/l/reduce-defects-software-tb)  is highly recommended.
Capture Website Screenshots with Python
Tags: api, screenshot, aws, python
Published: 2021-08-14 07:23:38

All, we've released our [McAPI Screenshot API](https://rapidapi.com/Softmatic/api/mcapi-screenshot/) on RapidAPI. In this post I'll show you how to capture website screenshots with Python. All sample code will work with the free tier of the API.
  
## Quickstart
Using the *requests* module to grab a screenshot (replace YOUR_API_KEY with your RapidAPI key). All relevant options are set in the *payload* string:
```python
# Python 3
  
import requests

url = 'https://mcapi-screenshot.p.rapidapi.com/'

payload = '{\
  "url": "https://dev.to",\
  "format": "jpeg",\
  "storeExternal": "false",\
  "devices": [ "Default" ]\
}'
headers = {
  'content-type': 'application/json',
  'x-rapidapi-key': 'YOUR_API_KEY',
  'x-rapidapi-host': 'mcapi-screenshot.p.rapidapi.com'
}

response = requests.request('POST', url, data=payload, headers=headers)
```
The response will be in JSON. With *storeExternal* set to "false", the screenshot is immediately returned as a base64 encoded image (if set to "true" the screenshot is stored in the cloud and the API will return a URL):
```json
{
  "service": "McAPI Screenshot Generator, https://mcapi.io",
  "version": "V1",
  "url": "https://dev.to",
  "screenshots": [
    {
      "device": "Default",
      "screenshot": "data:image/jpeg;base64,/9j/4AAQSkZJRgAB ... 9yXvZG0pSuhyP/9k="
    }
  ]
}
```
##Specifying devices
The API can take multiple screenshot with one REST call, very useful if you want to test website designs against various devices. Simply specify devices like so:
```python
# Python 3
  
...

payload = '{\
  "url": "https://dev.to",\
  "devices": [ "iPhone 12", "iPhone 12 landscape" ]\
}'

...
```
More than a hundred devices are predefined but you can also specify your on screen sizes; see [docs](https://mcapi.io/screenshot/screenshot-api-overview.php) for more. 
##Ads and cookie warnings
Other features include a built-in ad blocker and an option to auto-click GDPR cookie banners (currently experimental).

Shown are three screenshots, &#35;1 with default settings:
![Screenshot API - Cookie Consent Banner Python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n0pwg3pb7zwmgugg66jp.jpeg)
&#35;2 with *cookie* option set to "true":
![Screenshot API - Clicked Cookie Banner and Ad with Python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4xt9e6dm9glsk4hrn237.jpeg)
&#35;3 with *cookie* and *adblock* option set to "true": 
![Screenshot API - Clicked Cookie Banner and Ad Block Python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5jvjovwzwonwgste3907.jpeg)
##Try it live
Try the screenshot API on the [RapidAPI listing](https://rapidapi.com/Softmatic/api/mcapi-screenshot/).
##More
Reference and more sample code (Python, Ruby, NodeJS, PHP, Swift) on the [McAPI screenshot API product page](https://mcapi.io/screenshot/screenshot-api-overview.php).

The API is currently hosted on AWS Lambda with an API Gateway in front of it. Although over 55MB (zipped) we got it working by installing via S3. Let me know in the comments if you would like a post about this.
Top 10 freelancer category from wearehiring.top platform ❤❤❤
Tags: programming, redux, redis
Published: 2021-08-14 07:21:56

Dear community,

As many you know in January 2021 we founded the platform wearehiring.top; Now we want to share with you some of our results. Below we have created a list of the top 10 categories on our freelance platform:

- redis developers
- redux saga developers
- php developers
- swagger developers
- nestjs developers
- asp .net developers
- elasticsearch developers
- reactjs developers
- rabbitmq developers
- puppeteer developers

We have great projects and great freelancers in above categories. It's our pleasure to share with you our success and results.

If you are looking for a project or for a freelancer for your project then you can check https://www.wearehiring.top/ platform! ❤
🗃️ Backup your .dotfiles with a simple bash script
Tags: dotfiles, bash, linux, backup
Published: 2021-08-14 06:50:21

We will be creating a git repository with a script that backup your required dotfiles. 

### 1. Create a folder for the backup
```bash
mkdir my-dotfiles
```

### 2. Initialize git
```bash
git init
```

### 3. Create file list
Create a file named `backup.conf` at the root of the folder.
In this file we need to list out all the files & folders we need to backup. eg:
```
~/.gitconfig
~/.profile
~/.vimrc
~/.xinitrc
~/.zshrc
```
Our backup script will loop through the items and copy everything into respective folders. 

### 4. Create script
Create a file named `backup.sh` at the root of the folder.
This is our script file. Copy the content below and paste it inside the file.

```bash
#!/bin/sh

# This script copy files mentioned inside `backup.conf` to the root of the project.

# file to look for the paths to backup.
backupPaths="./backup.conf"
# home directory path.
homeDirectory=~
# same line identifier to echo in the same line.
sameLine="\e[1A\e[K"

echo "🛑 Clearing configurations directory..."
# removing the folder with exsiting contents. we have git version anyway!
rm -rf configurations
# creating it again for backup.
mkdir configurations
sleep 1
echo -e "$sameLine✅ Configurations directory cleared."
sleep 1

echo -e "$sameLine🏁 Starting backup..."
sleep 1

# looping through the list & avoiding the empty spaces
sed '/^[ \t]*$/d' $backupPaths | while read filePath; do
  echo -e "$sameLine⏳ Copying: $filePath"

  # find & replace for ~ with home path
  findThis="~/"
  replaceWith="$homeDirectory/"
  originalFile="${filePath//${findThis}/${replaceWith}}"

  # copying the files
  cp --parents --recursive $originalFile ./configurations
  sleep 0.05
done

git add .

echo -e "$sameLine🎉 Backup finished! You can review & commit your changes."
```

### 5. Make the script executable
```
chmod +x ./backup.sh
```

### 6. Commit all changes
```
git add .
git commit -m "initial commit"
```

### 7. Run script
```
./backup.sh
```

From now on, you can just run the script file whenever you need. After you run the backup script, all the files & folders mentioned inside the `backup.conf` file will be copied into `configurations` folder. Commit and push the changes to your remote repository.

> 🛑 Make sure you are not adding any confidential files or folders to `backup.conf` file. eg: `.ssh` or private keys.

Checkout below repository to see complete code. There is a `install.sh` script in the root which is made for Arch Linux systems. Feel free to fork the repository and make changes according to your needs.

{% github ctrleffive/linux-configurations %}
How i passed CLF-C01 exam in 2 weeks
Published: 2021-08-14 06:47:34

To keep agile, I earned my AWS Certified Cloud Practitioner CLF-C01 exam credential from Amazon Web Services.

**Resources that i have used to study CLF-C01 exam**
- 2 Weeks of study 
- [Go through Exam Guide](https://d1.awsstatic.com/training-and-certification/docs-cloud-practitioner/AWS-Certified-Cloud-Practitioner_Exam-Guide.pdf)
- [AWS Cloud Practitioner Essentials](https://aws.amazon.com/training/digital/aws-cloud-practitioner-essentials/?cp=sec&sec=prep)   *Free*
- [Ultimate AWS Certified Cloud Practitioner - 2021 ] (https://www.udemy.com/course/aws-certified-cloud-practitioner-new/)  *Paid*
- [AWS Whitepaper] (https://d1.awsstatic.com/whitepapers/aws-overview.pdf)  *Free*

and to fill my knowledge gaps I took few practice test 
- [Practice Exams | AWS Certified Cloud Practitioner CLF-C01 ] (https://www.udemy.com/course/practice-exams-aws-certified-cloud-practitioner/) *Paid*

### Important Topics
- Shared responsibility
- Support Plans
- EC2 Instance types
- Object Storage Class

### Important AWS services **must know**
- EC2
- S3
- VPC
- Trusted Advisor
- Guard Duty
- Redshift
- Neptune
- RDS
- Athena 
- Cost Explorer
- AWS Budgets
- TCO calculators
- EMR
- Snow Family
- AWS WAF
- EBS
- EFS
- Route53
- CloudFront
- CloudFormation
- CloudTrail
- Outpost
- S3 Global Accelator
- DAX and Elastic cache

> All the Best Folks!!!


Do follow me on 
- [LinkedIn] (https://www.linkedin.com/in/aadi-manchekar-b267621a6/)
- [Twitter] (https://twitter.com/ManchekarAadi)
Fix - Github password authentication was removed issue - MacOS/Windows
Tags: github, javascript, beginners
Published: 2021-08-14 06:42:04

---
title: Fix - Github password authentication was removed issue - MacOS/Windows
published: true
description: GitHub removed the Support for password authentication on August 13, 2021, and now we have to use a personal access token instead.
tags: #github, #js, #beginners, #javascript
//cover_image: https://direct_url_to_image.jpg
---

GitHub removed the Support for password authentication on August 13, 2021, and now we have to use a personal access token instead.

##For MAC OS
Click on the Spotlight icon (magnifying glass) on the right side of the menu bar. Type Keychain access then press the Enter key to launch the app - In Keychain Access, search for github.com -- Find the internet password entry for github.com-- Edit or delete the entry accordingly - You are done

##For Windows OS
Go to Credential Manager from Control Panel - Windows Credentials - find git:https://github.com - Edit - On Password replace with your Github Personal Access Taken -- You are Done

##Video
{% youtube s-CN4RaNq8A %}

## Steps to create a personal access token

https://docs.github.com/en/github/authenticating-to-github/keeping-your-account-and-data-secure/creating-a-personal-access-token