teleren/devto huggingface dataset:
Namespaces are just fine - No need to destructure every object in JavaScript
Tags: codequality, javascript
Published: 2022-06-13 11:16:36

An increasingly common practice in JavaScript is destructuring. This is great to get rid of otherwise generic terms like in the following examples.

Destructuring objects:
```typescript
/*❌*/ const results = await fetch('users')
/*❌*/ results.users
/*✔️*/ const { users } = await fetch('users')
```

Destructuring arrays:
```typescript
/*❌*/ const results = await validate(request)
/*❌*/ if (!results[0]) throw results[1]
/*✔️*/ const [isSuccessful, error] = await validate(request)
/*✔️*/ if (!isSuccessful) throw error
```

These are very good use-cases for destructuring!

But then there is the other side of the coin:

```typescript
const { user: { city }} = results
```

The variable “city” had a perfect home with the namespace “user”. It’s very clear that “user.city” is the city belonging to the user. With the nested destructuring technique, you lose these benefits.

---

This overdestructuring can also lead to name clashes, which would require renaming the variable:

```typescript
const { city } = location
const { user: { city: userCity }} = results
```

“userCity” vs. “user.city”. Is this difference worth the added complexity and loss of intent?

Compare these two code statements that could follow the above example:

```typescript
/*❌*/ if (city === userCity) {}
/*✔️*/ if (location.city === user.city) {}
```

---

In multi-line statements, over-destructuring can also confuse the reader as to which side of the assignment the reader is currently on (left side or right side):

```typescript
const {
  user: {
    city: userCity
  },
  location: {
    city: locationCity
  }
  ...rest
} = {
  ...cache,
  user: await getUser()
  date: now()
}
```

Not enough? How about some inlined TypeScript types to mix things up:

```typescript
const {
  user: {
    city: userCity
  },
  location: {
    city: locationCity
  }
  ...rest
} = {
  ...cache,
  user: await getUser()
  date: now()
} : {
  user: {
    id: string;
    city: string
  }
  date: number,
  location: {
    id: string;
    city: string;
  }
}
```

**Namespaces are just fine.** In fact, they are very helpful in communicating where a variable belongs to. And best of all, you get all of it out of the box.

---

This was an excerpt from my e-book Intent-Driven Development which will teach you how to simplify the day-to-day code you run into and the balance between over- and under-engineering. Get it over at https://michaelzanggl.com/intent.
Find Mode in Binary Search Tree
Tags: leetcode, dsa, theabbie
Published: 2022-06-13 11:00:48

Given the `root` of a binary search tree (BST) with duplicates, return _all the [mode(s)](https://en.wikipedia.org/wiki/Mode_(statistics)) (i.e., the most frequently occurred element) in it_.

If the tree has more than one mode, return them in **any order**.

Assume a BST is defined as follows:

*   The left subtree of a node contains only nodes with keys **less than or equal to** the node's key.
*   The right subtree of a node contains only nodes with keys **greater than or equal to** the node's key.
*   Both the left and right subtrees must also be binary search trees.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/03/11/mode-tree.jpg)

**Input:** root = \[1,null,2,2\]
**Output:** \[2\]

**Example 2:**

**Input:** root = \[0\]
**Output:** \[0\]

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 104]`.
*   `-105 <= Node.val <= 105`

**Follow up:** Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).**SOLUTION:**

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def inorder(self, root, ctr):
            if root:
                self.inorder(root.left, ctr)
                ctr[root.val] = ctr.get(root.val, 0) + 1
                self.inorder(root.right, ctr)
        
        def findMode(self, root: Optional[TreeNode]) -> List[int]:
            ctr = {}
            self.inorder(root, ctr)
            maxVal = max(ctr.values())
            return [k for k, v in ctr.items() if v == maxVal]
Copilot addons
Published: 2022-06-13 10:42:20

## addons yml 설정하기
기본 템플릿은 아래와 같습니다. 
경로는 `copilot/{serviceName}` 폴더 아래에 addons 폴더를 추가하고 `{name}.yml` 파일 추가하여서 작성하면됩니다. 
최종 경로는 `copilot/{serviceName}/addons/{name}.yml`가 됩니다.

```
Parameters:
  App:
    Type: String
  Env:
    Type: String
  Name:
    Type: String

Resources:
  SQSAccessPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Sid:
            Effect:
            Action:
            Resource:
Outputs:
  SQSAccessPolicyArn:
    Description:
    Value: !Ref SQSAccessPolicy
```

Parameters는 AWS Copilot에서 항상 요구하는 필수 항목입니다. (참고. [copilot-cli](https://aws.github.io/copilot-cli/docs/developing/additional-aws-resources/#customizing-the-parameters-section)) 
`AWS Copilot always requires the App, Env, and Name parameters to be defined in your template.`

Resources는 실제 사용할 AWS Resource PolicyDocument Statement에 사용할 Resource의 Sid, Effect, Action, Resource를 작성하면 됩니다.

```
Sid: SQS-A
Effect: Allow
Action:
  - sqs:SendMessage
Resource: arn:aws:sqs:ap-northeast-2:000000000000:sqs-a
```

예를 들어, sqs-a에 sqs message 전송 권한을 주고싶으면 위와 같이 Action에 권한 Resource에는 실제 arn값을 작성하면됩니다. Sid는 StatementId 입니다. (참고. [IAM sid](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html))

추가로 sqs-b에 전송 권한을 주고싶다면 아래와같이 작성하면 됩니다.

```
Sid: SQS-B
Effect: Allow
Action:
  - sqs:SendMessage
Resource: arn:aws:sqs:ap-northeast-2:000000000000:sqs-b
```

작성된 전체 yml은 아래와 같습니다. IAM 권한은 copilot이 deploy되면서 addons yml에 따라서 자동으로 IAM 권한을 만들어서 설정해줍니다.

```
Parameters:
  App:
    Type: String
  Env:
    Type: String
  Name:
    Type: String

Resources:
  SQSAccessPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Sid: SQS-A
            Effect: Allow
            Action:
              - sqs:SendMessage
            Resource: arn:aws:sqs:ap-northeast-2:000000000000:sqs-a
          - Sid: SQS-B
            Effect: Allow
            Action:
              - sqs:SendMessage
            Resource: arn:aws:sqs:ap-northeast-2:000000000000:sqs-b

Outputs:
  SQSAccessPolicyArn:
    Description: "Sqs 메시지 전송 권한"
    Value: !Ref SQSAccessPolicy
```

## 기대효과
- IAM 권한이 템플릿화 되어서 이상적인 서버 구조가 될 수 있음!!
What is it like being a Programmer?
Tags: programming, coding
Published: 2022-06-13 10:39:20


**Being a Programmer means constantly coding, learning, reading, planning, mapping out a new creation, and thinking about how to solve a current problem or writing solutions. Coding is fun and I Love it.**



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y8k7s5bxlfjm6rzthd0c.gif)

### "Every person that you meet knows something you don't; learn from them." -H. Jackson Brown Jr.


This is an attitude I always see by the best senior developers. Because a senior developer knows that a beginner dev or junior dev is learning all the new shortcuts a senior has missed through its first stages of learning. I find it funny to see that there's often much competition between junior developers. There are always a few with the "I know it all" attitude in the group. Not willing to learn/share from/with others. But I can assure you, you'll come much further if you take the attitude of "we can know it all". One thing which makes the tech industry grow so rapidly is because we share so much. Collecting feedback is what brings us further and speeds up productivity a lot. So don't think a beginner developer or someone who started later than you knows less than you. Stay open for a conversation, when you try to teach them something, they will teach you something in return. That's the ingredient of rapidly growing. If you have the possibility, observe a senior developer. Adapt on how they treat others because 9/10 times they are willing to listen to any developer no matter their skill. Because they know the world of tech, no one knows it all. And everyone has learned something unique and/or has his own unique vision on things. So, don't be an "I know it all", be a "we know it all". Because as cliché as it is, together we are much stronger!


### "It does not matter how slowly you go, as long as you do not stop." -Confucius.

#### So Keep coding!

```
while (true) {
code ();
}
```
ES5 Class based React Components
Tags: react, ie11, tutorial
Published: 2022-06-13 10:36:57

Most tutorials show how to make React components with either hooks or ES6 classes, but I haven't found one that uses ES5 classes. Now you may ask "Why bother with ES5 ?", but I still have to support IE11 & its 2 predecessor at work (at the time of writing). 

I'm going to show you a Number Spinner. Here's the basic skeleton of an ES5 React component.

```javascript
// The constructor cum class declaration
function NumberSpinner(props) {
    // equivalent to super(props)
    React.Component.call(this,props);
}

// These 2 lines together form the equivalent of
// extends React.Component
NumberSpinner.prototype = Object.create(React.Component.prototype);
NumberSpinner.prototype.constructor = NumberSpinner;

NumberSpinner.prototype.render = function() {

};
```





A spinner has only 3 use cases.
[![Spinner Use case](http://yuml.me/diagram/scruffy/usecase/%5BDev%5D-(Initialize%20spinner),%20%5BDev%5D-(Increment%20value),%20%5BDev%5D-(Decrement%20value).svg))](http://yuml.me/diagram/scruffy/usecase/edit/%5BDev%5D-(Initialize%20spinner),%20%5BDev%5D-(Increment%20value),%20%5BDev%5D-(Decrement%20value))


The spinner's state has only 1 property `num` that is added to the constructor.

```javascript
this.state = {num: 0};
```

For the user to be able to assign an initial value to the spinner, there needs to be a prop `initNum`. Unlike Vue, it isn't advisable in React to initialize state with props directly like `this.state = {num: this.props.initNum};`. Instead the static `getDerviedStateFromProps` should be used.

```javascript
NumberSpinner.getDerivedStateFromProps = function(props, state) {
    return {num: props.initNum};
};
```

Increment value

```javascript
NumberSpinner.prototype.increment = function() {
    this.setState(function(state, props) {
        return {num: state.num + 1};
    });
}
```

Decrement Value

```javascript 
NumberSpinner.prototype.decrement = function() {
    this.setState(function(state, props) {
        return {num: state.num - 1};
    });
};
```

To render the spinner, 3 elements are needed: 1 to show the current value 2 increment & decrement buttons.

```javascript
NumberSpinner.prototype.render = function() {
    var ce = React.createElement;
    var current = ce('div',{key:'current'}, this.state.num);
    var increment = ce('button',{key:'increment', onClick: this.increment}, '+');
    var decrement = ce('button',{key:'decrement', onClick: this.increment}, '-');
    return ce('div',{className:'spinner'}, [current,increment,decrement]);
};
```

It's been months I drafted my 1st Dev article, and Internet Explorer will be gone in 2 days. So any feedback is welcome :)
Coin Change
Tags: leetcode, dsa, theabbie
Published: 2022-06-13 10:30:41

You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.

Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.

You may assume that you have an infinite number of each kind of coin.

**Example 1:**

**Input:** coins = \[1,2,5\], amount = 11
**Output:** 3
**Explanation:** 11 = 5 + 5 + 1

**Example 2:**

**Input:** coins = \[2\], amount = 3
**Output:** -1

**Example 3:**

**Input:** coins = \[1\], amount = 0
**Output:** 0

**Constraints:**

*   `1 <= coins.length <= 12`
*   `1 <= coins[i] <= 231 - 1`
*   `0 <= amount <= 104`

**SOLUTION:**

    class Solution:
        def coinChangeRec(self, amount):
            if amount < 0:
                return -1
            if amount == 0:
                return 0
            if amount in self.memo:
                return self.memo[amount]
            numCoins = float('inf')
            for coin in self.coins:
                currMin = 1 + self.coinChangeRec(amount - coin)
                if currMin == 0:
                    continue
                numCoins = min(numCoins, currMin)
            if numCoins == float('inf'):
                numCoins = -1
            self.memo[amount] = numCoins
            return numCoins
        
        def coinChange(self, coins: List[int], amount: int) -> int:
            self.memo = {}
            self.coins = coins
            return self.coinChangeRec(amount)
Self learning is so important...
Tags: beginners, programming, python
Published: 2022-06-13 10:02:15

The lesson I learnt from watching Python tutorial videos on YouTube ,reading PEP documents and some full-semester computer courses is that in terms of computer science stuff, self learning is just much more effective and fun, especially if (1) your all that your instructor do in lectures is reading through PowerPoints and (2) not showing the mechanism with LIVE CODING or (3) just have a strong English accent.
The "C# Workshop" book review.
Published: 2022-06-13 07:26:22

Hello everyone. I am Ankur Mulasi working as an Acquisition Editor at Packt Publishing. This is regarding a marketing activity that we are doing for our title -"The C# Workshop ".
We are looking for your honest unbiased review on amazon.com for the title "The C# Workshop " which will be published on Amazon in July 2022. We are reaching out to a wider group of free reviewers to seek their genuine feedback on the book. We are contacting people who have the right subject-matter knowledge of the book’s topic to know how useful they find it. As part of this activity, we will be sending a free digital copy of the book to you and for now, the finalized chapters in the word format and seek your unbiased feedback about the book on Amazon.com Please note that to post a review on the book, you will need to own an account on Amazon.com along with the eligibility criteria of a purchase history worth of 50 USD in the last 12 months. Also, we might share the content in the current format (Word) as of now, but we promise to also share the final digital copy of the book with you. Would you like to receive a free copy? Please share your email id or you can drop me a message on my LinkedIn. 

Regards,
Ankur Mulasi
https://www.packtpub.com/
https://www.linkedin.com/in/ankurmulasi/
Smallest Subsequence of Distinct Characters
Tags: leetcode, dsa, theabbie
Published: 2022-06-13 10:00:46

Given a string `s`, return _the lexicographically smallest subsequence of_ `s` _that contains all the distinct characters of_ `s` _exactly once_.

**Example 1:**

**Input:** s = "bcabc"
**Output:** "abc"

**Example 2:**

**Input:** s = "cbacdcbc"
**Output:** "acdb"

**Constraints:**

*   `1 <= s.length <= 1000`
*   `s` consists of lowercase English letters.

**Note:** This question is the same as 316: [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/)**SOLUTION:**

    class Solution:
        def smallestSubsequence(self, s: str) -> str:
            lastIndex = {}
            for i, c in enumerate(s):
                lastIndex[c] = i
            used = set()
            stack = []
            for i, c in enumerate(s):
                if c in used:
                    continue
                while len(stack) > 0 and s[stack[-1]] > c and i < lastIndex[s[stack[-1]]]:
                    curr = stack.pop()
                    if s[curr] in used:
                        used.remove(s[curr])
                stack.append(i)
                used.add(c)
            return "".join(s[i] for i in stack)
            
    
    # class Solution:
    #     def smallestSubsequence(self, s: str) -> str:
    #         n = len(s)
    #         numdist = len(set(s))
    #         smallest = ""
    #         paths = [(s[i], [i]) for i in range(n)]
    #         while len(paths) > 0:
    #             curr, indexes = paths.pop()
    #             if smallest:
    #                 if curr < smallest and len(curr) == numdist:
    #                     smallest = curr
    #                     for j in range(indexes[-1] + 1, n):
    #                         if s[j] not in curr:
    #                             paths.append((curr + s[j], indexes + [j]))
    #             elif len(curr) == numdist:
    #                 smallest = curr
    #         return smallest
Let's create our own selector library.
Tags: javascript, webdev, html
Published: 2022-06-13 09:58:24

## The basic framework:
```html
<!DOCTYPE html>
<html lang=de>
  <meta charset=UTF-8>
  <title>myDemo</title>
  <style>
    .blue{
      color:blue;
    }
    .pointer{
      cursor:pointer;
    }
  </style>
  <h1>Selector</h1>
  <p>lorem 1</p>
  <p>lorem 2</p>
<script> 
"use strict";
const $ = function ( selector = null ) {
  class selection {
    constructor( selector ) {    
      if ( selector ) {
        this.nodes =
         selector === document ? [document] :
         selector === window ? [window] :
         selector.nodeType ? [selector] :
         selector.constructor.name==this.constructor.name ? selector.nodes :
         NodeList.prototype.isPrototypeOf( selector ) ? selector :
         document.querySelectorAll( selector )
         this.toNode=this.nodes[0] 
      }
    }

    each = callback => ( this.nodes.
      forEach( ( _node, index ) => 
        callback( _node, index )
      ), this)
  
    addClass = ( ...classes ) => this
      .each( _node =>
        _node.classList.add( ...classes ) )
  
    removeClass = ( ...classes ) => this
      .each( _node =>
        _node.classList.remove( ...classes ) )
  
    click = callBack => this
      .each( ( _node ) => _node
      .addEventListener( 'click' , callBack ) )
   
  }
  return selector = new selection( selector )
}

$( 'p' )
  .addClass( 'blue', 'red' )
  .addClass( 'white' )
  .removeClass( 'white', 'red' )
  .click( ( el ) => console.log(
    el.currentTarget.textContent
  ))
  .addClass( 'pointer' )
    
</script>
``` 

Write your suggestions and code for the extension in the comments:
Build a Group Video Call System using PHP,Javascript + WebRTC Day 2
Tags: webrtc, webdev, tutorial, php
Published: 2022-06-13 09:51:33

WebRTC unlocks the possibility that people can create any video chat app they like. The freedom that WebRTC grants makes the technology highly competitive against traditional video chat apps like Skype.In this video,we are going to create the register page

{% youtube aik96gZUlh8 %}
Bunzz closes a partnership with Spheron protocol to offer fast decentralized hosting for Dapps developers
Tags: webdev, web3, blockchain
Published: 2022-06-13 09:28:21

In order to cover all the steps and processes needed for web3 developers to publish their Dapps, from development to hosting, [Bunzz](https://www.bunzz.dev/) has closed its most recent partnership with Spheron protocol. This will make the final development stage easier and faster for Bunzz users.

[Spheron](https://spheron.network/) makes front-end web deployment easy, effective, and efficient through its blockchain-based platform that takes web apps to the DSNs (Decentralized Storage Networks). It removes the hurdles of centralization and censorship through blockchain, ensuring that Dapps are permanently deployed and experience 99.99% uptime throughout their life.

We are delighted to give a glimpse of how this partnership eases the process of deploying DApps to both Spheron and Bunzz users.

- Spheron Protocol is an all-in-one decentralized platform for automating modern web projects. It allows Bunzz users to replace the web2 hosting infrastructure, continuous integration, and deployment pipeline with a single workﬂow and simplify the deployment process on a decentralized cloud protocol.

- Spheron provides a frictionless developer experience to users to take care of the hard things: deploying instantly, scaling automatically, and serving personalized content on decentralized networks.

- Ecosystem partners: Spheron supports multiple decentralized protocols such as Arweave, Skynet, Filecoin, and Pinata that Bunzz users can use to deploy their apps.

- Allows Bunzz users to choose the protocol that best suits their needs. Turn your apps to dApps in simple streamlined steps.

![The Bunzz X Spheron development flow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fo0gnboy71e52v8h1nny.png)

Check out more detailed information on our Docs [here](https://docs.bunzz.dev/product-docs/others/bubble-plugin): 

In summary, Spheron is an all-in-one decentralized platform created to make the deployment of web apps easier by providing solutions that are transparent, immutable, and cryptographically verifiable, giving full control to developers over their data without worrying about censorship, outages, or hacking.

With the Spheron X Bunzz partnership, all projects under Bunzz shall have preferential access to the Spheron application and Vice versa.

Follow and Join Spheron on [Telegram](https://t.me/argoofficial) | [Discord](https://discord.com/invite/SjQf5shVSD) | [Twitter](https://twitter.com/SpheronHQ) | [LinkedIn](https://www.linkedin.com/company/spheron) 

---
Originally published on Bunzz's offical blog [here](https://blog.bunzz.dev/bunzz-closes-a-partnership-with-spheron-protocol-to-offer-fast-decentralized-hosting-for-dapps-developers/)

Join other web3 developers on [Discord](https://discord.com/invite/rjfvZzDEaN)
Video Converter Software
Tags: beginners, discuss, performance
Published: 2022-06-13 09:17:00

Here are a long list of [best video convetrer](https://www.videoproc.com/media-converter/best-video-converter.htm) from VideoProc, an multimedia software company devoted to designing capable apps for processing large/long/UHD videos. It's the minority that invest time in testing software in such roundup post. I'm glad to share it with you guys here.
Joined the community
Tags: devops, startup, blockchain, discuss
Published: 2022-06-13 09:01:16

Hey guys, how you all are doing.
Guys this post I'm doing here on this community is to tell you that I have just joined the community and now I will be posting here regularly.

I'm a developer and focus on the **Decentralized application development**, **Blockchain Development**, **Smart contract Development**, and more.
If you want any kind of tech support or you wanted to build a project feel free to connect.