teleren/devto huggingface dataset:
Champagne Tower
Tags: leetcode, dsa, theabbie
Published: 2022-06-04 04:30:42

We stack glasses in a pyramid, where the **first** row has `1` glass, the **second** row has `2` glasses, and so on until the 100th row.  Each glass holds one cup of champagne.

Then, some champagne is poured into the first glass at the top.  When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has its excess champagne fall on the floor.)

For example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.

![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/03/09/tower.png)

Now after pouring some non-negative integer cups of champagne, return how full the `jth` glass in the `ith` row is (both `i` and `j` are 0-indexed.)

**Example 1:**

**Input:** poured = 1, query\_row = 1, query\_glass = 1
**Output:** 0.00000
**Explanation:** We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.

**Example 2:**

**Input:** poured = 2, query\_row = 1, query\_glass = 1
**Output:** 0.50000
**Explanation:** We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.

**Example 3:**

**Input:** poured = 100000009, query\_row = 33, query\_glass = 17
**Output:** 1.00000

**Constraints:**

*   `0 <= poured <= 109`
*   `0 <= query_glass <= query_row < 100`

**SOLUTION:**

    class Solution:
        def getRowState(self, poured, query_row):
            if query_row == 0:
                return [poured]
            prev = self.getRowState(poured, query_row - 1)
            curr = [0] * (query_row + 1)
            for i in range(query_row):
                if prev[i] > 1:
                    extra = (prev[i] - 1) / 2
                    curr[i] += extra
                    curr[i + 1] += extra
            return curr
        
        def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
            state = self.getRowState(poured, query_row)
            return min(state[query_glass], 1)
Explain this code
Published: 2022-06-04 04:18:35



	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String[] suits = {"hearts","Diamonds","Clubs","Spades"};
		
		List<String> list = Arrays.asList(suits);
		
		System.out.printf("Unsorted array element : %s%n",list);
		
		Collections.sort(list,Collections.reverseOrder());
		System.out.printf("Sorted lest element : %s%n",list);
	}

}
React Bricks | Made with React JS
Published: 2022-06-04 04:07:32

![React Bricks | Made with Javascript | React JS](https://res.cloudinary.com/madewithjavascript/image/upload/v1653508532/large_react_bricks_made_with_react_js_9dd0c68593.png "React Bricks | Made with Javascript | React JS")


### React CMS with Visual editing for Next.js, Gatsby, Remix

> React Bricks is a CMS with the best Visual editing experience for Content editors, but great for Developers too, as content blocks are React components defined in code. Easy as Wix for editors, but with your pixel-perfect design and no way to break it.

## 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 | [React Bricks on Twitter](https://twitter.com/withjavascript/status/1532935507788840966?s=20&t=e1Jgsr0u0Dm2lJ_T8vcQcA)
 |
| Medium | [React Bricks on Medium](https://medium.com/@madewithjavascript/react-bricks-made-with-react-js-98123d8629b0)
 |
| Facebook | [React Bricks on Facebook](facebook.com/madewithjavascript/posts/pfbid02TBCG1uhK6QZvvFmyeuydmK4VywHKXj5zAytGmXeYY217og4dKEJ4T4m4YVKNQth1l)
 |
| Tumblr | [React Bricks on Tumblr](https://www.tumblr.com/blog/view/madewithjavascript/686099405272645632?source=share)
 |
| LinkedIn | [React Bricks on LinkedIn](https://www.linkedin.com/feed/update/urn:li:activity:6938701737499230208)
 |
| Pinterest | [React Bricks on Pinterest](https://pin.it/1IfuRQ0)
 |


Filled Under:
 - [Made with Javascript](https://madewithjavascript.club)    
 - [Made with React JS](https://madewithjavascript.club/categories/react-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!
Random Pick Index
Tags: leetcode, dsa, theabbie
Published: 2022-06-04 04:00:43

Given an integer array `nums` with possible **duplicates**, randomly output the index of a given `target` number. You can assume that the given target number must exist in the array.

Implement the `Solution` class:

*   `Solution(int[] nums)` Initializes the object with the array `nums`.
*   `int pick(int target)` Picks a random index `i` from `nums` where `nums[i] == target`. If there are multiple valid i's, then each index should have an equal probability of returning.

**Example 1:**

**Input**
\["Solution", "pick", "pick", "pick"\]
\[\[\[1, 2, 3, 3, 3\]\], \[3\], \[1\], \[3\]\]
**Output**
\[null, 4, 0, 2\]

**Explanation**
Solution solution = new Solution(\[1, 2, 3, 3, 3\]);
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(1); // It should return 0. Since in the array only nums\[0\] is equal to 1.
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.

**Constraints:**

*   `1 <= nums.length <= 2 * 104`
*   `-231 <= nums[i] <= 231 - 1`
*   `target` is an integer from `nums`.
*   At most `104` calls will be made to `pick`.

**SOLUTION:**

    import random
    
    class Solution:
    
        def __init__(self, nums: List[int]):
            self.valIndex = {}
            for i, num in enumerate(nums):
                self.valIndex[num] = self.valIndex.get(num, []) + [i]
    
        def pick(self, target: int) -> int:
            return random.choice(self.valIndex[target])
    
    
    # Your Solution object will be instantiated and called as such:
    # obj = Solution(nums)
    # param_1 = obj.pick(target)
Check if Number is a Sum of Powers of Three
Tags: leetcode, dsa, theabbie
Published: 2022-06-04 03:30:36

Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`.

An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`.

**Example 1:**

**Input:** n = 12
**Output:** true
**Explanation:** 12 = 31 + 32

**Example 2:**

**Input:** n = 91
**Output:** true
**Explanation:** 91 = 30 + 32 + 34

**Example 3:**

**Input:** n = 21
**Output:** false

**Constraints:**

*   `1 <= n <= 107`

**SOLUTION:**

    class Solution:
        def checkPowersOfThree(self, n: int) -> bool:
            while n != 1:
                if n % 3 == 0:
                    n = n // 3
                elif n % 3 == 1:
                    n = (n - 1) // 3
                else:
                    break
            return n == 1
Generate Random Point in a Circle
Tags: leetcode, dsa, theabbie
Published: 2022-06-04 03:00:46

Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle.

Implement the `Solution` class:

*   `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and the position of the center `(x_center, y_center)`.
*   `randPoint()` returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array `[x, y]`.

**Example 1:**

**Input**
\["Solution", "randPoint", "randPoint", "randPoint"\]
\[\[1.0, 0.0, 0.0\], \[\], \[\], \[\]\]
**Output**
\[null, \[-0.02493, -0.38077\], \[0.82314, 0.38945\], \[0.36572, 0.17248\]\]

**Explanation**
Solution solution = new Solution(1.0, 0.0, 0.0);
solution.randPoint(); // return \[-0.02493, -0.38077\]
solution.randPoint(); // return \[0.82314, 0.38945\]
solution.randPoint(); // return \[0.36572, 0.17248\]

**Constraints:**

*   `0 < radius <= 108`
*   `-107 <= x_center, y_center <= 107`
*   At most `3 * 104` calls will be made to `randPoint`.

**SOLUTION:**

    import random
    import math
    
    class Solution:
    
        def __init__(self, radius: float, x_center: float, y_center: float):
            self.r = radius
            self.cx = x_center
            self.cy = y_center
    
        def randPoint(self) -> List[float]:
            randRadius = self.r * math.sqrt(random.random())
            randAngle = 2 * math.pi * random.random()
            x = self.cx + randRadius * math.cos(randAngle)
            y = self.cy + randRadius * math.sin(randAngle)
            return [x, y]
    
    # Your Solution object will be instantiated and called as such:
    # obj = Solution(radius, x_center, y_center)
    # param_1 = obj.randPoint()
Validate Now. Build Later.
Tags: startup, productivity, sideprojects
Published: 2022-06-04 03:00:11

I’m an engineer working on a side project that I’ve not even started building yet. And here’s why:

With all the projects I’ve taken on personally in the past, my immediate response is to build a working MVP and make sure it’s usable for my needs. And now I see why those projects never lift off the ground: I’ve solved my need and moved on.

What if I started building an audience first? What if I started understanding other potential users’ needs before I build something and assume that’s what everyone else will need?

These are the questions I’ve been asking myself as I’m going down the path of yet another idea. And it’s working so far! I’m picking up traction by asking for feedback on Reddit, paying for a few ads on Google, and sharing my story on LinkedIn.

So what have I built? Almost nothing so far in terms of code - just a small prototype to verify I _can_ build this. But what I am building is a waitlist: an audience. I even went so far as to not code the landing page! Mad props to Carrd for that 🤓

All that said, I’m not sure how this is going to turn out, but I’m giving it a shot! Next up is figuring out how long to wait before building. My goal is to hit 50 waitlist subscribers this month and take it from there 🤞

---

And if you’re curious, I’m building a meeting plugin to easily take notes, create action items, view your day’s schedules, and sync all those pieces in your normal work apps - all without minimizing your video call!

You can check it out and sign up at: [Enhancemeet.com](https://enhancemeet.com)!
react firebase crud realtime database
Published: 2022-06-04 02:53:32

https://firebase.google.com/docs/database/web/start?authuser=0
https://youtu.be/azdwN_4IDKA
https://create-react-app.dev/docs/adding-bootstrap/#using-a-custom-theme

## terminal
```
npx create-react-app xxx-app-name
cd xxx-app-name
code .
```

## vscode

```
npm i firebase
npm i uid
```

## firebase
new web app
SDK setup and configuration

## vscode
`firebase.js`

```
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";

const firebaseConfig{
apiKey: "your api key";
authDomain: "your authDomain";
databaseURL: "your dbURL";
projectId: "your projectId";
storageBucket: "your storageBucket";
messagingSenderId: "your messagingSenderId";
appId: "your appId";
};

const app = initializeApp(firebaseConfig);
export const db = getDatabase(app);
```

## firebase > realtime database
`rules`
```
{
  "rules": {
    ".read": true,
    ".write": true
  }
}
```

## vscode
`App.js`
text input

```
import { db } from "./firebase" 
//firebase.js
import { uid } from "uid"

function App(){

return(
<div>
<input type="text" />
<button>submit</button>
</div>)
}

```
write
```
  const writeToDatabase = () => {
    const uuid = uid();
    set(ref(db, `/${uuid)`}, {
      todo,
      uuid,
    });
  };
```
Queries on Number of Points Inside a Circle
Tags: leetcode, dsa, theabbie
Published: 2022-06-04 02:30:39

You are given an array `points` where `points[i] = [xi, yi]` is the coordinates of the `ith` point on a 2D plane. Multiple points can have the **same** coordinates.

You are also given an array `queries` where `queries[j] = [xj, yj, rj]` describes a circle centered at `(xj, yj)` with a radius of `rj`.

For each query `queries[j]`, compute the number of points **inside** the `jth` circle. Points **on the border** of the circle are considered **inside**.

Return _an array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query_.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/03/25/chrome_2021-03-25_22-34-16.png)

**Input:** points = \[\[1,3\],\[3,3\],\[5,3\],\[2,2\]\], queries = \[\[2,3,1\],\[4,3,1\],\[1,1,2\]\]
**Output:** \[3,2,2\]
**Explanation:** The points and circles are shown above.
queries\[0\] is the green circle, queries\[1\] is the red circle, and queries\[2\] is the blue circle.

**Example 2:**

![](https://assets.leetcode.com/uploads/2021/03/25/chrome_2021-03-25_22-42-07.png)

**Input:** points = \[\[1,1\],\[2,2\],\[3,3\],\[4,4\],\[5,5\]\], queries = \[\[1,2,2\],\[2,2,2\],\[4,3,2\],\[4,3,3\]\]
**Output:** \[2,3,2,4\]
**Explanation:** The points and circles are shown above.
queries\[0\] is green, queries\[1\] is red, queries\[2\] is blue, and queries\[3\] is purple.

**Constraints:**

*   `1 <= points.length <= 500`
*   `points[i].length == 2`
*   `0 <= x​​​​​​i, y​​​​​​i <= 500`
*   `1 <= queries.length <= 500`
*   `queries[j].length == 3`
*   `0 <= xj, yj <= 500`
*   `1 <= rj <= 500`
*   All coordinates are integers.

**Follow up:** Could you find the answer for each query in better complexity than `O(n)`?

**SOLUTION:**

    class Solution:
        def countPoints(self, points: List[List[int]], queries: List[List[int]]) -> List[int]:
            answer = []
            for x, y, r in queries:
                numPoints = 0
                for cx, cy in points:
                    if (cx - x) ** 2 + (cy - y) ** 2 <= r ** 2:
                        numPoints += 1
                answer.append(numPoints)
            return answer
Number of Laser Beams in a Bank
Tags: leetcode, dsa, theabbie
Published: 2022-06-04 01:30:35

Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a security device.

There is **one** laser beam between any **two** security devices **if both** conditions are met:

*   The two devices are located on two **different rows**: `r1` and `r2`, where `r1 < r2`.
*   For **each** row `i` where `r1 < i < r2`, there are **no security devices** in the `ith` row.

Laser beams are independent, i.e., one beam does not interfere nor join with another.

Return _the total number of laser beams in the bank_.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/12/24/laser1.jpg)

**Input:** bank = \["011001","000000","010100","001000"\]
**Output:** 8
**Explanation:** Between each of the following device pairs, there is one beam. In total, there are 8 beams:
 \* bank\[0\]\[1\] -- bank\[2\]\[1\]
 \* bank\[0\]\[1\] -- bank\[2\]\[3\]
 \* bank\[0\]\[2\] -- bank\[2\]\[1\]
 \* bank\[0\]\[2\] -- bank\[2\]\[3\]
 \* bank\[0\]\[5\] -- bank\[2\]\[1\]
 \* bank\[0\]\[5\] -- bank\[2\]\[3\]
 \* bank\[2\]\[1\] -- bank\[3\]\[2\]
 \* bank\[2\]\[3\] -- bank\[3\]\[2\]
Note that there is no beam between any device on the 0th row with any on the 3rd row.
This is because the 2nd row contains security devices, which breaks the second condition.

**Example 2:**

![](https://assets.leetcode.com/uploads/2021/12/24/laser2.jpg)

**Input:** bank = \["000","111","000"\]
**Output:** 0
**Explanation:** There does not exist two devices located on two different rows.

**Constraints:**

*   `m == bank.length`
*   `n == bank[i].length`
*   `1 <= m, n <= 500`
*   `bank[i][j]` is either `'0'` or `'1'`.

**SOLUTION:**

    class Solution:
        def numberOfBeams(self, bank: List[str]) -> int:
            bank = [b.count("1") for b in bank if b.count("1") != 0]
            val = 0
            n = len(bank)
            for i in range(n - 1):
                val += bank[i] * bank[i + 1]
            return val
Shortest Unsorted Continuous Subarray
Tags: leetcode, dsa, theabbie
Published: 2022-06-04 01:00:43

Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.

Return _the shortest such subarray and output its length_.

**Example 1:**

**Input:** nums = \[2,6,4,8,10,9,15\]
**Output:** 5
**Explanation:** You need to sort \[6, 4, 8, 10, 9\] in ascending order to make the whole array sorted in ascending order.

**Example 2:**

**Input:** nums = \[1,2,3,4\]
**Output:** 0

**Example 3:**

**Input:** nums = \[1\]
**Output:** 0

**Constraints:**

*   `1 <= nums.length <= 104`
*   `-105 <= nums[i] <= 105`

**Follow up:** Can you solve it in `O(n)` time complexity?**SOLUTION:**

    class Solution:
        def findUnsortedSubarray(self, nums: List[int]) -> int:
            n = len(nums)
            i = float('inf')
            j = float('-inf')
            sortednums = sorted(nums)
            for x in range(n):
                if sortednums[x] != nums[x]:
                    i = min(i, x)
                    j = max(j, x)
            return max(j - i + 1, 0)
Collaborating with team mates!
Tags: programming, productivity, github, database
Published: 2022-06-04 00:46:05

I start a project, I have a vision for it. I work with teams because I enjoy maximizing the synergy that comes from individuals from different backgrounds. When assembling my teams, I give people chances, I give everyone the benefit of the doubt. 
#easynessmall
#ecommerce 
#CTO
Maximum Candies Allocated to K Children
Tags: leetcode, dsa, theabbie
Published: 2022-06-04 00:30:37

You are given a **0-indexed** integer array `candies`. Each element in the array denotes a pile of candies of size `candies[i]`. You can divide each pile into any number of **sub piles**, but you **cannot** merge two piles together.

You are also given an integer `k`. You should allocate piles of candies to `k` children such that each child gets the **same** number of candies. Each child can take **at most one** pile of candies and some piles of candies may go unused.

Return _the **maximum number of candies** each child can get._

**Example 1:**

**Input:** candies = \[5,8,6\], k = 3
**Output:** 5
**Explanation:** We can divide candies\[1\] into 2 piles of size 5 and 3, and candies\[2\] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.

**Example 2:**

**Input:** candies = \[2,5\], k = 11
**Output:** 0
**Explanation:** There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.

**Constraints:**

*   `1 <= candies.length <= 105`
*   `1 <= candies[i] <= 107`
*   `1 <= k <= 1012`

**SOLUTION:**

    class Solution:
        def numChild(self, candies, candy):
            k = 0
            for pile in candies:
                k += int(pile / candy)
            return k
        
        def maximumCandies(self, candies: List[int], k: int) -> int:
            beg = 1
            end = max(candies)
            while beg <= end:
                mid = (beg + end) // 2
                val = self.numChild(candies, mid)
                nextval = self.numChild(candies, mid + 1)
                if val >= k and nextval < k:
                    return mid
                elif beg == end:
                    break
                elif val < k:
                    end = mid
                else:
                    beg = mid + 1
            return 0
Protect Passwords in Cloud
Tags: terraform, devops, aws, security
Published: 2022-06-04 00:11:24

## [Protect Passwords in Cloud](https://www.bitslovers.com/protect-passwords-in-cloud-full-project-review/)

Let's go through a real project where we need to remove hardcoded passwords from several applications and make them more secure in the Cloud.

Some topics from this article: [Protect Passwords in Cloud](https://www.bitslovers.com/protect-passwords-in-cloud-full-project-review/)

- How to protect passwords for your application
- How to build a scalable solution in the Cloud.
- AWS Secret Manager
- Terraform Module for Secret Manager
- Build a Pipeline that deploys all Secrets for us and protects them at the same time.
- How to use OpenSSL to project our secrets file in our Git Repository.


Enjoy the reading!
Lowest Common Ancestor of a Binary Search Tree
Tags: leetcode, dsa, theabbie
Published: 2022-06-04 00:00:46

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): “The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**).”

**Example 1:**

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

**Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 8
**Output:** 6
**Explanation:** The LCA of nodes 2 and 8 is 6.

**Example 2:**

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

**Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 4
**Output:** 2
**Explanation:** The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

**Example 3:**

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

**Constraints:**

*   The number of nodes in the tree is in the range `[2, 105]`.
*   `-109 <= Node.val <= 109`
*   All `Node.val` are **unique**.
*   `p != q`
*   `p` and `q` will exist in the BST.

**SOLUTION:**

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
            if root:
                if (p.val <= root.val and q.val >= root.val) or (p.val >= root.val and q.val <= root.val):
                    return root
                if p.val < root.val and q.val < root.val:
                    return self.lowestCommonAncestor(root.left, p, q)
                if p.val > root.val and q.val > root.val:
                    return self.lowestCommonAncestor(root.right, p, q)