teleren/devto huggingface dataset:
Top 5 JavaScript Frameworks for Frontend in 2022
Tags: react, discuss, javascript, webdev
Published: 2022-06-14 14:07:42

1. [React.js](https://reactjs.org/)
2. [Vue](https://vuejs.org/)
3. [Angular](https://angular.io/)
4. [Ember](https://emberjs.com/)
5. [Backbone.js](https://backbonejs.org/)

_**Vote your favourite one in comment section✍️**_

**Sources**
![Image 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h73in8epsj22nu8ru4zp.png)
![Image 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/78tjorpwey224ih6k3gs.png)


Catch me on : [GitHub](https://github.com/deepakydv9315) || [Codepen](https://codepen.io/deepakydv9315) || [Instagram](https://www.instagram.com/syco_coders/)
Contains Duplicate II
Tags: leetcode, dsa, theabbie
Published: 2022-06-14 14:00:46

Given an integer array `nums` and an integer `k`, return `true` if there are two **distinct indices** `i` and `j` in the array such that `nums[i] == nums[j]` and `abs(i - j) <= k`.

**Example 1:**

**Input:** nums = \[1,2,3,1\], k = 3
**Output:** true

**Example 2:**

**Input:** nums = \[1,0,1,1\], k = 1
**Output:** true

**Example 3:**

**Input:** nums = \[1,2,3,1,2,3\], k = 2
**Output:** false

**Constraints:**

*   `1 <= nums.length <= 105`
*   `-109 <= nums[i] <= 109`
*   `0 <= k <= 105`

**SOLUTION:**

    class Solution:
        def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
            valIndex = {}
            for i, num in enumerate(nums):
                if num in valIndex:
                    curr = valIndex[num][-1]
                    if i - curr <= k:
                        return True
                    valIndex[num].append(i)
                else:
                    valIndex[num] = [i]
            return False
Should I have separate GitHub accounts for personal and professional projects?
Tags: discuss, anonymous
Published: 2022-06-14 13:50:45

_This is an anonymous post sent in by a member who does not want their name disclosed. Please be thoughtful with your responses, as these are usually tough posts to write. Email sloan@dev.to if you'd like to leave an anonymous comment or if you want to ask your own anonymous question._ 

***


I was just wondering what I should do - I've been using GitHub for around 2 years now, and I don't know if I should create a separate account for purely professional projects. Then, I'd still be able to keep my personal GitHub for anything I'd like to contribute to. Would that be helpful or redundant? I'd love to know some pros and cons.
Easy migration to Ansible Vault id
Tags: ansible, devops
Published: 2022-06-14 13:49:37

To keep all our tokens secure we use [the Ansible vault](https://docs.ansible.com/ansible/latest/user_guide/vault.html) to encrypt them. Historically all files with secrets were encrypted with a single password instead of using a vault id and password file. This week we decided to migrate to vault id.

All files encrypted with a password and without vault id specified will have the header `$ANSIBLE_VAULT;1.1;AES256`. We can use grep to find all files with this header. To do that run

```
grep "\$ANSIBLE_VAULT;1.1;AES256" group_vars/**/*.yml
```
Now we have a list of files that looks like that: 
```
group_vars/staging/amazon.yml:$ANSIBLE_VAULT;1.1;AES256
group_vars/staging/db.yml:$ANSIBLE_VAULT;1.1;AES256
group_vars/staging/docker_registry.yml:$ANSIBLE_VAULT;1.1;AES256
....
```

Grep adds matched string at the end of every file. We can use the `cut` command to remove this part since we only need file names. `cut -d: -f1` will leave only the file name.

And finally, we can use `xargs` to pass the file list to the `ansible-vault rekey` command to convert all encrypted files to encrypted files with vault id.

The full command will look like this:
```
grep "\$ANSIBLE_VAULT;1.1;AES256" group_vars/**/*.yml | cut -d: -f1 | xargs ansible-vault rekey --new-vault-id vaultID@vaultfile
```
Sort Integers by The Power Value
Tags: leetcode, dsa, theabbie
Published: 2022-06-14 13:30:38

The power of an integer `x` is defined as the number of steps needed to transform `x` into `1` using the following steps:

*   if `x` is even then `x = x / 2`
*   if `x` is odd then `x = 3 * x + 1`

For example, the power of `x = 3` is `7` because `3` needs `7` steps to become `1` (`3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1`).

Given three integers `lo`, `hi` and `k`. The task is to sort all integers in the interval `[lo, hi]` by the power value in **ascending order**, if two or more integers have **the same** power value sort them by **ascending order**.

Return the `kth` integer in the range `[lo, hi]` sorted by the power value.

Notice that for any integer `x` `(lo <= x <= hi)` it is **guaranteed** that `x` will transform into `1` using these steps and that the power of `x` is will **fit** in a 32-bit signed integer.

**Example 1:**

**Input:** lo = 12, hi = 15, k = 2
**Output:** 13
**Explanation:** The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)
The power of 13 is 9
The power of 14 is 17
The power of 15 is 17
The interval sorted by the power value \[12,13,14,15\]. For k = 2 answer is the second element which is 13.
Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.

**Example 2:**

**Input:** lo = 7, hi = 11, k = 4
**Output:** 7
**Explanation:** The power array corresponding to the interval \[7, 8, 9, 10, 11\] is \[16, 3, 19, 6, 14\].
The interval sorted by power is \[8, 10, 11, 7, 9\].
The fourth number in the sorted array is 7.

**Constraints:**

*   `1 <= lo <= hi <= 1000`
*   `1 <= k <= hi - lo + 1`

**SOLUTION:**

    import heapq
    
    class Solution:
        def getPower(self, n):
            if n == 1:
                return 0
            if n in self.power:
                return self.power[n]
            if n & 1:
                val = 1 + self.getPower(3 * n + 1)
            else:
                val = 1 + self.getPower(n >> 1)
            self.power[n] = val
            return val
                
        
        def getKth(self, lo: int, hi: int, k: int) -> int:
            self.power = {}
            heap = []
            for num in range(lo, hi + 1):
                heapq.heappush(heap, (-self.getPower(num), -num))
                if len(heap) > k:
                    heapq.heappop(heap)
            return -heap[0][1]
#OpenCV – Convert camera feed 🎦 to Grayscale and resalt Blue 🔵 and Red ❤️
Tags: englishpost, codesample, opencv
Published: 2022-06-15 14:18:56

---
title: #OpenCV – Convert camera feed 🎦 to Grayscale and resalt Blue 🔵 and Red ❤️
published: true
date: 2022-06-14 13:29:30 UTC
tags: EnglishPost,CodeSample,EnglishPost,OpenCV
canonical_url: 
---

Hi !

A new twist on these days demos, this time:

- Open a camera feed
- Convert each frame to grayscale
- Use a hue mask to resalt colors, Blue and Red

Here is a live sample from my office.

![Convert image to GraysScale and resalt red and blue](https://brunocapuano.files.wordpress.com/2022/06/convert-image-to-graysscale-and-resalt-red-and-blue.jpg?w=808)

Note: I created a mask that identifies the Captain America shield, SpyderGwen poster and Ahsoka frame, but it’s missing the Canada flag 🍁 ! Still, my guitar and working desk are converted to grayscale.

Another funny scenario !

And the sample code:

{% gist https://gist.github.com/elbruno/bdbdea6088fa841db9ff1183381813f8 %}

Happy coding!

Greetings

El Bruno

More posts in my blog [ElBruno.com](https://www.elbruno.com).

* * *
HTML tips
Tags: webdev, javascript, css, html
Published: 2022-06-12 17:00:25

Following are the html tips:

Change the menu

`function showHide(anchor)
{
	if(anchor.innerHTML.startsWith("Show"))
	{
		anchor.innerHTML = anchor.innerHTML.replace("Show","Hide");
	}
	else
	{
		anchor.innerHTML = anchor.innerHTML.replace("Hide","Show");
	}
}`


Checking if the div with id exists
ength property will return zero if element does not exists.

`if ($("#mydiv").length > 0){
  // do something here
}`


Getting the child element from the parent element

`var parent = document.getElementById('disptable');
parent.querySelector("#boardc");`


Setting CSS to the element

`function setCSS(eleID) {
    var currTabElem = document.getElementById(eleID);
    currTabElem.setAttribute("class", "some_class_name");
    currTabElem.setAttribute("className", "some_class_name");
}`


Show and Hide div element

`<button onclick="myFunction()">Click Me</button>

<div id="myDIV">
  This is my DIV element.
</div>

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}`

Creating Text Node

`let docs = document.getElementByID('#freelancer');
let elements = freelancer.getElementsByClassName('item');
var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");
td1.appendChild(text);`

removing the highlighted marked text

`targets = document.querySelectorAll("mark");
for (let target of targets) {  
  target.outerHTML=target.innerHTML;
}`


Getting the table column cell text

`$('#td1').html('hello world');
	$(tbl).find('tr').each(function(){
	    var currentRow=$(this);
		var column_count = 0;
		currentRow.find("td").each(function() {
			var currentColumn = $(this);
			var col_value = currentColumn.text();
			});
			});`
yet another fail
Tags: interview, mental, paralysis
Published: 2022-06-14 13:10:22

---
title: yet another fail
published: true
description: about my nth fuckup
tags: interview, mental, paralysis
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

I weren't able to write that code during an interview. I've been asked to scrape unique 200 posts from a json feed.


```ruby
require 'net/http'
require 'json'

start_url = "https://url-to-json.feed"
posts = []

loop do
  body = JSON.parse(Net::HTTP.get(URI(start_url)))
  next_page = body["paging"]["next"]
  body["data"].each do |new_post| 
    id_exists = posts.detect {|post| post["id"] == new_post["id"] }
    unless id_exists
      posts << new_post
    end
  end
  url = next_page
  if posts.count > 199 
    break
  end
end
```

Instead of that dumb and simple 15 lines of code, I started to create functions, pipe them each other, do some bullshit abstractions, and finally fucked up.
How to Push an Empty Commit in Git
Tags: git, github, devops
Published: 2022-06-14 13:09:07

There are a lot of Git commands.  I'm always discovering a new and useful one.  This time I have found one that allows you to push an empty commit to a repository. 

## Why push an empty Git commit?

Git doesn't allow you to push commits without making changes, and there are times when you don't want to make changes but perhaps trigger a pipeline or job or build that is attached to a repository. 

This is where pushing an empty commit can come in handy.  If you can't manually trigger your build or pipeline, staying in the command line prompt and pushing an empty commit can mean triggering the build or pipeline without making any changes. 

## How to push an empty commit
It is a fairly straight forward command, using the --allow-empty flag. 

```bash
git commit --allow-empty -m "Empty commit"
```

Very similar to pushing a commit when you've made changes to your code.  But using this flag you can push a commit without making any changes. 😊
Copy List with Random Pointer
Tags: leetcode, dsa, theabbie
Published: 2022-06-14 13:00:47

A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`.

Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**.

For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`.

Return _the head of the copied linked list_.

The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where:

*   `val`: an integer representing `Node.val`
*   `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node.

Your code will **only** be given the `head` of the original linked list.

**Example 1:**

![](https://assets.leetcode.com/uploads/2019/12/18/e1.png)

**Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]

**Example 2:**

![](https://assets.leetcode.com/uploads/2019/12/18/e2.png)

**Input:** head = \[\[1,1\],\[2,1\]\]
**Output:** \[\[1,1\],\[2,1\]\]

**Example 3:**

**![](https://assets.leetcode.com/uploads/2019/12/18/e3.png)**

**Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\]
**Output:** \[\[3,null\],\[3,0\],\[3,null\]\]

**Constraints:**

*   `0 <= n <= 1000`
*   `-104 <= Node.val <= 104`
*   `Node.random` is `null` or is pointing to some node in the linked list.

**SOLUTION:**

    """
    # Definition for a Node.
    class Node:
        def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
            self.val = int(x)
            self.next = next
            self.random = random
    """
    
    class Solution:
        def copy(self, head):
            newhead = None
            if head:
                newhead = self.visited.get(head, Node(head.val))
                self.visited[head] = newhead
                if head.random != None:
                    newhead.random = self.visited.get(head.random, Node(head.random.val))
                    self.visited[head.random] = newhead.random
                newhead.next = self.copy(head.next)
            return newhead
        
        def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
            self.visited = {}
            return self.copy(head)
Umbraco 10 - punkTwoFactor Authentication Package
Tags: umbraco, twofactor, dotnet, csharp
Published: 2022-06-14 12:53:51

I needed to easily rollout **Two Factor** authentication on Umbraco, so I decided to take the [Umbraco Documentation](https://our.umbraco.com/documentation/Reference/Security/two-factor-authentication/#two-factor-authentication-for-users) and create a package to make installation simple for Umbraco 9.5+ sites.  

I've changed some of the code to be extensions on the IUmbracoBuilder rather than a composer, added the manual key to the dialog modal and added configuration for each environment.

## Nuget

https://www.nuget.org/packages/punkTwoFactor/

```
Install-Package punkTwoFactor
```

## Installation

Install the nuget package, then add the following section to your appsettings.json:
```json
"punkTwoFactor": {
    "ProviderName": "Two Factor Authentication",
    "Issuer": "Two Factor Authentication - Dev",
    "BackOfficeView": "..\\App_Plugins\\punkTwoFactor\\twoFactorProviderGoogleAuthenticator.html"
  }
```

Add the following code block within your **ConfigureServices** section above the Umbraco setup:
```csharp
services.Configure<TwoFactorConfig>(_config.GetSection("punkTwoFactor"));
TwoFactorConfig twoFactorConfiguration = new();
_config.GetSection("punkTwoFactor").Bind(twoFactorConfiguration);
```

Now add the "AddBackOfficeTwoFactorAuthentication" extension to the Umbraco setup. 

```csharp
services
    .AddUmbraco(_env, _config)
    .AddBackOffice()
    .AddWebsite()            
    .AddBackOfficeTwoFactorAuthentication(twoFactorConfiguration)
    .Build();
```

## Usage

Click on your profile picture in Umbraco:
![Header](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8u9k235suhu6ai6k2cyh.png)
 
Click the **Configure Two Factor** button:
![Configure Two-Factor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zejvdoj1c0272vr26a4v.png)

Then click **Enable**:
![Enable Button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lgwpggfoqj6bhwr457ih.png)
 
You'll then see the familar QR code, with the additional Manual Input key: 
![QR Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7a59zw5bedh4sk2f0cny.png)

Once you add this QR code to your authenticator, you can enter the code and you're good! 

![Enabled](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1mb6pbh9xvalnr354i6x.png)
  
You'll now be configured to use Two Factor Authentication on your account! :) 

![Login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v50sg5tvluzc4f16034t.png)
 
## GitHub 

https://github.com/garpunkal/punkTwoFactor

## Contact

If you need any help, give me a shout on [twitter](https://twitter.com/garpunkal).
N-ary Tree Postorder Traversal
Tags: leetcode, dsa, theabbie
Published: 2022-06-14 12:30:42

Given the `root` of an n-ary tree, return _the postorder traversal of its nodes' values_.

Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)

**Example 1:**

![](https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png)

**Input:** root = \[1,null,3,2,4,null,5,6\]
**Output:** \[5,6,3,2,4,1\]

**Example 2:**

![](https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png)

**Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\]
**Output:** \[2,6,14,11,7,3,12,8,4,13,9,10,5,1\]

**Constraints:**

*   The number of nodes in the tree is in the range `[0, 104]`.
*   `0 <= Node.val <= 104`
*   The height of the n-ary tree is less than or equal to `1000`.

**Follow up:** Recursive solution is trivial, could you do it iteratively?

**SOLUTION:**

    """
    # Definition for a Node.
    class Node:
        def __init__(self, val=None, children=None):
            self.val = val
            self.children = children
    """
    
    class Solution:
        def postorder(self, root: 'Node') -> List[int]:
            if not root:
                return []
            children = []
            for node in root.children:
                children += self.postorder(node)
            return children + [root.val]
Trino: Scalable, Distributed, and OpenSource SQL Engine!
Tags: tutorial, database, nosql, opensource
Published: 2022-06-14 12:17:32

Trino: SQL at any scale, on any storage, in any environment!
Trino is a tool designed to query large amounts of data using distributed queries efficiently. If you work with terabytes or petabytes of data, you probably use tools that interact with Hadoop and HDFS. Trino is designed as an alternative to tools that query HDFS using MapReduce job pipelines such as Hive or Pig, but Trino is not limited to accessing HDFS. 

Trino can be extended to operate on different data sources, including traditional relational databases and other data sources such as Cassandra.

Trino is designed to handle data storage and analysis: analyzing data, aggregating large amounts of data, and producing reports. These workloads are generally classified as Online Analytical Processing (OLAP).
To learn more about it, visit:

https://jlgjosue.medium.com/trino-scalable-distributed-and-open-source-sql-engine-f51f42f863c1

Thanks for your reading; share the post! :)
Dependency injection without the decorators
Tags: javascript, webdev, beginners
Published: 2022-06-14 12:10:09

I'm a big fan of dependency injection since I'm working with the front-end a lot, I needed a dependency injection library that is not based on decorators and has a small file size.  I couldn't find anything, so I've created one myself.

It's called `Pumpa` it's around 2KB and this is how it works.

```ts
class A {
  static inject=[B]
  constructor(public b:B){}
}
class B {}

const container = new Pumpa()

container.bindClass(A,A)
container.bindClass(B,B)

const instanceA = container.resolve<A>(A)
```

You can also register function factories

```ts
class B{}

function myFactory(b: B) {
  return function resolvedFunction() {
    // do something with b
  }
}

myFactory.inject = [B]

container.bindFactory(myFactory, myFactory)

const fn = container.resolve(myFactory)
fn === resolvedFunction
```

There is also another way to register values with the container. It is particularly useful when you don't have access to the values you want to register (third-party libraries).

```ts
class A {
  //note: there is no static inject property on the class
  constructor(public b:B){}
}
class B {}

const container = new Pumpa()

//alternative way of registering
container.bindClass(A,{value:A,inject:[B]})
container.bindClass(B,B)

const instanceA = container.resolve<A>(A)
instanceA.b === B
```
It also supports injecting an array of dependencies.

```ts
class A {
  static inject = [getArray([A, B, C])]
  constructor(deps: [A, B, C]) {}
}
```

And that's the gist of it.

It is written in Typescript, it is modeled similarly to the [Microsoft tsyringe](https://github.com/microsoft/tsyringe) (which I was using previously).

I've spent a lot of time on the documentation, so head over to the [Github repository](https://github.com/ivandotv/pumpit) to see what else the library can do.

I'm open to new ideas and pull requests.
UML Class Association Explain with Code
Tags: uml
Published: 2022-06-14 12:04:03

Short note about relation in UML class diagram.

## Relation and Dependency 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mqis62ir6gsbhchn6hv3.png)

Can turn into TS code like this 

```ts
class Address {}

class Food {}

class People {
  // for this line People has relation with Address 
  address: Address
  heart: Heart

  // for this line People has dependency with Food
  eat(food: Food) {}
}
```  

## Aggregation and Composition 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tx3t994rdirqnav8124h.png)

Can turn into TS code like this

```ts
class Heart {}

class People {
  heart: Heart

  constructor () {
    // for this line People has composition with Heart
    this.heart = new Heart()
  }
}

class PeopleGroup {
  peoples: People[]

  // for this line PeopleGroup has aggregation with (alot of) People
  constructor (peoples: People[]) {
    this.peoples = peoples
  }
}
``` 

## Generalization and Realization 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gexi0ptfbp6x127p9kms.png)

Can turn into TS code like this 

```ts
class Animal {}

interface Eatting {
  eat(food: Food): void
}

class People 
  // for this line People is extends (generalization) from Animal
  extends Animal
  // for this line People is implement (realization) from Eatting
  implements Eatting {
  // ...
}
```