teleren/devto huggingface dataset:
Graph Algorithm - Breadth First Search
Tags: beginners, programming, tutorial, career
Published: 2022-03-04 07:39:31

## What is a Graph

A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices, and edges are lines or arcs that connect any two nodes in the graph. 
More formally, a graph is a finite set of vertices(or nodes) and a set of edges that connect a pair of nodes.


## Important Graph Algorithms

* Breadth-First Search (BFS).
* Depth-First Search (DFS).
* Topological Sorting.
* Cycle Detection in Undirected Graph.
* Cycle Detection in Directed Graph.
* Kahn's Algorithm.
* Graph Bipartite check.
* Dijkstra's Algorithm.
* Bellman-Ford Algorithm.
* Prims Algorithm.
* Disjoint Set.
* Kruskal's Algorithm.
* Kosaraju's Algorithm.

## Breadth-First Search (BFS)

Breadth-First Search algorithm is a graph traversal algorithm that starts traversing the graph from the root node and goes through all its neighboring nodes. We select the nearest node and visit all neighbors. We can consider any node in the graph as the root node.
Consider a graph given below, with node 0 as the root node. In the BFS algorithm, we will use a queue, a First In First Out(FIFO) data structure, and enqueue our root node. We will also maintain a boolean array to keep track of the nodes which are visited, unvisited because we don't want to traverse a node that visited before. We will be traversing all the nodes given in the graph and try to apply the BFS algorithm to each node. These are the initial setup we do for the BFS algorithm.

![BFS Initial setup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tm1fjlmu11davlicc1op.png)

Until our queue is empty, repeat the following step:
Remove the node from the top of the queue.
Traverse through the neighbors of the removed node.
If the current neighbor is not visited, mark it as visited and add it to the queue.


![BFS Step Simulation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ai1fhik5rlb1mqdee78.gif)

## Time Complexity

* We are traversing through all the nodes and edges. So time complexity will be O(V + E) where V = vertices or node, E = edges.

* We use a visited array, queue, and an adjacency list for the graph. So the space complexity will be O(V) + O(V) + O(V + E). (Ignoring the space for the final result list).


## Code

![Java Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m5hcswzswe6bh7l9x7jw.png)

Originally Published On LinkedIn Newsletter : [LinkedIn Newsletter](https://www.linkedin.com/newsletters/graph-algorithm-6905161199672025088/) 

## Github Link

{% github https://github.com/Rohithv07/LeetCodeTopInterviewQuestions %}
Python for everyone: Mastering python the right way
Tags: python, beginners, codenewbie
Published: 2022-03-04 07:32:51

**An Overview of Python**

Python is a high-level interpreted language that was created by Guido van Rossum, and named by Rossum after Monty Python's Flying Circus, a BBC comedic series of the 1970s. Perhaps due to its recent popularity, many people think Python is a new programming language. Contrary to this, Python was actually first released in 1991, and is even older than traditionally "old" languages such as Java. With the rise in needs such as programming in data science and machine learning, python has provided an easy go-to, for people not trained as programmers to get started. Additionally, older versions of Python could not address specific domains as competing languages could. Take for example Django, a python web-framework, which was created more than a decade after the release of python to simplify web development. However, as we move towards an automated world, where coding has become a sought-after skill, you cannot hate Python, as it provides an easy way to get started with programming. Now, how should you approach it?
Writing well
Tags: discuss, personal, improvement, growth
Published: 2022-03-04 07:25:29

---
title: Writing well
published: true
description: Learning to write well is a skill that will come useful no matter the industry
tags: discuss, personal, improvement, growth
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/15znuwzv6x8ric2ela8k.jpg
---

> Learning to write well is a skill that will come useful no matter the industry.

---

_Originally published on [my blog](https://www.nikola-breznjak.com/blog/daily-thoughts/writing-well/)._

This is [why I write](https://www.nikola-breznjak.com/blog/daily-thoughts/why-do-i-write-these-daily-thoughts-posts/) these 'daily thoughts' posts.
Find number of lines of code  in a .Net project
Tags: dotnet
Published: 2022-03-04 07:00:17

I had a requirement to find the number of lines in a major project which has been completed with .Net 2019.

The way I found the number of lines of  coding is -


Step 1: Open the project 
step 2: View > Other Windows > Code Metrics Results
![![Find number of lines of code in a .Net project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzc2p2o4mceb2dh3f9jd.png)
 ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r09inmwpgcbpwsrs6yuk.png)

step 3 :
![Code Matrics Result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gwvfdh8y1hy4aqa3k1zu.png)

![Code Matrics Result View](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o6odxb7lncrn7kaw5sbp.png)
Should event handlers be named using business actions or UI events?
Tags: react, naming, frontend, discuss
Published: 2022-03-04 06:55:31

This problem is not specific to a framework, But I demonstrate questions in React.

Example 1. Suppose the following is a user registration page component

```jsx
const Register = () => {
  // business actions
  const onUserRegistered = () => {
    userService.register();
  };
  // Element event
  const onUserRegisteredFormSubmit = () => {
    userService.register();
  };

  return (
    <form onSubmit={onUserRegistered}>
      <button type="submit">Register</button>
    </form>
  );
};
```

Example 2. Suppose the following is a product create page component.

```jsx
const NewProduct = () => {
  // business actions
  const onProductCreated = () => {
    productService.create();
  };
  // Element event
  const onProductCreateButtonClick = () => {
    productService.create();
  };
  return (
    <>
      <button type="button" onClick={onProductCreated}>
        Create
      </button>
    </>
  );
};
```

As you can see, I am hesitant to use business actions, or elements events to name event handlers. I prefer element events to name the event handler because this is the presentation layer, the presentation layer should not care about business actions. The service layer contains business actions. Please advice.

Business action name composed by: `on` + `BusinessAction`

UI event name composed by: `on` + `WhichElement` + `Event`
Create simple form with Angular
Published: 2022-03-04 06:39:37

This article will introduce how to set a simple form in Angular with **ReactiveFormsModule**.

In order to use ReactiveFormsModule functionalities  you need to import ReactiveFormsModule in your module.


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

FromGroup containes all the input field value and binds those into a single json object.  These are key values pair, keys can be accessable from the template through FormGroup instance.
FromControl has two optional paramter, the first one the value of the control and the second is the validators.
FormArray can holds  and array of FormControl, its very hand to use when dynamic froms are required in form.

![form ts ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cyo1cgoq7wa5xi36jejc.png)

In the template FormGroup and its properties (FormControl, FormArray) can be bindable though _formGroup, formControlName, formArryName_


![form html](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7zsbnuqu8gy0gqocy4kq.png)

This simple demo project can be found under [this repo!](https://github.com/PJozeph/simple-form-demo)
Laravel 8 - Scopes (3 Easy Steps)
Tags: php, laravel, beginners, bestpractices
Published: 2022-03-04 06:35:17

**Scoping** is one of the superpowers that eloquent grants to developers when querying a model. **Scopes** allow developers to add `constraints` to queries for a given model.

> In simple terms **laravel scope** is just a query, a `query` to make the code `shorter` and `faster`. We can create custom query with relation or anything with scopes. 

> In any admin project we need to get data using status base, just like active, pending, draft something else. Instead of writing the same query everytime just use scopes and you're done!

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

## Let's Start Creating our Scope!

Let's create a simple with today() scope and it will get only today records.

## Step 1: Create Scope in Model

We will add today scope in our post model. So when we query in controller then we will use that scope in laravel model.

**app/Post.php**
```
<?php
  
namespace App;
  
use Illuminate\Database\Eloquent\Model;
  
class Post extends Model
{
    public $table = "posts";
      
    protected $fillable = [
        'id', 'title', 'body', 'status'
    ];
 
    public function scopeToday($query)
    {
        return $query->whereDate('created_at', \Carbon\Carbon::today());
    }
}
```

## Step 2: Use the scope in your controller

Go to you controller and use the scope by pasting this:

```
Post::today()->get();
```

We can also include parameters to make the scope more dynamic!

## Step 3: Make the Scope Dynamic by Adding Parameters

Lets go back to the model and add parameters to the scope 

**app/Post.php**

```
/**
     * Scope created awhile ago
     */
public function scopeToday($query)
    {
        return $query->whereDate('created_at', \Carbon\Carbon::today());
    }
/**
     * New Dynamic Scope
     */
public function scopeStatus($query, $type)
    {
        return $query->where('status', $type);
    }
```

## Use Both in your controller!

```
Post::status(1)->today()->get();
```

> Hurray! We have succesfully created our scopes (local scopes) and used it, now use it to your projects and make your code more readable and stable!

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

> I don't recommend the usage of Global Scopes because it can mess up the readability of queries when you are working with a team, specially if there are new members of the team. 

> But if you want to use it click [here](https://www.itsolutionstuff.com/post/laravel-global-scope-tutorial-exampleexample.html)

Instead just use Local Scopes which we discussed here and you are good to go!


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jowiq4q986im59flg966.gif)
What makes “Ant” pay for Guo Wengui's mistakes?
Published: 2022-03-04 06:27:12

Everyone knows,Guo Wengui was able to live in the United States for four years, relying entirely on the "loving support" of the “ants”.After all, as a "former tycoon", he left behind most of his assets and evaded most of his debts when he absconded from the United States, and without any money.Guo Wengui's money was used for repayment and pleasure, except for the apartment and yacht he purchased when he first arrived in the U.S. Everything else was purchased for him by the “Ants”.
PostCSS ဆိုတာဘာလဲ?
Tags: css, postcss
Published: 2022-03-04 06:16:53

PostCSS ဆိုတာက Polyfill လိုမျိုးပဲ။ 
PostCSS က modern web browser တွေကို အကုန်လုံးထောက်ပံနိုင်အောင်လို့ ပြောင်းလဲပေးတဲ့ နည်းပညာ တစ်မျိုး။
သမန်အားဖြင့် class selector ဆိုပါစို့။ mozillar အတွက်ဆိုရင် -moz နဲ့ ခံခံနေရတာ လက်ပေါက်ကပ်တယ်။
PostCSS က ဒါပေးရေးပေးရင်
```
:fullscreen {
}
```
ဒါပါ လုပ်ပေးလိုက်တယ်။
```
:-webkit-full-screen {
}
:-ms-fullscreen {
}
:fullscreen {
}
```
Limiting Pusher Connections with Laravel
Tags: laravel
Published: 2022-03-04 06:14:27

Laravel allows you to [Broadcast](https://laravel.com/docs/9.x/broadcasting#introduction) Server Side Events over a WebSocket Connection. This allows you to update your Frontend when a certain action is initiated or completed on Server, without User having to refresh their screen, thereby improving the User experience.

Laravel supports multiple drivers to implement Broadcasting, with [Pusher](https://pusher.com/) being one of the famous drivers. It allows you to have 100 Concurrent Connections in the Free Plan. Depending upon your usage, you might need one of their [Paid Plan](https://pusher.com/channels/pricing).

We had implemented the same on [Laravel Shift](https://laravelshift.com/), most noticeably on [Can I Upgrade Laravel](https://laravelshift.com/can-i-upgrade-laravel), which allows you to determine if your dependencies are compatible. All the other pages using Pusher were behind login and not publicly accessible.

Just before Laravel 9 was due to be released, the number of visitors to the Shift increased and we had to upgrade to a higher Pusher Plan to keep up with the Concurrent Connections. As the release buzz passed, the number of visitors were going back to pre-release levels, however the number of Concurrent Connections hadn't fallen by as much.

On further investigation we found out that a New Connection was being established for every visitor on the Site. Ideally a Connection should only be established when a User visits a Page which has functionality related to Pusher. However, a New Connection was getting established even if User Visited the Home Page. With the large number of Users that visit Laravel Shift, this was definitely a problem that we needed to address.

Laravel Documentation recommends adding the following code to  `bootstrap.js` inside `/resources/js` in order to enable Pusher.

```
import Echo from 'laravel-echo';
 
window.Pusher = require('pusher-js');
 
window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: true
});
```

We soon found out that whenever Pusher encounters the code `new Echo({...`, it starts a New Connection. Since this code was present in `bootstrap.js` which was being loaded on every page of the website (compiled via Laravel Mix), a connection was being established on every Page.

So once we figured out the root cause, we just moved the above code from `bootstrap.js` to a New JS File `custom.js`. We then injected this JS File using [Stacks](https://laravel.com/docs/9.x/blade#stacks) only on the pages where we were using Pusher.

We immediately saw a big decrease in the number of Connections after this fix and the numbers have been steady since then. In the hindsight, it is something which should have been obvious and could easily have been avoided. Fortunately it wasn't a very costly mistake.
Pointer ใน Go part 1
Published: 2022-03-04 06:11:17

คิดว่าเรื่อง pointer ในภาษา Go นี่อาจจะมีหลายตอน ทั้งๆที่ตอนนี้ก็ไม่ได้มีอะไรในหัว แต่ก็ขอตั้งชื่อ part 1 เอาไว้ก่อน 😅

พอดีว่าไปเจอโค้ดนึง น่าสนใจที่จะเอามาอธิบาย

```go
func NewPointerString(s string) *string {
	p := new(string)
	*p = s
	return p
}
```

โค้ดนี้น่าสนใจตรงที่ ความเข้าใจของเราจะคิดว่า ถ้าไม่ new pointer ตัวใหม่ขึ้นมา แล้วมาเขียนแบบนี้

```go
func NewPointerString(s string) *string {
	return &s
}
```

มันจะทำให้เราได้ address ของ s ตัวเดิมออกไป ซึ่งจะกลายเป็นว่า ค่าที่ return ออกไปมันจะ refer กลับไปหา s ตัวเดียวกัน

แต่ความเป็นจริง เมื่อ s เข้ามาในฟังก์ชัน `NewPointerString` แล้ว มันจะเป็นการ copy ค่า string เข้ามาในฟังก์ชันนี้อยู่แล้ว และนั่นทำให้ s ในฟังก์ชันเป็นคนละตัวกันกับ string ที่ใส่เข้ามาอยู่แล้ว

ทำให้เราสามารถเขียนแค่

```go
func NewPointerString(s string) *string {
	return &s
}
```

ก็ได้เช่นกันก็จะทำให้ pointer ตัวที่ return ออกไป refer ไปที่ string คำเดียวกัน แต่เป็นคนละตัวกันแล้ว ลองพิสูจน์ด้วยการพิมพ์ค่า address มันออกมาดูได้ดังนี้

```go
func main() {
	s := "Hi"
	p := NewPointerString(s)

	fmt.Println(p, &s)
}

func NewPointerString(s string) *string {
	return &s
}
```

output:

0xc00009e220 0xc00009e210

นี่ก็คือผลลัพธ์ที่ได้ เป็นคนละ address กันแล้วครับ
Preprocessor ဆိုတာဘာလဲ?
Tags: preprocess, css
Published: 2022-03-04 06:09:50

C language မှာဆိုရင် ကျွန်တော်တို့ `#define` တို့ `#include <stdio.h>` တို့ကို အဲထဲမှာ ပါဝင်တဲ့ code နဲ့ သွားပေါင်းလိုက်တဲ့ သဘော။
```
// main.c
#include <math.h>
void main(){
   return 0;
}
```
Preporcessor ဆိုတာကြီးက `math.h` ထဲက header file ထဲက codeတွေနဲ့ လို့အပ်သလို့ `main.c` ထဲကို သွားပေါင်းမှာ။ 

ဒီလိုပဲ CSS Preporcessor ဖြစ်တဲ့ LESS တို့၊ SASS တို့လည်း ဒီလိုသဘောပဲ။
ထပ်ခါ ထပ်ခါရေးနေရတဲ့ value ကို variable ပေးပြီးအသုံးပြုလို့ရအောင် လုပ်တဲ့ နည်းပညာမျိုး။
သာမန် CSS မှာဆိုရင်
```
body {
  font: 100% Helvetica, sans-serif;
  color: #333;
}
```
SASS မှာဆိုရင်
```
$font-stack: Helvetica, sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;
}
```
ရှိတယ်၊ အလာတူး တန်ဖိုးတွေကို variable ပေးပြီး ကြိုက်သလို အသုံးပြုနိုင်တယ်။ အထူးသဖြင့် global theme လိုမျိုးမှာ။
Razorpay payment DJANGO
Published: 2022-03-04 05:51:53

# Steps to integrate Razorpay 

* Setting up Razorpay account.

* Storing API keys in settings.py

* Installing Razorpay library.

* Creating order using Razorpay API.

* Creating order at backend and also creating Razorpay order.

	* Show template

	* render to payment.html

	* Get info of call back URL

	* Done with creating an order.

* Making payment.

* Handling payment success and failure.

	* Razorpay makes a post request

	* with the help of that handling success/failure

	* Done with payment.

	* Final checks for all platforms

	* Final checking

![](https://notionpack-uploads.s3.amazonaws.com//tmp/tmp6hepv6od.png)

![](https://notionpack-uploads.s3.amazonaws.com//tmp/tmpk_vyo514.png)

[https://gist.github.com/Nishant127/ed0e02cfb0ae0da3fb82f17b21252ca4](https://gist.github.com/Nishant127/ed0e02cfb0ae0da3fb82f17b21252ca4)


```python
def get_image_urls(cls, markdown):
        regex = r"!\[.?]\((https.*?)\)"
        urls = re.findall(regex, markdown)
        for url in urls:
            img_data = requests.get(url).content
            with tempfile.NamedTemporaryFile(suffix=".png") as image:
                image.write(img_data)
                upload_file_to_bucket(image.name)
                url = create_file_upload_url(image.name)
```

<br/>
Take ScreenShot using Java
Tags: beginners, programming, tutorial, java
Published: 2022-03-04 05:49:54

```
  Robot robot=new Robot();
Dimension dimension= Toolkit.getDefaultToolkit().getScreenSize();
Rectangle rectangle=new Rectangle(dimension);
BufferedImage img= robot.createScreenCapture(rectangle);
File f=new File("D://RobotScreenshot1.png");
ImageIO.write(img,"png", f);
```
I Storing the image in "D://RobotScreenshot1.png" this location.
Array Grouping In JavaScript Using array.groupBy()
Tags: javascript, arraygrouping, groupby, groupbytomap
Published: 2022-03-04 05:46:16

Today’s topic is the new array-group-proposal that introduces new methods array.groupBy() and array.groupByToMap().

We will learn about grouping an array of objects by key using groupBy() and groupByToMap().

👉 Click [here](https://www.c-sharpcorner.com/article/array-grouping-in-javascript-using-array-groupby/) to read full article.
I created the best web3 boilerplate out there!
Tags: web3, nextjs, javascript, react
Published: 2022-03-04 05:41:00

## Welcome!

Why is this boilerplate the best? Because all the top eth boilerplates on github right now are created by companies who integrate every aspect of their product/service into the boilerplate, making it all but unusable unless you sign up for their service!

Not this one.

Check out the [boilerplate](https://github.com/ilyxium/eth-nextjs-boilerplate)

This boilerplate uses the following open source libraries to bring you a fully functional, mobile optimized dApp:

- [next.js](https://nextjs.org/docs)
- [react.js](https://reactjs.org/)
- [wagmi](https://wagmi-xyz.vercel.app/)
- [ethers.js](https://docs.ethers.io/v5/)
- [chakra](https://chakra-ui.com/)

<img width="1437" alt="Screen Shot 2022-03-04 at 12 02 01 AM" src="https://user-images.githubusercontent.com/100057052/156702502-2882bdb6-4860-44ac-99fe-34056e8f356d.png">

## Get Started:
```bash
git clone https://github.com/ilyxium/eth-nextjs-boilerplate.git
# then
npm install
# then
npm run dev
# or
yarn dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

## What you get
- Connect Wallet + One example transaction 💲
- Scalable header + mobile menu ↔️
- Mobile friendly 📱
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s2ftpvmqghisqabzfnc7.png)
  
- 3 pages, including a 404 page, and routing done ✅
- Examples of buttons and links 👽

## Connect with me
Feel free to reach out on twitter [@ilyxium](https://twitter.com/ilyxium) and drop your questions, comments or suggestions on how I can improve this!

# Enjoy :)
Center Stuff using VSCode
Tags: css, webdev, productivity, tutorial
Published: 2022-03-04 05:33:05

Now I know for sure when coding for long hours for after a long gap we all go to Stack overflow to search one thing(even though it's just 3 lines of code) and that is "how to center x".

Being a fun banter in a recent interview I gave, on how to center a div. I thought if it is that simple, why not simplify it even more. Writing the same piece of code or copy-pasting is still a hassle xD.

So, while trying to find some solution I came across an interesting idea. Why not use VSCode Snippet to do it?
I confess I did not know that we can set custom snippets before this. 

So How do we do it?

For beginners who don't use code snippets, VSCode allows us to define a block of code that can be inserted with the help of a certain letter or set of letters and a TAB hit.

On Windows: Go to File then to Preferences then to User Snippets

On Mac: Replace File with Code menu -> Preferences -> User Snippets

![Getting to User Snippets](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9l6532u8cdzw4y35e3tn.png)

This will open a popup box will open asking which file you want to edit. Click on the `css.json`.

In the file, write the following code block:

```json
"Center Things" : {
  "prefix": "fc",
  "body": [
    "align-items: center;",
    "justify-content: center;"
  ],
  "description": "Center items in a flex container"
}
```
![Inside css.json](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lq82mn86n9k2lcrgyoa5.png)

The prefix is the text you'll have to write before hitting the TAB to expand the body. `fc` stands for "flex center".

We can make multiple such snippets. Here's one including the `display: flex` option

```json
"Flex and Center Things" : {
  "prefix": "ffc",
  "body": [
    "display: flex;",
    "align-items: center;",
    "justify-content: center;"
  ],
  "description": "Define a container flex and center it"
}
```
Save the file and have fun with it!

![Example 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/21kdw0cygqujibprhn1u.png)

Although this article is focused on VSCode, I'm sure there must be similar settings and files in other code editors as well.

What do you think of this? Let me know in the comments👇🏻

Follow my [Twitter](https://twitter.com/Neo_kaizerr) and [LinkedIn](https://www.linkedin.com/in/sobhandash/).
Python Exercise - Q2
Tags: programming, python, beginners, practice
Published: 2022-03-04 05:24:05

## Intro
Hello everyone welcome back and here is the **Practice Question **for python today

And the question is :
## Write a python program to calculate Simple interest in python

Please comment down your answers.
I will meet you soon in the next post till then stay safe and do take very good care of yourselves .