teleren/devto huggingface dataset:
YARN Cheatsheet
Tags: yarn
Published: 2022-07-16 05:14:10

**Install via npm**

```jsx
npm install --global yarn
```

**Check installation**

```jsx
yarn --version
```

**Starting a new project**

```jsx
yarn init
```

**Adding a dependency**

```
yarn add [package]
yarn add [package]@[version]
yarn add [package]@[tag]
```

**Adding a dependency to different categories of dependencies**

Add to `devDependencies`, `peerDependencies`, and `optionalDependencies` respectively:

```jsx
yarn add [package] --dev
yarn add [package] --peer
yarn add [package] --optional
```

**Upgrading a dependency**

```jsx
yarn upgrade [package]
yarn upgrade [package]@[version]
yarn upgrade [package]@[tag]
```

**Removing a dependency**

```jsx
yarn remove [package]
```

**Installing all the dependencies of project**

```jsx
yarn

or

yarn install
```
2332. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-16 05:10:58

```
class Solution {
public:
    int latestTimeCatchTheBus(vector<int>& buses, vector<int>& passengers, int capacity) {
        int i = 0;
        sort(buses.begin(), buses.end());
        sort(passengers.begin(), passengers.end());
        int ans = min(passengers[0] - 1, buses[buses.size() - 1]), idx = 0;
        for(i = 0; i < buses.size() && idx < passengers.size(); i++){
            int cap = capacity;
            while(cap && idx < passengers.size() && passengers[idx] <= buses[i]){
                if(idx != 0){
                    if(passengers[idx] - passengers[idx - 1] > 1) ans = passengers[idx] - 1;
                }
                cap -= 1;
                idx += 1;
            }
            if(cap != 0){
                if(idx > 0 && buses[i] != passengers[idx - 1]) ans = buses[i];
            }
        }
        if(i != buses.size()) ans = buses[buses.size() - 1];
        return ans;
    }
};
```
#leetcode
#weekly contest
Here is the link for the problem.....
https://leetcode.com/contest/biweekly-contest-82/problems/the-latest-time-to-catch-a-bus/
2331. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-16 05:08:21

```
class Solution {
public:
    bool solve(TreeNode* root) {
          if(root->left == NULL && root->right == NULL) return root->val;
          bool left, right;
          left = solve(root->left);
          right = solve(root->right);
          if(root->val == 2) return left | right;
          return left & right;
    }
    bool evaluateTree(TreeNode* root) {
        if(root->left == NULL && root->right == NULL) return root->val;
          return solve(root);
    }
};
```

#leetcode
#weekly contest
Here is the link for the problem.....
https://leetcode.com/contest/biweekly-contest-82/problems/evaluate-boolean-binary-tree/
173. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-16 05:05:50

```
class BSTIterator {
 public:
  BSTIterator(TreeNode* root) {
    inorder(root);
  }

  /** @return the next smallest number */
  int next() {
    return vals[i++];
  }

  /** @return whether we have a next smallest number */
  bool hasNext() {
    return i < vals.size();
  }

 private:
  int i = 0;
  vector<int> vals;

  void inorder(TreeNode* root) {
    if (!root)
      return;

    inorder(root->left);
    vals.push_back(root->val);
    inorder(root->right);
  }
};

```

#leetcode
#challenge
Here is the link for the problem.....
https://leetcode.com/problems/binary-search-tree-iterator/
230. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-16 05:04:46

```
class Solution {
 public:
  int kthSmallest(TreeNode* root, int k) {
    const int leftCount = countNodes(root->left);

    if (leftCount == k - 1)
      return root->val;
    if (leftCount >= k)
      return kthSmallest(root->left, k);
    return kthSmallest(root->right, k - 1 - leftCount);  // leftCount < k
  }

 private:
  int countNodes(TreeNode* root) {
    if (!root)
      return 0;
    return 1 + countNodes(root->left) + countNodes(root->right);
  }
};

```
#leetcode
#challenge
Here is the link for the problem.....
https://leetcode.com/problems/kth-smallest-element-in-a-bst/
108. Leetcode Solution in Java
Tags: java
Published: 2022-07-16 05:03:37

```
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums == null || nums.length == 0) return null;
        return createTree(nums, 0, nums.length - 1);
    }
    private TreeNode createTree(int[] nums, int start, int end){
        if(start > end) return null;
        int mid = start + (end - start) / 2;
        TreeNode node = new TreeNode(nums[mid]);
        node.left = createTree(nums, start, mid - 1);
        node.right = createTree(nums, mid + 1, end);
        return node;
    }
}
```
#leetcode
#challenge
Here is the link for the problem.....
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
How to serve media files on Django production environment?
Tags: django, python, tutorial, nginx
Published: 2022-07-16 05:00:37

I repeat this is not an absolute solution or recommended solution for a large-scale web app. It's just for personal project or low traffic web application. 

For high traffic web applications, recommended solution use cloud services like amazon s3 bucket etc for serving media file.

OK! I assume that you know about little bit about nginx. If want to know all about nginx configuration let me know in comment.

Go to your nginx domain file configuration - 
```bash
sudo nano /etc/nginx/sites-available/<your domain file configuration>
```

```bash 
location /static/ {
        #############
    }
location /media/ {
        root #path of your project directory where your media folder exist- example: /home/sium/nmedia_backend/nMedia;
    }
```
And then save this file and check is there any error in nginx config file by `sudo nginx -t` and then restart nginx service by `sudo systemctl restart nginx`

Voila! your media file will serve via nginx. Because `DEBUG=FALSE` mode means in production mode django won't serve your media file by itself.
How to consolidate cleanup logic using the "with" function pattern
Published: 2022-07-16 04:19:00

A few of my teammates have liked the "with" function pattern and how convenient it is for ensuring proper cleanup of resources.

A "with" function takes a callback and performs some initialization, calls the callback, then performs some cleanup.

For example, instead of manually doing a `COMMIT` or `ROLLBACK` for every SQL transaction like this:

```go
tx, err := db.Begin()
if err != nil {
	return err
}

err = tx.Exec("INSERT ...")
if err != nil {
	// 💥 Oops, forgot tx.Rollback(), tx remains open!
	return err
}

// execute more statements...

err = tx.Commit()
if err != nil {
	return err
}
```

We can create a `withTx()` function:

```go
func withTx(db DB, callback func(Tx) error) error {
	tx, err := db.Begin()
	if err != nil {
		return err
	}
 	defer tx.Rollback()

	err = callback(tx)
	if err != nil {
		return err
	}

	return tx.Commit()	
}
```

And use it like this:

```go
err := withTx(db, func(tx Tx) error {
	err = tx.Exec("INSERT ...")
	if err != nil {
		// 🙂 No need to remember to call tx.Rollback()
		return err
	}
	// execute more statements...
})
if err != nil {
	return err
}
```

At a glance, ~5% of [calls](https://sourcegraph.com/search?q=context:global+mattn/go-sqlite3+AND+Begin+NOT+Rollback+lang:go&patternType=literal) to `Begin()` appear to be missing a corresponding `Rollback()` on error ([likely example](https://github.com/owncast/owncast/blob/fb3973b264d82aad7e0ae3086255d72506a38c41/core/data/persistence.go#L86)). Using a `withTx()` function would help eliminate those bugs.

And with Go generics we can return a value from `withTx`:

```diff
-func withTx(db DB, callback func(Tx) error) error {
+func withTx[T any](db DB, callback func(Tx) (*T, error)) (*T, error) {
 	tx, err := db.Begin()
 	if err != nil {
-		return err
+		return nil, err
 	}
 	defer tx.Rollback()

-	err = callback(tx)
+	t, err := callback(tx)
 	if err != nil {
 	 	return err
 	}

-	return tx.Commit()
+	return t, tx.Commit()
 }
```

Benefits of the "with" function pattern:

- Automatic initialization and cleanup
- Less code
- In some cases, there's no need to check if the operation succeeded and do something different if it didn't

One caveat to bear in mind: you have to make sure the callback does not return the resource, otherwise that resource could be used after the clean up runs and cause an error! I don't think it's possible to enforce correct use at compile time in Go. It is possible (but not ergonomic) in [Haskell](https://www.snoyman.com/blog/2018/10/raii-better-than-bracket-pattern/) and it's convenient in [Rust](https://www.snoyman.com/blog/2018/10/raii-better-than-bracket-pattern/#rust) by piggy-backing on the built-in value lifetime machinery.
576. Leetcode Solution in Java
Tags: java
Published: 2022-07-16 04:55:24

```
class Solution {
    private static final int[][] dir = new int[][]{{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
    public int findPaths(int m, int n, int N, int i, int j) {
        int[][][] dp = new int[N + 1][m][n];
        for(int k = 1; k <= N; k++){
            for(int r = 0; r < m; r++){
                for(int c = 0; c < n; c++){
                    // (r, c) means the current position of a node.
                    int tempRow = 0, tempCol = 0;
                    for(int d = 0; d < 4; d++){
                        // (tempRow, tempCol) means the next posible position
                        tempRow = r + dir[d][0];
                        tempCol = c + dir[d][1];
                        if(tempRow < 0 || tempRow >= m || tempCol < 0 || tempCol >= n){
                            // if next position is out of boundary, current index add 1.
                            dp[k][r][c] += 1;
                        }else{
                            // if next position is within the boundary, we add that ways to current one.
                            dp[k][r][c] = (dp[k][r][c] + dp[k - 1][tempRow][tempCol]) % 1000000007;
                        }
                    }
                }
            }
        }
        return dp[N][i][j];
    }
}
```

#leetcode
#challenge
Here is the link for the problem.....
https://leetcode.com/problems/out-of-boundary-paths/
Using Laravel Controllers, Events, Listeners, Services and Validation Together!
Tags: laravel, php, webdev, programming
Published: 2022-07-16 04:20:03

We can put all codes of a web application into controllers but this action sounds crazy and it’s quite not right to do!

In this article we will see how to structure a web-app with a well-known pattern. I must say you can do below examples in other different ways and probably all of them will be right, So this article is just some examples for doing things!

Let me explain the scenario:

Imagine we have a simple medium-app and it will have a Content section which a user can share a blog post and his/her followers will notice when a new article published!

### 1. Ugly Way

Make a `ArticleController` and put all codes in it, like below:

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


### 2. Better Way

First, we should replace Request $request an `ArticleStoreRequest $request` to validate data in a better way:

`php artisan make:request ArticleStoreRequest`

Don’t forget to return true in `authorize()` method, so user can do this action:

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

Second, we should make the `ArticleService` to move creation logic from controller to service. Because the only thing that a controller will do is passing data!

So we will make `ArticleService` in Services folder and write creation code to a simple related method and by considering Single Responsibility Principle move upload image to it’s method like below:

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

Let’s have another look at our `ArticleController` again see what have been changed so far:


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

 * Now let’s use Event and Listener for sending emails to followers of article writer:

```
php artisan make:event ArticlePublishedEventphp artisan make:listener ArticlePublishedListener --event=ArticlePublishedEvent
```

This philosophy help us to devide operations and the event will fire automatically when ever and where ever we want. Also this will pretend us to repeat ourselves!

The event class should accept the User model and Article model, which is then passed to ANY listener of that event:

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

Then, the Event is fired from the Controller, like this:


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

And, in the Listener class, we repeat the same logic:


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

That’s it…
Latest web trends
Tags: programming, language
Published: 2022-07-16 02:34:15

Follow Latest Web Trends

1. Core Web Vital 
  -Loading [LCP] 
  -Interactivity. [ FID]
  - visal stability [CLS]
2. Figma & Invision app 
3. Static Site Generator [Gatsby js] 
4. Design System not systems design
5. svg animations
  -Svgator 
  -velocity.js
  -GSAP
6. HTML Bilaterplate
Create a react app with bun
Tags: react, bunjs, webdev, javascript
Published: 2022-07-16 02:11:25

## Want to use bun for your next react projects?

---

### Install `bun`

First run the following command to check `bun` is installed or not

```sh
bun -v
```

If you don't have `bun` installed then run the following command to install `bun`

```sh
curl https://bun.sh/install | bash
```

### Create a react app

Now run the following command to create a react app

```sh
bun create react [your-app-name]
```

It will create a new directory with the name of your app. To start the app run the following command

```sh
cd your-app-name
bun dev
```

### Build production bundle for react app

By default `bun` does not ship with `react-scripts` so you need to install it first.

```sh
bun a react-scripts -d
```

Here we install it as a dev dependency.

Then run the following command to build the production bundle

```sh
bun react-scripts build
```

When you run the command above it will build the production bundle and it will be stored in the `build` directory.

### Adding `scripts` to your package.json

We can add the following scripts to our package.json file

```json
{
  "scripts": {
    "start": "bun dev",
    "build": "react-scripts build"
  }
}
```

Now we can run the following command to start the app

```sh
bun start
```

And we can run the following command to build the production bundle

```sh
bun run build
```

### Bonus:

> By default `bun` creates react app with javascript but we can easily use typescript by changing the file extension from `.jsx` to `.tsx`

### [Get Full Source Code In GitHub](https://github.com/AshirbadGudu/bun-react-app)
CSSBattle | #26 Smiley
Tags: css, challenge, cssbattle, smiley
Published: 2022-07-16 01:53:45

Welcome to CSSBattle Challenges!

In this short article, I go through my solution for [CSSBattle - #26 Smiley](https://cssbattle.dev/play/26) challenge. Please refer to the code snippet below to get a better insight into my thought processes and the implementation detail.

---

> #### Challenge:

![Smiley Challenge](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ank90hs2cywlwehes01f.png)

---

> #### Solution:

```html
<div class="container">
  <div class="arc left"></div>
  <div class="arc mid"></div>
  <div class="arc right"></div>
</div>

<style>
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  .container {
    background: #6592CF;
    width: 100vw;
    height: 100vh;
    position: relative;
  }
  .arc {
    position: absolute;
    width: 120px;
    height: 60px;
    border: 20px solid #060F55;
    border-top-left-radius: 100px;
    border-top-right-radius: 100px;
    border-bottom: 0;
    top: 50%;
    left: 50%;
  }
  .left {
    transform: translate(calc(-50% - 100px), calc(-50% - 80px));
  }
  .right {
    transform: translate(calc(-50% + 100px), calc(-50% - 80px));
  }
  .mid {
    transform: translate(-50%, calc(-50% + 80px)) rotate(-180deg);
  }
</style>
```

---

> #### Key Takeaway(s):
- using arc-like shapes with border properties and transparent background

As always, I welcome any feedback or questions regarding the implementation detail of the challenge. Otherwise, I hope this was useful!
How to Plan a Power Apps Development Project
Tags: powerfuldevs, powerapps, powerplat, poweraddicts
Published: 2022-07-16 01:53:18

This is the first video in the Beginner Power Apps series

Ee Lane Yu will be sharing with us what to pay attention to starting from the Requirement workshop, wireframing, theming and branding, to accessibility and many more.

Requirement Workshop Process
Pay attention to the following
1. Preparation and planning

- Read the Scope of Work
- Get to know your client and who is the stakeholders
- Find out the current environment landscape, business processes, data model organisation chart, user stories and app wireframe
- Tailor the workshop questions

2. Requirement Workshop

- Understand use case and pain points that need to be addressed
- Identify the users and their roles
- Clarify the business process and to-be environment landscape
- Confirm scope and interface design

3. Outcome

- User Stories & Acceptance Criteria
- App Storyboarding/Wireframe
- Environment landscape design
- Data Model Design
- Backlog

And many others
#canvasapp #powerapps #powerplatform
Share your coding mistake(s)!
Tags: discuss, programming, watercooler
Published: 2022-07-16 01:24:35

Hello, coders! :computer:

I’ll get the ball rolling.

Back in 2006 we were building an e-commerce from scratch and in a hurry as deadline was very tight!
I was in charge of orders from shopping carts to order modifications.
Users were able to edit their orders until the same day at midnight.
Some users complained their orders were missing a DVD or a book. It was a bit random and hard to track.
Upon investigation my colleague realised I had forgotten the order ID clause when deleting products from orders...
So any users who removed a DVD from their own order would remove it from all orders! D’oh!

What are some oops moments you can share?
Alias to remove deleted branches in a git remote at once
Tags: git
Published: 2022-07-16 01:17:22

---
title: Alias to remove deleted branches in a git remote at once
published: true
description: When working with git, local branches that have already been used are accumulated. Then I want to delete them all at once, so I defined an alias.
tags: git
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

When working with git, local branches that have already been used are accumulated. Then I want to delete them all at once, so I defined an alias.

```
git config --global alias.prune-no-longer-exist '!git branch -vv | grep '"'"': gone]'"'"' | grep -v '"'"'\*'"'"' | awk '"'"'{ print $1; }'"'"' | xargs -r git branch -d'
```

The alias `prune-no-longer-exist` will be available after executing the above command.

It can be used as follows

```
 $ git prune-no-longer-exist                                                                                                                                               
 Deleted branch xxxxx-account (was 9907023).
 Deleted branch xxxxx-account-accomplish (was 4b1bc41).
 Deleted branch xxxxx-to-gitignore (was 4154555).
 Deleted branch dependabot/bundler/puma-5.6.4 (was b8cf408).
```

Unnecessary branches are removed from the local machine to refresh it.

I referred to the following.

- [Git - Remove Local Branches That Are Merged or No Longer Exist | Justin James](https://digitaldrummerj.me/git-remove-local-merged-branches/)
- [8 Git aliases that make me more efficient | Opensource.com](https://opensource.com/article/20/11/git-aliases)
Python queue.Queue
Tags: python, queue
Published: 2022-07-16 00:59:18

---
title: Python queue.Queue
published: true
description: 
tags: python, queue
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

Python has 3 ways to implement a "queue" (FIFO rule).
- list
- collections.deque
- queue.Queue

[list](https://docs.python.org/3/tutorial/datastructures.html) is build-in, multi purpose structure. If get item out from a list, need to shift all item, may slow. [collections](https://docs.python.org/3/library/collections.html).deque: list-like container with fast appends and pops on either end. Here introduce more about [Queue](https://docs.python.org/3/library/queue.html):

```
from queue import Queue

q = Queue(5) # 5 is maxsize of the queue [1]
q.put('foo') # put item into a queue
q.put('bar')

print(q.qsize()) # approximate [2] size of the queue
>>> 2
print(q.full()) # check full or not
>>> False
print(q.empty()) # check empty or not
>>> False
a = q.get()
print(a)
>>> foo
b = q.get()
print(b)
>>> bar
c = q.get() 
# blocking  ... queue is empty, wait until an item is available. 

get_nowait() # get(False), if not available, raise queue.Empty

# blocking process
task_done() & join()
```


[1]
If queue is full, no free slow, put() will block while available

[2]
qsize() > 0 doesn’t guarantee that a subsequent get() will not block, nor will qsize() < maxsize guarantee that put() will not block.
AI-Driven Social Media Dashboard, Multi-language Tweets, Capture, Translate And Extract Insights In Near Real-time
Tags: aws, socialmedia, dashboard
Published: 2022-07-16 00:33:54

This is a step by step walkthrough image guide for the "AI-Driven Social Media Dashboard" https://aws.amazon.com/solutions/implementations/ai-driven-social-media-dashboard/

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


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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ljqqxynvlyyq1iij13g.jpg)


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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/630tl01v2cktg7p68uka.jpg)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8mh2gasfcb87p90jx7ko.jpg)


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


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


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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7jt0pkuyshu3j683q3vz.jpg)


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


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

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