teleren/devto huggingface dataset:
Firebase Auth (v9)で複数のProviderをリンクさせる
Tags: webdev, firebase, typescript
Published: 2022-11-13 07:52:23

`firebase/auth` は認証周りの機能を提供してくれるSDKです。今回はそれを用いて複数のプロバイダー（GoogleやGithub、Twitterなど）の認証情報を一人のユーザーと結びつける方法の紹介です。

## 具体的なケース
`signInWithPopup` という関数が提供されていて、アプリケーションとプロバイダーを引数に渡すことでユーザー認証が行えるようになっています。以下のコードはGoogleアカウントを用いた認証の例です。

```ts
import { getAuth, signInWithPopup, GoogleAuthProvider } from 'firebase/auth'
 // appはinitializeAppを用いてconfigファイルを元に生成したもの
import { app } from '../utils/firebase/client'

const provider = new GoogleAuthProvider()
const auth = getAuth(app)

// 認証を行う処理
const handleSignIn = () => {
  signInWithPopup(auth, provider).then(/* ... */)
}
```

この時点で認証を試してみると、問題なく動きます。さてここに、GitHubアカウントを用いた認証を追加します。引数にProviderを渡せるようにして、Google同様にインスタンスを初期化しておきます。

```ts
import { getAuth, signInWithPopup, GoogleAuthProvider, GithubAuthProvider } from 'firebase/auth'

const googleProvider = new GoogleAuthProvider()
const githubProvider = new GithubAuthProvider()

const handleSignIn = (provider: AuthProvider) => {
  signInWithPopup(auth, provider).then(/* ... */)
}
```

この状態でGitHubでの認証を試みると次のようなエラーが発生します。

```
auth/account-exists-with-different-credential
```

## 一旦エラーハンドリングする

ハンドラでエラーの内容を見てみます。エラーはオブジェクト形式で渡され、`code`プロパティにエラーを示す文章が入います。内容は先程と同じ `auth/account-exists-with-different-credential` が格納されています。

```ts
const handleSignIn = (provider: AuthProvider) => {
  signInWithPopup(auth, provider)
    .then(/* ... */)
    .catch(error => {
      console.log(error.code)
    })
}
```

## エラーから認証情報を生成する
`OAuthProvider` というクラスを用いることでエラーからcredentialを生成できます。失敗した場合はnullが返ってきます。とりあえず生成して早期リターンさせておきます。（エラーが正しい場合は失敗する可能性はないのですが、コンパイラが警告を出してくる場合があるので正しく型とガード節を書いたほうが良いです。）

```ts
const credential: AuthCredential | null = OAuthProvider.credentialFromError(error)
if (credential === null) return
```

次に `fetchSignInMethodsForEmail` という関数を用いて、メールアドレスから認証情報を取得します。メールアドレスは `customData` プロパティから取得できます。

```ts
const email = error.customData.email
fetchSignInMethodsForEmail(auth, email).then(/* ... */)
```

resolveされたら、メールアドレスが使用しているメソッドが配列形式で得られます。今回のケースの場合、先にGoogle認証を行ってからGitHubでの認証を試みているので、`google.com`が出力されるはずです。

```ts
fetchSignInMethodsForEmail(auth, email).then((methods: string[]) => {
  console.log(methods[0]) // 認証に用いた方式を取り出せる
})
```

次に、得られた認証方式の文字列からプロバイダーを得る関数を定義してあげます。ここでreturnしているものは最初に初期化したインスタンスです。

```ts
const getProviderById = (id: string) => {
  switch (id) {
    default: {
      return null
    }
    case 'google.com': {
      return googleProvider
    }
  }
}
```

あとは `linkWithCredential` 関数を用いてこれらの情報をリンクさせ、同一ユーザーであることをFirebaseに教えてあげます。

```ts
.catch((error) => {
  if (error.code === 'auth/account-exists-with-different-credential') {
    const email = error.customData.email
    const credential: AuthCredential | null = OAuthProvider.credentialFromError(error)
    if (credential === null) return

    fetchSignInMethodsForEmail(auth, email).then((methods: string[]) => {
      const provider = getProviderById(methods[0])
      if (provider === null) return
      signInWithPopup(auth, provider).then(result => {
        // 紐付けを行い、以降ログイン時はここまでのフローがスキップできる
        linkWithCredential(result.user, credential)
      })
    })
  }
})
```
Javascript: Check if an Array is a Subset of Another Array
Tags: webdev, javascript, typescript, beginners
Published: 2022-11-13 18:34:41

There are many use cases where knowing if an array is a subset of another can be quite useful - and although usually immediately obvious to the human eye, it can be difficult to evaluate in code.

In the code below, `arr2` is a **subset** of `arr1`, but `arr3` is not. 
```javascript
let arr1 = [ 'a', 'b', 'c' ];
let arr2 = [ 'b', 'c' ];
let arr3 = [ 'c', 'd' ];
```

If we want to find out if an array is a subset of another array, the best way to evaluate this is by using the [array every method](https://fjolt.com/article/javascript-array-every). This method iterates through each element in an array and performs a test on it. If every element in the array passes that test, then the overall `every` method will return true.

For each evaluation, we have a "parent" array, and a "subset" array - where we want to check if the "subset" array is fully contained within the "parent" array.

To evaluate if one array is a subset of another, we can run `every` on the each element on the "subset" array. Within the `every` function, we can test if the "parent" array contains each element in the "subset" array. If it does, then `every` will return `true`. Otherwise, it'll return `false`. 

This can be accomplished easily with a function like the one shown below - `checkSubset` will return `true` should the `subsetArray` be fully contained within the `parentArray`:

```javascript
let arr1 = [ 'a', 'b', 'c' ];
let arr2 = [ 'b', 'c' ];
let arr3 = [ 'c', 'd' ];

let checkSubset = (parentArray, subsetArray) => {
    return subsetArray.every((el) => {
        return parentArray.includes(el)
    })
}

checkSubset(arr1, arr2); // returns true
checkSubset(arr1, arr3); // returns false
```
Launch NFT WordPress Plugin 🚀
Tags: blockchain, web3, nft
Published: 2022-11-13 18:24:49

You will be glad to know that we have released a Brand NEW NFT WordPress plugin on Codecanyon, proudly named "[**Smart NFT - NFT Marketplace WordPress Plugin**](https://codecanyon.net/item/smart-nft-nft-marketplace-wordpress-plugin/39767244)".

Smart NFT is a plugin that empowers you to turn your website into a Full functional NFT Marketplace. You will be able to SELL, BUY, MINT and AUCTION on your website.

Smart NFT also allows you to list NFTs from your website visitors. Get multivendor functionalities with public profiles, edit profiles and custom settings panel. 

Grab it Now →
https://wpsmartnft.com/
Copying objects in javascript
Published: 2022-11-13 18:23:27

There are a few ways to copy objects in javascript. One of them is using one of the native javascript object methods - Object.assign

```
const obj = {
 name:"John",
 surname:"Doe",
 age:15
}

const copyObj = Object.assign({}, obj);
```

With ES6, you can also use the spread operator as well.

```
const obj = {
  name:"John",
  surname:"Doe",
  age:15
}

const copyObj = {...obj}
```

However, these methods are for creating shallow copies.
Let's say you have a nested object and you use one of the methods mentioned above this is what will happen:

```
const obj = {
  name:"John",
  surname:"Doe",
  age:19,
  location:{
	country:"USA",
	city:"New York",
	address:"Queens, New York 11418, USA",
      }
 }
	
const copyObj = {...obj}

obj.location.country = "Russia"
console.log(copyObj.location.country) //Russia
```

The nested objects will be copied as a reference, that means when you change some property of the nested object, it will also affect the copied object.
There are several ways to make a copy of nested object, one of them is:

```
const obj = {
  name:"John",
  surname:"Doe",
  age:19,
  location:{
	country:"USA",
	city:"New York",
	address:"Queens, New York 11418, USA",
      }
 }
	
const copyObj = JSON.parse(JSON.stringify(obj));
obj.location.country = "Russia"
console.log(copyObj.location.country) //USA
```
Or using lodash's cloneDeep utility function:

```

import cloneDeep from 'lodash/cloneDeep'

const obj = {
  name:"John",
  surname:"Doe",
  age:19,
  location:{
    country:"USA",
    city:"New York",
    address:"Queens, New York 11418, USA",
   }
 }
 
const copyObj = cloneDeep(obj)
```

You can find the original article here:
[Copying objects in javascript](https://thejsblog.netlify.app/posts/how-to-copy-objects-in-javascript)
Difference between exports and module.exports
Tags: javascript, node, angular, codenewbie
Published: 2022-11-13 18:11:25

The module represents the current module in the plain Javascript object. 

Exports is a plain JavaScript variable. Module is a plain javascript object which has the exports property

From one module to another, when we want to  export a single class, variable, or function, we use modules. exports.

From one module to another, when we want to export multiple variables or functions, we use exports.


```javascript
var module = { exports: { value1: 10 , value2: 20 } };
var exports = module.exports;

return module.exports;
``` 

In the above example, we have assigned multiple values to the same object.

module.exports.value1 returns 10 and module.exports.value2 returns 20


```javascript
var module = { exports:  10  } };
var exports = module.exports;

return module.exports;
``` 

In the preceding example, exports is set to a value that results in modules.Exports are no longer the same object.

module.exports returns 10


```javascript
const userDetails= (data)=>{
    return {
        getUsername:()=> data.username,
        getEmail:()=> data.email,
   }
}

module.exports = userDetails;
``` 

In the preceding example, calling userDetails(data>) returns the value of the username.getUsername()


```javascript
const getUsername:(data)=> data.username

const getEmail:(data)=> data.email

exports.getUsername = getUsername;
exports.getEmail = getEmail;
``` 

In the above example the value of username can be got by getUsername(<data>)

If we go with the first approach, we do not need to include new lines in the export statement each time we create a new function.

Whereas in the second approach new functions if created gradually increases the number of lines of the exports statement as well

Therefore, as a best practice in accordance with the NodeJs documentation's usage of exports and module.exports, we can avoid using exports and instead use module.exports.

Thanks for reading ❤️. I hope you liked it.

Follow me via [Twitter](https://twitter.com/Dhanush_Nehru), [Instagram](https://instagram.com/Dhanush_Nehru), or [Github](https://github.com/dhanushnehru).
Installing Git and Creating a GitHub account
Tags: git, github, learnwithmitulcommunity, beginners
Published: 2022-11-13 18:09:20

## What is the purpose of Git and GitHub?
- To connect tech-enthusiastic people from all around the world.

- To reach out to my past version of myself while coding.

- To keep track of individual projects.

- To look back at any timeline of the project.

- To allow us to host a git repository for an open-source project with everyone.

- To know who is working with us on the project and what changes are made by them.
 
To conclude, GitHub is a portable online portfolio for all. 

## <u>Installation of Git:</u>

1. Go to [https://git-scm.com/downloads](url)
2. Depending on your operating system, you can choose to download the link:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tl4f4ht89puoxifoc67r.png)
3. After clicking that,
 - For Windows users: We can download according to our system type. i.e. 32-bit or 64-bit operating system.
  

---- 

**N.B:** Just in case, if someone does not know how many bits their operating system is, you can check it by the following steps:
   - Go to **"Settings".**

   - Click on **"System".** and then look for **"About"**.
   - After opening **"About"**, we can see **Device 
     Specifications** and let us know any information about our 
     operating system i.e.**system type**. For example, my system 
     is:
                              ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/16e6rq64bvythgsczhkr.png)

## How to make a GitHub account?:
1. Go to [https://github.com/](url)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z4xw4mhaq9zv6tlduwlz.png)
2. Click on "Sign up" and follow the steps as instructed by the website to create a GitHub account.
Explain Git to a 5 year old!
Tags: webdev, git, github, programming
Published: 2022-11-13 18:01:58

So imagine you are working on a painting. You started the work on Monday and by the end of the day you made pretty good progress on it. Now the only thing left is adding some colors and some final touch up. So you decide to do it next day. 

Next day you wake you and resume your work. Unfortunately while working you spill the bottle of water color on your painting and now the entire painting is destroyed. You can’t do anything about it, than to start over again! 

Here at this point you must be thinking what if I could 

1. Go back in time and resume my work before the water color gets spilled?
2. Go back to yesterday and create a exact copy of completed work so that even if I mess up one, I have another copy to carry on my work.

But this would only be possible if you had a Time machine! But neither of us knows Tony Stark or Bruce Banner who could let us borrow their time machine from Avengers Endgame!!


![Git is like a time machine](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d1unvwrwdbh3fi6p543v.gif)


So Git is nothing but a time machine! Not for your Painting, but your code!

Git allows us to create 

1. Create stops(commits) in your project
2. Reset your project to any of these previous stops. 
3. Create copies of your project and carry on your work separately
4. Merge these copies whenever required.

Isn’t Git amazing? 

If you go by the definition, Git is a Version Control System. That is, a System that lets you manage and control the version of your project. 

Whereas GitHub is a platform by Microsoft that uses Git to manage your projects. 

I hope I was able to explain what is Git in simple terms for you!
Why To Focus On Accessibility
Tags: a11y, career, beginners
Published: 2022-11-13 17:37:27

When I started programming over a year ago, I became interested in the topic of accessibility very early on. I'm interested in this topic not only because **it's the right thing to do** or **the logical thing to do**, but also because I want to write **good and clean code**.

And using **semantic HTML** and the **right aria attributes** is for me part of the basic knowledge that every frontend developer should have.

Lately, however, **another good reason** why focusing on accessibility is a good choice is becoming more and more apparent: **The need for accessibility developers**.

What do I mean by that?

A few months ago, [LinkedIn officially added accessibility to their job titles](https://www.linkedin.com/pulse/driving-more-equitable-workforce-enhanced-tools-resources-berger/). And certainly not without reason.

Because the accessibility law is getting more and more serious (like web security). There's only one direction it's going to go: In the next few years, **more and more companies will have to comply with accessibility requirements**, and those companies will be looking for people who are knowledgeable about the subject.

There aren't that many UX designers, front-end developers, and QA testers with a good knowledge of accessibility (yet). So **focusing on this now** will give you a big advantage when you apply for a job. 

In Austria, for example, not only state-owned companies, but also companies with more than 10 employees and annual sales of more than 2 million euros must meet accessibility requirements to avoid being sued (Accessibility Act (BaFG)).

And by 2025, this law is to be **applied throughout Europe**. The laws are getting stricter and stricter, and that's a good thing.

And for all these reasons, I advise you to get familiar with accessibility. I'm preparing [my learning website YurisCodingClub](https://www.yuriscodingclub.com/about) for CodeNewbies, portfolio creators and job seekers in such a way that accessibility is **already incorporated into the learning process**. You can thank me later 😇
How to use git
Published: 2022-11-13 17:31:06


**What is Git:**
 Git is an open-source control management system. You can collaborate on projects using Git. You can revert to previous versions with Git.

**How to set up Git?**
When you have downloaded git, you must first configure it. This is so when we commit a file, we know who is committing it. To configure a file, you must enter the following code
git config --global user.name "Your name"
git config --global user. Email "Your email"

**How can I check my status on Git?**
 To check your Git status, you can type in the command git status. This will tell you the status of your repository, like which files  have been tracked and untracked and more.

**How to track and untrack your files:**
To track a file, it means that git will track the file when any changes have made to it. To track a file, enter the command git add then the name of the file you wish to track.
To untrack a file, enter the command git rm --cached and the file you wish to untrack. Git will no longer care what changes you make to this file because it is untracked.
To track all your files, you can type git add -all, git add -A or git add.

**How to commit a file:**
To commit a file, you are taking a snapshot of it at that point in time. It is like you are writing it out in page of a history book.
 To do this type, git commit -m and then a message along with the commit.

**How to change a file:**
To change or modify a file you must select the file you want you want to edit and once you happy with your changes you can save it and go back to git and type git status to see if it has recognized the change.
 Git will only recognize the change if you have tracked it. If you want to see the changes that you have made with the file, you can type in the command git diff.
 It will show you two different texts in two colours: the red is the original text before you edited it and the green is the text after the file has been modified.

**How to remove and restore a file:**
You can use git to remove or delete a file that you do not need. You can do this by typing git rm and the file you want to delete.
 If you want to restore a file, you can do this by typing git restore and then the file you want to restore. 

**How to rename a file:**
To rename a file you can use git to do it by typing git mv and the current name of your file then the name you want to change it to.

**How to view commit history:**
If you want to view all the commits that you have made you can do this by typing git log, this will show all the commits that you have made in the past starting with the most recent commit.
If you want to view a more simplified version of the commit you can by typing git log --oneline. This will still show all your commits but only one line for each one.
SSR en NextJS
Tags: nextjs, ssr
Published: 2022-11-13 17:28:38

Es el más utilizado en grandes aplicaciones por su rapidez en la hidratación en el servidor.


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

La página nos entrega de primero el `HTML `mientras por debajo está procesando desde el servidor los archivos `JS `los cuales van cargando los diferentes eventos. Es por ésta razón que el primer render es muy rápido, porque lo se que se hace es pintar antes de cargar acciones, ésto tiene una mejora directa en el flujo.

NextJS ya incluye éste concepto en sus implementaciones y lo puedes usar de ésta manera:


![vscodessr](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6xt33pknl6szqs2i5hln.png)
Front-end and Back-end differences
Published: 2022-11-13 17:16:03


**What is Front-end?**
Front-end is how things look, what the user can see with their eyes.
•Things like the images, text, colour, and structure are examples of front-end.
•Three programming languages are front-end based. Those are HTML, CSS, and JavaScript.
•Front-end languages are normally used together on the same site for different things.
•For example, when you go on amazon you see the products, text, content. This is what we call a user-interface which is the interactions between the user and the machine.
**What is Back-end?**
Back-end is how things work such as the logic and database. Users cannot see this physically.
•The back end is the code that creates the user-interface.
•Back-end programming languages are ones such as Ruby, Python, PHP, Java (Not related with JavaScript!), C#, etc.
•Back-end languages are used alone in contrast to front-end ones. For, example you may use HTML, CSS and JavaScript as front ends but only use Python as the back end.
**How do front and back-end languages communicate?**
Application programming interface (API) is a way two or more programming languages communicate with each other.
•APIs are different to a user interface which connect the user to the computer because it acts as services available for the user
•One purpose of an API is to hide the information a user does not need to know how a system works; it will only expose what is necessary
•For example, when a user goes onto amazon and want to buy something on the front end, it will get the back-end language to look in the database which in the back end. The back end will look in the database to see if the user’s email is there and if so, it will tell the front end to proceed to the next page.
•In another scenario another user wants to buy a product and the back end checks the database but does not find the user’s email it will tell the front-end to take the user to a page so it can register with his or her email and then take it to the page to buy the product.
First connection with Wes Bos
Published: 2022-11-13 17:09:23

I just started connecting with the Tech World as part of an assignment for a Bootcamp. I chose Wes Bos only because it was the first suggestion on the list. I am so glad I chose this one, it looks like it will prove extremely useful. He describes himself as a professional explainer. This is extraordinarily generous. I loved seeing the beginner JavaScript course as the pinned tweet. I can imagine coming back to this several times later. I loved seeing the videos of him delving into Twitter code. Obviously I didn't understand the technical things yet. However, just from an initial 20 or so minutes spent looking at his tweets, I could see why this was an important part of the Bootcamp.
Reverse Odd Levels of Binary Tree
Tags: javascript, leetcode
Published: 2022-11-13 17:04:27

[Reverse Odd Levels of Binary Tree](https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/)

```js
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var reverseOddLevels = function (root) {
  let queue = [root];
  let level = 0;
  let levelValues = [];

  while (queue.length) {
    const next = [];
    levelValues = [];
    for (let i = 0; i < queue.length; i++) {
      const node = queue[i];
      levelValues.push(node.val);
      if (node.left) {
        next.push(node.left);
      }
      if (node.right) {
        next.push(node.right);
      }
    }

    if (level % 2) {
      levelValues = levelValues.reverse();
      for (let i = 0; i < levelValues.length; i++) {
        queue[i].val = levelValues[i];
      }
    }

    queue = next;
    level++;
  }

  return root;
};

```
Error: The active duration is too short while removing role assignment
Tags: azure, devops, pim, community
Published: 2022-11-13 17:00:21

Greetings my fellow Technology Advocates and Specialists.

In this Troubleshooting Session, I will demonstrate, how to resolve the encountered error - "__The Active Duration is too short__" while removing PIM role assignment.

__Azure DevOps Administrator__ PIM role was assigned (Active Assignment) to the Service Principal configured as DevOps Service Connection. 

Immediately, within couple of minutes, I tried removing the assigned PIM role when I encountered the mentioned error.

__This is how it looks:-__

| ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1mhgfdq77zvj4dagmkwe.jpg) |
| --------- |
| ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j2yz1sq1d3lykypbd4a6.jpg) |
| ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l9aytl7ccjpy9jg66ezq.JPG) |

When tried after 5 minutes, Assigned PIM role (Azure DevOps Administrator) could be removed successfully.

__Hope You Enjoyed the Session!!!__

__Stay Safe | Keep Learning | Spread Knowledge__