teleren/devto huggingface dataset:
Maximal Network Rank
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 04:00:47

There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`.

The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either** city. If a road is directly connected to both cities, it is only counted **once**.

The **maximal network rank** of the infrastructure is the **maximum network rank** of all pairs of different cities.

Given the integer `n` and the array `roads`, return _the **maximal network rank** of the entire infrastructure_.

**Example 1:**

**![](https://assets.leetcode.com/uploads/2020/09/21/ex1.png)**

**Input:** n = 4, roads = \[\[0,1\],\[0,3\],\[1,2\],\[1,3\]\]
**Output:** 4
**Explanation:** The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.

**Example 2:**

**![](https://assets.leetcode.com/uploads/2020/09/21/ex2.png)**

**Input:** n = 5, roads = \[\[0,1\],\[0,3\],\[1,2\],\[1,3\],\[2,3\],\[2,4\]\]
**Output:** 5
**Explanation:** There are 5 roads that are connected to cities 1 or 2.

**Example 3:**

**Input:** n = 8, roads = \[\[0,1\],\[1,2\],\[2,3\],\[2,4\],\[5,6\],\[5,7\]\]
**Output:** 5
**Explanation:** The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.

**Constraints:**

*   `2 <= n <= 100`
*   `0 <= roads.length <= n * (n - 1) / 2`
*   `roads[i].length == 2`
*   `0 <= ai, bi <= n-1`
*   `ai != bi`
*   Each pair of cities has **at most one** road connecting them.

**SOLUTION:**

    from collections import defaultdict
    
    class Solution:
        def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
            l = len(roads)
            edges = defaultdict(set)
            for k in range(l):
                a, b = roads[k]
                edges[a].add(k)
                edges[b].add(k)
            mnetwork = 0
            for i in range(n):
                for j in range(i + 1, n):
                    mnetwork = max(mnetwork, len(set.union(edges[i], edges[j])))
            return mnetwork
Learning from Different Programming Language
Tags: programming, discuss
Published: 2022-06-11 13:00:53

I have worked on different programming language / frameworks mostly for web development tasks. Here are list of tasks which seems to be common across all programming language, syntax is different but semantic remains almost same across programming language

1. Variable declaration or assignment
2. Loop construct like while, for.
3. Function declaration or return
4. Meta programming support
5. Import / Exporting the function or file
Longest Valid Parentheses
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 13:00:46

Given a string containing just the characters `'('` and `')'`, find the length of the longest valid (well-formed) parentheses substring.

**Example 1:**

**Input:** s = "(()"
**Output:** 2
**Explanation:** The longest valid parentheses substring is "()".

**Example 2:**

**Input:** s = ")()())"
**Output:** 4
**Explanation:** The longest valid parentheses substring is "()()".

**Example 3:**

**Input:** s = ""
**Output:** 0

**Constraints:**

*   `0 <= s.length <= 3 * 104`
*   `s[i]` is `'('`, or `')'`.

**SOLUTION:**

    class Solution:
        def longestValidParentheses(self, s: str) -> int:
            n = len(s)
            stack = [-1]
            mlen = 0
            for i, c in enumerate(s):
                if c == '(':
                    stack.append(i)
                elif len(stack) > 0:
                    stack.pop()
                    if len(stack) > 0:
                        mlen = max(mlen, i - stack[-1])
                    else:
                        stack.append(i)
            return mlen
How to Install Redis on Linux Server (Ubuntu 20.04)
Tags: redis, ubuntu, linux, webdev
Published: 2022-06-11 12:56:42

## What is Redis Cache

Redis is an open-source in-memory key-value data store. It can be used as a database, cache and queue.  Redis supports various data structures such as Strings, Hashes, Lists, Sets, and more. Redis can provide high availability using Redis Node Cluster.

## Install Redis on Ubuntu 20.04
You can install Redis on Linux Server using following commands

`$sudo apt update
$sudo apt install redis-server`

Once the installation is done, then Redis service will start automatically. You can check the status of the Redis service using following command:

`$sudo systemctl status redis-server`

**You will get following output** 

`redis-server.service - Advanced key-value store
     Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
     Active: active (running) since Sat 2022-06-11 12:15:20 UTC; 20s ago
...`


## Test Redis Server Locally 
To verify that everything is set up properly, you can try to ping the Redis server from your server using the **redis-cli** command:
`redis-cli -h <REDIS_IP_ADDRESS> ping`

If you are testing locally from server then, this **REDIS_IP_ADDRESS ** would be 127.0.0.1

Above command should return a response of **PONG**



## Test Redis Server Remotely 
To verify that everything is set up properly, you can try to ping the Redis server from your Remote Machine using the redis-cli command:

`redis-cli -h <REDIS_IP_ADDRESS> ping`

REDIS_IP_ADDRESS would be your Server Public IP Address where Redis is installed.

Above command should return a response of PONG

**IMPORTANT **– Redis run on port: 6379 so you have to open this Port to communicate from Remote machine.
Deploy Nest JS App using PM2 on Linux (Ubuntu) Server
Tags: nestjs, devops, pm2, ubuntu
Published: 2022-06-11 11:14:35

In this article, I will cover steps that will help you to deploy Nest JS application on Linux Server. I am using **Ubuntu 20.04 LTS **during writing this article and I am assuming you have already installed **Node.js** on your server.

## Step 1 (Install Nest JS CLI)
Generally, we use **npm i** command to run all the dependencies but that will not install Nest JS so we have to manually install Nest JS CLI

`$ sudo npm i -g @nestjs/cli`


## Step 2 (Install PM2)
If you didn’t install PM2 earlier then you have to use following command to install PM2. 

`$ sudo npm install pm2@latest -g`

If you want to get more details about PM2 commands, then please visit url: [PM2 Commands](https://pm2.keymetrics.io/docs/usage/quick-start/)

## Step 3 (Clone Code Repository)
You can clone your repo using following command and install necessary dependencies. If you want more details on Cloning, please refer article: [Clone Specific Git Branch](https://dev.to/deadwin19/how-to-clone-a-specific-git-branch-1npj)

`$ git clone http://coderepo.com/projectname.git
$ cd projectname
$ npm install`

## Step 4 (Build Project)
For Nest JS app, you have to first generate a build then only you can run the project on server.

`$ npm run build`

## Step 5 (Run Project)
If build is generated successfully then will create /dist folder under root directory. Now you can run your project using following PM2 command

`$ pm2 start dist/main.js --name <application_name>`

**_application_name_** you can use to give unique app name so that you can easily identify your apps in pm2 list.

There are some PM2 commands to make your application auto restart after system reboot also

`$ pm2 startup systemd
$ pm2 save`

## Conclusion

I hope this article will help you deploy your Nest JS application on Linux Server. If you liked the solution, please hit the Clap button or comment if you have any suggestion or feedback.
5 things you need to be a great platform manager
Tags: engineer, platformmanager, productivity, microservices
Published: 2022-06-11 12:54:05

Being a platform manager is a challenging job. In this video, I talk about 5 things that can be done to make your life a bit easier:
- Budget & Time
- Define Platform Interface
- Reduce Custom Engineering
- Build Right Culture
- Everything as a Service

{% embed https://www.youtube.com/watch?v=nXrop_JVV2I %}
Smallest Index With Equal Value
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 12:30:37

Given a **0-indexed** integer array `nums`, return _the **smallest** index_ `i` _of_ `nums` _such that_ `i mod 10 == nums[i]`_, or_ `-1` _if such index does not exist_.

`x mod y` denotes the **remainder** when `x` is divided by `y`.

**Example 1:**

**Input:** nums = \[0,1,2\]
**Output:** 0
**Explanation:** 
i=0: 0 mod 10 = 0 == nums\[0\].
i=1: 1 mod 10 = 1 == nums\[1\].
i=2: 2 mod 10 = 2 == nums\[2\].
All indices have i mod 10 == nums\[i\], so we return the smallest index 0.

**Example 2:**

**Input:** nums = \[4,3,2,1\]
**Output:** 2
**Explanation:** 
i=0: 0 mod 10 = 0 != nums\[0\].
i=1: 1 mod 10 = 1 != nums\[1\].
i=2: 2 mod 10 = 2 == nums\[2\].
i=3: 3 mod 10 = 3 != nums\[3\].
2 is the only index which has i mod 10 == nums\[i\].

**Example 3:**

**Input:** nums = \[1,2,3,4,5,6,7,8,9,0\]
**Output:** -1
**Explanation:** No index satisfies i mod 10 == nums\[i\].

**Constraints:**

*   `1 <= nums.length <= 100`
*   `0 <= nums[i] <= 9`

**SOLUTION:**

    class Solution:
        def smallestEqual(self, nums: List[int]) -> int:
            n = len(nums)
            for i in range(n):
                if i % 10 == nums[i]:
                    return i
            return -1
Throwing disk reads and writes away!
Tags: webdev, node, typescript, api
Published: 2022-06-11 12:24:50

So earlier in this series, I told you how I did the image manipulations. When I first learned how to decode an image from a base64 string into an image file, I wrote that file to disk and then accessed that file. I did this for two reasons, the first to be quite honest was because the tutorial I had come across had done it that way. The second being that I was used to working with files on disk and I didn’t want to leave my comfort zone at the time cause I was just happy having the base64 image decoded. I hadn’t done much work with buffers directly and I didn’t want to try and mess with them yet so I opted to go with the thing I was most familiar with, writing to and reading from disk.

It was when it came to deploying the application that I started thinking about converting the app to not write the image to disk. I was thinking about deployment and one of the options I thought of was deploying the app as a serverless function. I’ve never worked with serverless functions before and felt this may be a good opportunity to explore them. Ultimately, I didn’t deploy the app that way but that was my thought process when I decided to do the conversion. I also thought about the performance of the application and reads and writes to and from disk, even using a PCIe SSD which my machine was using would be slower. Also, JavaScript is asynchronous and API Developers try to utilize this in the writing of their applications. In my application, my reads and writes had to be synchronous which also slowed the application down. The performance gains in practice would be negligible but it was good practice and ironically a key refactor for a successful deployment, but I’ll touch on that in another article.

The conversion was easy enough. The key thing for me was honestly viewing the buffer as a variable that can be passed around like other variables in JavaScript. Originally, the function would return an address to the file to be used later but now we just passed around the image buffer instead. I had some scripts written for cleaning up the images written to disk as I worked which I could take out since I was no longer writing things to disk which made starting up the application a much cleaner experience.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/98nx63y2kz834kifsyds.png)<figcaption>My base64 conversion functions before the reimplementation</figcaption>
 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fzu5b4eyd0e5kpu1tuv8.png)<figcaption>My base64 conversion functions after the reimplementation</figcaption>
  

With this work done, I felt the app was ready to be deployed and reviewed!

Here’s a commit with containing the conversion: https://github.com/chadstewart/you-go-backend-project/commit/090dbb7c6c2d10ddbd1742fd9381f6719a3dd209

In the next article of this series, I’ll talk about how I did logging and I eventually deployed the application.
First Ever Blog Post
Tags: beginners, cloudresumechallenge, aws
Published: 2022-06-10 18:38:10

I've never blogged before, just not my thing, but I'll jump off the deep end and see what happens.

I'm not a writer, never really enjoyed it, oddly enough though, I'm pretty good at it. I'm more of an analytical thinker and doer. I mean, I can write something down to get a point across or explain how to do something, but creative writing is unknown to me. I'm a - hand me a task and I'll get it done in the most efficient, simple way I know how - kind of guy.  KISS for all you old engineers out there.

Although for you poor souls who are kind enough to follow me, you may get everything from a step-by-step blueprint to a stream of unintelligible thoughts that resemble a summoning spell (too bad I don't know Latin). And once the original purpose of this blog is fulfilled, may never see another post again. Guess it depends on how much I come to enjoy it and what things I think are interesting enough to write about.

Now for this original purpose I spoke of. I've recently stumbled across this thing called the Cloud Resume Challenge.  It's a bit old now, originally conceived in 2020 by Forrest Brazeal. I won't go into the details here, follow the link to see for yourself what it's about.  Anyways, part of the challenge is to create a blog and post about your progress. So here it is, my blog. Probably won't be fancy (not the creative type remember), but I'll try and make it fun and informative as I write about my trials and tribulations moving forward. Definitely won't be a daily thing, but I will try my best to post something once a week so you know how it's going.

Should probably call this entry good and move on. Just wanted to introduce myself a bit, and give the basis for this blog, that's done, so see you next time.

{% embed https://cloudresumechallenge.dev/docs/the-challenge/ %}
Ubuntu で Alt Shift 4 で選択範囲のスクショをして Clipboard に貼り付けられるようにする
Tags: ubuntu
Published: 2022-06-11 12:09:22


## Why

Mac では Cmd Shit ctrl 4 で
選択範囲のスクショが開始して
クリップボードに行った。

かなり便利だったので、Ubuntu でも同じキーで動くようにした。

---

## Setttings/KeybaordShortcuts/Screenshots のキーバインドを書き換える

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/89xulyc4f2xecyk6xa88.png)

Setttings/KeybaordShortcuts/Screenshots

設定のキーボードショートカットを見ると
全て書き換えられる。
Mac よりはるかに自由だな？？

Copy a screenshot of an area to clipboard

これの当てられているキーを

Alt Shift 4

これに変えると適用された。

快適だ。Mac から移りやすい。
What is Currying function? – JavaScript
Tags: javascript, currying, programming, tutorial
Published: 2022-06-11 12:01:33

The currying function takes a function with multiple arguments into a sequence of functions, each with only a single argument.

Currying is named after mathematician Haskell Curry.

Using the currying function, an n-ary function turns into a unary function.

Example of n-ary function and turn into curing function (code):

`const multiargFunction = (a,b,c) => a + b + c;
console.log(multiargFunction(1,2,3))   //6

const curryFunction = (a) => (b) => (c) => a + b + c;
console.log(curryUnaryFunction(1)); // returns a function: (b) => (c) =>  a + b + c
console.log(curryUnaryFunction(1)(2)); // returns a function: (c) => a + b + c
console.log(curryUnaryFunction(1)(2)(3)); // returns the number 6 `

Curried functions are great to improve code reusability and functional composition.

I hope you like our post, please feel free to comment with your suggestion or problems you face in programming.
Clone Graph
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 12:00:48

Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.

Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.

Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.

class Node {
    public int val;
    public List<Node> neighbors;
}

**Test case format:**

For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.

**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.

The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.

**Example 1:**

![](https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png)

**Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Explanation:** There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/01/07/graph.png)

**Input:** adjList = \[\[\]\]
**Output:** \[\[\]\]
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.

**Example 3:**

**Input:** adjList = \[\]
**Output:** \[\]
**Explanation:** This an empty graph, it does not have any nodes.

**Constraints:**

*   The number of nodes in the graph is in the range `[0, 100]`.
*   `1 <= Node.val <= 100`
*   `Node.val` is unique for each node.
*   There are no repeated edges and no self-loops in the graph.
*   The Graph is connected and all nodes can be visited starting from the given node.

**SOLUTION:**

    """
    # Definition for a Node.
    class Node:
        def __init__(self, val = 0, neighbors = None):
            self.val = val
            self.neighbors = neighbors if neighbors is not None else []
    """
    
    class Solution:
        def cloneGraph(self, node: 'Node') -> 'Node':
            if not node:
                return node
            nodemap = {}
            nodemap[node.val] = Node(val = node.val)
            paths = [node]
            while len(paths) > 0:
                curr = paths.pop()
                currcopy = nodemap[curr.val]
                for nbr in curr.neighbors:
                    if nbr.val not in nodemap:
                        paths.append(nbr)
                        nodemap[nbr.val] = Node(val = nbr.val)
                    currcopy.neighbors.append(nodemap[nbr.val])
            return nodemap[node.val]
Aviyel | Made with Next JS
Published: 2022-06-11 11:49:06

![Aviyel | Made with Javascript | Next JS](https://res.cloudinary.com/madewithjavascript/image/upload/v1654095554/large_aviyel_made_with_next_js_08f3c93896.png "Aviyel | Made with Javascript | Next JS")


### Aviyel is a community platform for open source projects to monetise and be sustainable.

> Aviyel Rewards is a rewards and recognition platform for open source communities. Contributors can earn badges and mint them as soul-bound NFTs for both their code and non-code contributions across platforms.
> 
> ### Build Sustainable Communities, Scale Open Source Projects.
> 
> Awesome communities make Amazing Open Source Projects. Make your community fun and awesome.
> 
> #### Build Relations
> Transition your community to your favourite hangout place.Meet great people who share your passion and goals, strike conversations and build together.
> 
> #### Rewards for Contributions
> Find more reasons than your love for the project to contribute. Get rewarded for your contribution, build your reputation and be a proud shareholder in your project's success.
> 
> #### Acquire & Share Knowledge
> Go all the way from an explorer to an expert. Accelerate your open source journey by learning from the best in the community and share your knowledge to pave way for others.
> 
> #### Seamless Decision Making
> Decision making and operational frameworks to run faster and to be ready for the inevitable scale of your project. Organized communities can be more powerful than teams.

## Check out more such amazing projects on our website

[Made with Javascript](https://madewithjavascript.club)

## Want us to feature your project

[Submit your Project to Made with Javascript](https://madewithjavascript.club/submit-project)


You can also write to us for any of your queries at:

[Email Made with Javascript](mailto:madewithjavascript@gmail.com)

## Project already shared on our social media handles.

| SocialMedia | SharedLink |
| ----------- | ---------- |
| Twitter | [Aviyel on Twitter](https://twitter.com/withjavascript/status/1535588198453329922?s=20&t=Cc9bH1OghUbeuxaz7LE26g)
 |
| Medium | [Aviyel on Medium](https://medium.com/@madewithjavascript/aviyel-made-with-next-js-f5a279c9f21b)
 |
| Facebook | [Aviyel on Facebook](https://www.facebook.com/madewithjavascript/posts/pfbid0KnSYwouJ9DZnz95w9SGdzY9qJzPqLjssWZuRyeZ9TSH8Wyh6HsUU3Aaky1FePdZil)
 |
| Tumblr | [Aviyel on Tumblr](https://www.tumblr.com/blog/view/madewithjavascript/686762658475687936?source=share)
 |
| LinkedIn | [Aviyel on LinkedIn](https://www.linkedin.com/feed/update/urn:li:activity:6941354264099270656)
 |
| Pinterest | [Aviyel on Pinterest](https://pin.it/536kkJG)
 |


Filled Under:
 - [Made with Javascript](https://madewithjavascript.club)
    
 - [Made with Next JS](https://madewithjavascript.club/categories/next-js)

Make sure to give this post ❤ 50 ❤ hearts, click the 🦄 unicorns 🦄 and follow 👉 @madewithjavascript 👈 for more such awesome showcases. Show you love for the people who have worked so hard!