teleren/devto huggingface dataset:
Serialize and Deserialize Binary Tree
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 07:00:41

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

**Clarification:** The input/output format is the same as [how LeetCode serializes a binary tree](/faq/#binary-tree). You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/09/15/serdeser.jpg)

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

**Example 2:**

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

**Constraints:**

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

**SOLUTION:**

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Codec:
    
        def serialize(self, root: Optional[TreeNode]) -> str:
            tree = {}
            paths = [(root, 0)]
            while len(paths) > 0:
                curr, i = paths.pop()
                if curr:
                    tree[i] = curr.val
                    paths.append((curr.left, 2 * i + 1))
                    paths.append((curr.right, 2 * i + 2))
            return ";".join(["{}={}".format(k, v) for k, v in tree.items()])
    
        def deserialize(self, data: str) -> Optional[TreeNode]:
            vals = data.split(";")
            tree = {}
            for v in vals:
                if len(v) > 0:
                    key, value = v.split("=")
                    tree[int(key)] = int(value)
            if len(tree) == 0:
                return None
            root = TreeNode()
            paths = [(root, 0)]
            while len(paths) > 0:
                curr, i = paths.pop()
                curr.val = tree[i]
                if (2 * i + 1) in tree:
                    curr.left = TreeNode()
                    paths.append((curr.left, 2 * i + 1))
                if (2 * i + 2) in tree:
                    curr.right = TreeNode()
                    paths.append((curr.right, 2 * i + 2))
            return root
            
    
    # Your Codec object will be instantiated and called as such:
    # ser = Codec()
    # deser = Codec()
    # ans = deser.deserialize(ser.serialize(root))
Do you use semicolon in JS?
Published: 2022-06-05 06:53:31

Do you usually use semicolon when you program? And why?

In my case, I don't use semicolon. I know how ASI(Auto Semicolon Insertion) works and it's rule makes my code more clean and readable.

Let me give you an example. The code below is an incorrect way to use ASI.
```js
let foo = 'bar'
[1, 2].map(e => e + 1)
```

because ASI will fix the code like this.
```js
let foo = 'bar'[1, 2].map(e => e + 1)
```

However, most of developer do not write code like this. In that code, we can't figure out what [1, 2] means. So we store it in a variable with name, that everyone can understand. 
```js
const ids = [1, 2]
const newIds = ids.map(e => e + 1)
```

I'm not blaming people for using semicolons in their code, but I don't think there's a particular reason for me to use semicolons. Please share your opinion :p
12 Coding Challenges Sites for Programmers
Tags: codenewbie, programming, challenge
Published: 2022-06-05 06:47:30

✅ CodeChef
✅ CodeFights
✅ CodeForces 
✅ CoderByte 
✅ Codewars
✅ CodinGame
✅ EdaBit 
✅ GeeksforGeeks
✅ HackerEarth 
✅ HackerRank 
✅ LeetCode
✅ TopCoder**
10 FREE Hosting Services for Your WordPress Site or Full Stack Project.
Published: 2022-06-05 06:39:52


✅ ByetHost
✅ Hostinger
✅ HyperPHP
✅ Freehostia
✅ Infinityfree
✅ 000webhost
✅ FreeHosting
✅ AwardSpace
✅ FreeWebHostingArea
✅ Google Cloud Hosting
NestJS: Modules
Tags: webdev, javascript, node, nestjs
Published: 2022-06-05 06:33:50

**Modules** are isolated parts of a NestJS application. Thanks to the modular system, you can easily expand the functionality of the application. Also, isolation makes it easier to debug code and keeps it cleaner. But, isolation can bring some difficulties.

In NestJS, you can create a module using the CLI

> nest g module products

A module is a class wrapped in @Module decorator which is imported from '@nestjs/common'. Many applications written in NestJS use many modules, but there must be at least one - the root module.

The @Module decorator passes certain metadata and takes an object with properties as an argument:

- **imports** - list of imported modules - using this property, you can create a convenient structure of modules in the application;
- **controllers** - a list of controllers that are used only in this module;
- **providers** — providers used in this module;
- **exports** - part of the providers used in this module, but which may be available in other parts of the application.

```
import { Module } from '@nestjs/common';

import { ProductsService } from './products.service';
import { ProductsController } from './products.controller';

@Module({
  controllers: [ProductsController],
  providers: [ProductsService],
})
export class ProductsModule {}
```

Every new module must be imported into the **root App module** in order for it to be available in the application.

```
// app.module.ts

import { Module } from '@nestjs/common';

import { ProductsModule } from './products/products.module';

@Module({
  imports: [ProductsModule ],
})
export class AppModule {}
```

Also, in NestJS it is possible to create a global module that can be used throughout the application. For this purpose, you need use the @Global decorator. This module must be registered once in the root module and can be used in all application.

```
import { Module, Global } from '@nestjs/common';

import { CommonService } from './common.service';
import { CommonController } from './common.controller';


@Global()
@Module({
  controllers: [CommonController],
  providers: [CommonService],
})
export class CommonModule {}
```

---

The main thing to understand is that **Modules** are parts of an application. Their purpose is to encapsulate and isolate these parts within themselves. For example, for the Product module, we can use ProductController and ProductService - they will include all the code related only to the Product module and will work with a specific entity. As for me, it would be convenient to create modules according to the entities from app's database.

Thanks for your time!
A small experiment with DoH in browser
Published: 2022-06-05 05:22:42

I wanted to explore some new uses cases for DoH (DNS over HTTPS). The criteria was simple, anything thats useful for at least one person (thats usually just me) so I was set for the success.

I work with startups, from naming product, implementation to marketing. So I decided to build a small tool to find available domain names directly from the browser. That is, without using registrar's slow and sluggish websites.

Using a DNS resolver for domain lookup is not a fool proof method since it will result in false positives if the registrar has misconfigured the domain or if the registry have the domain as not reservable. Either way I decided to give it a go.

I used Node.js, [WordNet data source](https://wordnet.princeton.edu/) for the dictionary and [Cloudflare open DNS](https://developers.cloudflare.com/1.1.1.1/) which is capable of DoH.

I will eventually open source the entire project (once cleaned up) but here is a quick snippet so you know how easy it is to do a lookup from your browser.


// Add doh.min.js
`https://cdn.jsdelivr.net/npm/dohjs@latest/dist/doh.min.js
`
// Using cloudflare open dns resolver
`const DNS = new doh.DohResolver('https://1.1.1.1/dns-query')
`
`DNS.query('KickSmart.app', 'A')
   .then(response => {
     const available = response.rcode == 'NXDOMAIN' ? true : false
     console.log('KickSmart.app is avaiable: '+available)
    })
    .catch(err => {
        console.error(err)
    })
    .finally(() => {
        console.log('Finished query!')
    })
`


Thats it!

Here I am using Cloudflare open DNS but you can use any available DNS resolver capable of DoH like [google open dns](https://developers.google.com/speed/public-dns/docs/doh) (used by Chrome) or your own DNS resolver.

As mentioned above, you will get some false positives time to time. But having the ability to privately and quickly search for domains made it worth.

The name of the project is [IDEA Ramen](https://idearamen.com/), it's a simple yet powerful domain name generator.

All feedback and questions are welcome!

----
The roadmap to learning JavaScript
Tags: javascript, webdev, codenewbie
Published: 2022-06-05 06:33:20


1. Print statement
2. Data types and variables
3. Basic operators
4. Logical operators
5. Comparisons
6. Loops and statements
7. alert() 
8. prompt()
9.  Arrays
10. Objects
11. Functions
12. Arrow function
13. Array methods
14. Hoisting
15. Closures
16. Callbacks
17. Promises
18. Async & Await
19. Currying
20. And other ES6 feature
The roadmap to learning CSS
Tags: css, web, webdev
Published: 2022-06-05 06:32:12

1. Inline, internal and external CSS
2. Selectors
3. Background
4. Color
5. Box model
6. Height and width
7. Margin and padding
8. Border
9. Positioning
10. display
11. Layouts
12. Grid and Flex
13. Alignment
14. Fonts
15. Animation
16. Pseudo-classes
17. Media query
Redundant Connection
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 06:30:45

In this problem, a tree is an **undirected graph** that is connected and has no cycles.

You are given a graph that started as a tree with `n` nodes labeled from `1` to `n`, with one additional edge added. The added edge has two **different** vertices chosen from `1` to `n`, and was not an edge that already existed. The graph is represented as an array `edges` of length `n` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the graph.

Return _an edge that can be removed so that the resulting graph is a tree of_ `n` _nodes_. If there are multiple answers, return the answer that occurs last in the input.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/05/02/reduntant1-1-graph.jpg)

**Input:** edges = \[\[1,2\],\[1,3\],\[2,3\]\]
**Output:** \[2,3\]

**Example 2:**

![](https://assets.leetcode.com/uploads/2021/05/02/reduntant1-2-graph.jpg)

**Input:** edges = \[\[1,2\],\[2,3\],\[3,4\],\[1,4\],\[1,5\]\]
**Output:** \[1,4\]

**Constraints:**

*   `n == edges.length`
*   `3 <= n <= 1000`
*   `edges[i].length == 2`
*   `1 <= ai < bi <= edges.length`
*   `ai != bi`
*   There are no repeated edges.
*   The given graph is connected.

**SOLUTION:**

    class Solution:
        def DFS(self, node, graph, visited, src, dest):
            visited.add(node)
            for i in graph.get(node, []):
                if i not in visited:
                    if (node, i) != (src, dest) and (i, node) != (dest, src):
                        self.DFS(i, graph, visited, src, dest)
        
        def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
            n = len(edges)
            graph = {}
            numnodes = 0
            for a, b in edges:
                numnodes = max(numnodes, a, b)
                graph[a] = graph.get(a, set()).union({b})
                graph[b] = graph.get(b, set()).union({a})
            for k in range(n - 1, -1, -1):
                a, b = edges[k]
                visited = set()
                self.DFS(a, graph, visited, a, b)
                if len(visited) == numnodes:
                    return edges[k]
Laravel 9 - Eloquent Date Methods
Tags: laravel, eloquent, php
Published: 2022-06-05 04:28:04

In Eloquent, you can use the date functions like: `whereDay()`, `whereMonth()`, `whereYear()`, `whereDate()` and `whereTime()`.

```
User::whereDate('created_at', '2022-05-31')->get();
User::whereMonth('created_at', '5')->get();
User::whereDay('created_at', '31')->get();
User::whereYear('created_at', date('Y'))->get();
User::whereTime('created_at', '=', '12:12:12')->get();
```
In 2022 | Ages
Published: 2022-06-05 06:26:20

⛳️HTML is 29 years old
⛳️ CSS is 26 years old
⛳️ JavaScript is 27 years old
⛳️ ReactJS is 9 years old
⛳️VueJs is 8 years old
⛳️ Angular is 6 years old
⛳️ Svelte is 6 years old
⛳️ VSCode is 7 years old
⛳️ Git is 17 years old
⛳️ Github is 14 years old

@ChakuTech

⛳️ C → 50 years old
⛳️ C++ → 37 years old
⛳️ Python → 31 years old
⛳️ PHP → 27 Years old
⛳️ Java → 26 years old
⛳️ C# → 22 years old
⛳️ Rust → 9 yrs old
⛳️ Go → 12 yrs old
⛳️ Ruby → 27 yrs old
⛳️ Rust → 11 yrs old
5 Most Popular Web Development Stacks
Published: 2022-06-05 06:20:36



⬇️ LAMP 
→Linux
→Apache
→MySQL
→PHP

⬇️ LEMP
→Linux
→Nginx
→MySQL
→PHP

⬇️ MERN 
→MongoDB
→Express
→React
→NodeJs

⬇️ MEVN
→MongoDB
→Express
→Vue
→NodeJs

⬇️ MEAN
→MongoDB
→Express
→Angular
→NodeJs
13 Sites To Get Free Illustrations for Web developers
Published: 2022-06-05 06:17:37


✅ drawkit. io
✅ undraw. co
✅ icons8. com
✅ iradesign. io
✅ blush .design
✅ storyset. com
✅ pixeltrue. com
✅ manypixels. co
✅ iconscout. com
✅ illustrations. co
✅ humaaans. com
✅ isometric .online
✅ openpeeps. com
Starting over again...
Tags: devjournal, writing, motivation
Published: 2022-06-05 06:04:52

I never had a blog before, thought it would be a perfect occasion for a first time. 

Even thought I don't know where it will get, my intension is to take a look back in a couple of years and see where I was when I decided to start over. 

A brief introduction would be very welcomed. 

My name is Andressa, 30yo, Brazilian. Decided to start a new career in tech when I was 27. Long story short, hated my career at the time and wanted to do something that could make me excited and proud. Existential crises? maybe 👀 

I got to college again, thought I could not make it, but I made it and I am going to my convocation ceremony in 10 days from now [Jun 15, 2022] 👩🏻‍🎓🥳

and why have I decided to name my first post here as "Starting over again"? 

Well, giving a brief overview... I got my first full-time development job in a big company. At that time, I could not even put in words how delightful I was. Could not be happier. I was so proud of myself! my family and I were celebrating all the time. I was literally thinking I could do everything, but I couldn't. Things were way different than what I was told, and from what I was expecting. 

I started to feel devastated. And here I want to emphasize that I was feeling terrible. I am still felling terrible. Was not on my plans to quit, but I decided to quit. I decided to quit because I knew I could do better. I always wanted to be productive and grow as a developer, and my decision was based on that. 

oh boy, I am starting again. Looking for a new full-time development job. Starting again to search companies I want to work for, starting again to write resumes and cover letters, starting again to wait for responses to positions I have applied for, starting again to have those moments of felling I am not good enough. That is scary AF, but _Andressa, you got this_. 

You had your downs, but you were always determined and always got where you decided to get. You are about to find a job you will love and a job you will proudly say "oh yeah, I work there! 😎". I trust you. Your family trusts you. We know everything is gonna be just fine.

Finally, I am starting this blog to document the process of reviewing coding concepts I find important to have well grounded, and also sharing my progress through this journey again.
Search a 2D Matrix
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 06:00:42

Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties:

*   Integers in each row are sorted from left to right.
*   The first integer of each row is greater than the last integer of the previous row.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/10/05/mat.jpg)

**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 3
**Output:** true

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg)

**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 13
**Output:** false

**Constraints:**

*   `m == matrix.length`
*   `n == matrix[i].length`
*   `1 <= m, n <= 100`
*   `-104 <= matrix[i][j], target <= 104`

**SOLUTION:**

    class Solution:
        def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
            m = len(matrix)
            n = len(matrix[0])
            beg = 0
            end = m * n - 1
            while beg <= end:
                mid = (beg + end) // 2
                i = mid // n
                j = mid % n
                if matrix[i][j] == target:
                    return True
                elif beg == end:
                    break
                elif matrix[i][j] < target:
                    beg = mid + 1
                else:
                    end = mid
            return False
Check If a String Contains All Binary Codes of Size K
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 05:30:38

Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`.

**Example 1:**

**Input:** s = "00110110", k = 2
**Output:** true
**Explanation:** The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.

**Example 2:**

**Input:** s = "0110", k = 1
**Output:** true
**Explanation:** The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring. 

**Example 3:**

**Input:** s = "0110", k = 2
**Output:** false
**Explanation:** The binary code "00" is of length 2 and does not exist in the array.

**Constraints:**

*   `1 <= s.length <= 5 * 105`
*   `s[i]` is either `'0'` or `'1'`.
*   `1 <= k <= 20`

**SOLUTION:**

    class Solution:
        def hasAllCodes(self, s: str, k: int) -> bool:
            n = len(s)
            codes = set()
            curr = int(s[0:k], 2)
            codes.add(curr)
            for i in range(n - k):
                curr = (curr << 1) - int(s[i]) * (1 << k) + int(s[i + k])
                codes.add(curr)
            return len(codes) == 1 << k
Subarray Sums Divisible by K
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 05:00:52

Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.

A **subarray** is a **contiguous** part of an array.

**Example 1:**

**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible by k = 5:
\[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\]

**Example 2:**

**Input:** nums = \[5\], k = 9
**Output:** 0

**Constraints:**

*   `1 <= nums.length <= 3 * 104`
*   `-104 <= nums[i] <= 104`
*   `2 <= k <= 104`

**SOLUTION:**

    from collections import defaultdict
    
    class Solution:
        def subarraysDivByK(self, nums: List[int], k: int) -> int:
            total = 0
            ctr = defaultdict(int)
            ctr[0] += 1
            for num in nums:
                total = (total + num) % k
                ctr[total] += 1
            return sum(n * (n - 1) // 2 for n in ctr.values())
What are you currently struggling with?
Tags: discuss, career
Published: 2022-06-05 04:47:01

This is super open ended, but what are you all currently struggling with? Doesn't have to be code related. We're more than our jobs.

I won't have answers to everything, probably lots of things, but others in the community might be able to help. 

![Leslie Knope from Parks and Recs asking "Can I help you?"](https://media.giphy.com/media/TbQRqDo63qD7TEffT3/giphy.gif)
Check If Word Is Valid After Substitutions
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 04:30:36

Given a string `s`, determine if it is **valid**.

A string `s` is **valid** if, starting with an empty string `t = ""`, you can **transform** `t` **into** `s` after performing the following operation **any number of times**:

*   Insert string `"abc"` into any position in `t`. More formally, `t` becomes `tleft + "abc" + tright`, where `t == tleft + tright`. Note that `tleft` and `tright` may be **empty**.

Return `true` _if_ `s` _is a **valid** string, otherwise, return_ `false`.

**Example 1:**

**Input:** s = "aabcbc"
**Output:** true
**Explanation:**
"" -> "abc" -> "aabcbc"
Thus, "aabcbc" is valid.

**Example 2:**

**Input:** s = "abcabcababcc"
**Output:** true
**Explanation:**
"" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc"
Thus, "abcabcababcc" is valid.

**Example 3:**

**Input:** s = "abccba"
**Output:** false
**Explanation:** It is impossible to get "abccba" using the operation.

**Constraints:**

*   `1 <= s.length <= 2 * 104`
*   `s` consists of letters `'a'`, `'b'`, and `'c'`

**SOLUTION:**

    class Solution:
        def isValid(self, s: str) -> bool:
            while "abc" in s:
                i = s.index("abc")
                s = s[:i] + s[i+3:]
            return s == ""
Create Binary Tree From Descriptions
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 04:00:42

You are given a 2D integer array `descriptions` where `descriptions[i] = [parenti, childi, isLefti]` indicates that `parenti` is the **parent** of `childi` in a **binary** tree of **unique** values. Furthermore,

*   If `isLefti == 1`, then `childi` is the left child of `parenti`.
*   If `isLefti == 0`, then `childi` is the right child of `parenti`.

Construct the binary tree described by `descriptions` and return _its **root**_.

The test cases will be generated such that the binary tree is **valid**.

**Example 1:**

![](https://assets.leetcode.com/uploads/2022/02/09/example1drawio.png)

**Input:** descriptions = \[\[20,15,1\],\[20,17,0\],\[50,20,1\],\[50,80,0\],\[80,19,1\]\]
**Output:** \[50,20,80,15,17,19\]
**Explanation:** The root node is the node with value 50 since it has no parent.
The resulting binary tree is shown in the diagram.

**Example 2:**

![](https://assets.leetcode.com/uploads/2022/02/09/example2drawio.png)

**Input:** descriptions = \[\[1,2,1\],\[2,3,0\],\[3,4,1\]\]
**Output:** \[1,2,null,null,3,4\]
**Explanation:** The root node is the node with value 1 since it has no parent.
The resulting binary tree is shown in the diagram.

**Constraints:**

*   `1 <= descriptions.length <= 104`
*   `descriptions[i].length == 3`
*   `1 <= parenti, childi <= 105`
*   `0 <= isLefti <= 1`
*   The binary tree described by `descriptions` is valid.

**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 makeTree(self, tree, node):
            root = None
            if node:
                root = TreeNode(val = node)
                if node in tree:
                    root.left = self.makeTree(tree, tree[node][0])
                    root.right = self.makeTree(tree, tree[node][1])
            return root
        
        def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:
            roots = set(d[0] for d in descriptions)
            tree = {}
            for p, c, left in descriptions:
                if p not in tree:
                    tree[p] = [None, None]
                if left:
                    tree[p][0] = c
                else:
                    tree[p][1] = c
                if c in roots:
                    roots.remove(c)
            root = list(roots)[0]
            return self.makeTree(tree, root)