teleren/devto huggingface dataset:
Number of longest common subsequence
Tags: css, dp
Published: 2022-01-13 18:57:18

## Solution:

```
class Solution {
public:
   
    int findNumberOfLIS(vector<int>& nums) {
         int n=nums.size();
         int *length=new int[n];
        int *count=new int[n];
        for(int i=0;i<n;i++)
        {
            length[i]=1;
            count[i]=1;
        }
        for(int i=1;i<n;i++)
        {
            for(int j=0;j<=i-1;j++)
            {
                if(nums[j]<nums[i])
                   {
                    if(length[j]+1>length[i])
                    {
                        length[i]=length[j]+1;
                        count[i]=count[j];
                    }
                    else if(length[j]+1==length[i])
                    {
                        count[i]+=count[j];
                    }
                }
            }
        }
        int t=*max_element(length,length+n);
int result=0;
        for(int i=0;i<n;i++)
        {  if(length[i]==t)
            result+=count[i];
            
        }
        return result ;
        
    }
        
};
```


 

 * Here we had to count the LIS. So we maintained another array named count.
 * The idea is to use two arrays len[n] and cnt[n] to record the maximum length of Increasing Subsequence and the
 * coresponding number of these sequence which ends with nums[i], respectively. That is:
 *
 * len[i]: the length of the Longest Increasing Subsequence which ends with nums[i].
 *
 * cnt[i]: the number of the Longest Increasing Subsequence which ends with nums[i].
 *
 * Then, the result is the sum of each cnt[i] while its corresponding len[i] is the maximum length.
 *
 * For example, we have nums = [1,3,5,4,7]. Then after we have processed till 4, our len and count array will be like
 *                       len = [1,2,3,3,4]
 *                     count = [1,1,1,1,2].
 * We see that when we have two increasing subseq of len 3, and need one more element to increase both lengths to 4, then we have a
 * number of count1 + count2 ways to find a lIS of length 4. Thats why we add both count[i] and count[j] when len[i] == len[j]+1
 * Thats because when we have len[i] already equal to len[j]+1 means that there already exists a subseq which can make an LIS of len[j]+1
 * so we need to count its number of ways too!
X-Guardian - MongoDB Atlas Hackathon
Tags: atlashackathon
Published: 2022-01-13 18:36:50

# X-Guardian 

Alert webapp backed by Mongo

The app allows you to report different kind of alerts such as outage, crime, stray and flood.

Reported alerts are sent to backend and then presented through different dashboards (generated by MongoDB Charts).

## Stack

- Scala + MongoDB Scala Driver
- React
- MongoDB Charts and MongoDB Atlas
- Scheduled Triggers to generate random data into the collections

## Submission Category:

Action Star

## Link to Code

[X-Guardian](https://github.com/osorionicolas/x-guardian)

## Additional Resources / Info

We use docker and docker-compose to deploy the app

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

### Screenshots

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


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

### Collaborators:

* https://dev.to/serdeliverance
To do list app with react typescript and react testing library
Tags: react, typescript, testing, javascript
Published: 2022-01-13 18:26:44

## Using typescript and testing code with react testing library

Typescript really makes it easy for developers to know the type of variables and return type of the functions which are in play.

I have used hooks for managing states, one can mention the type of state they are defining which makes its type unchangeable resulting in lesser discrepancy issues.

```
  const [task,setTask] = useState<string>("");
  const [tasks,setTasks] = useState<Array<string>>([])
```

The type of props should be defined before using them in the children component which can be done using `type` or `interface` keyword.

```
type props = {
    setTask:React.Dispatch<React.SetStateAction<string>>
    tasks:string[] 
    setTasks:React.Dispatch<React.SetStateAction<string[]>>
    task:string
}
```
 
For testing purpose I've used react testing library to do simple unit and integration testing. 

```
const mockSetTask = jest.fn()
const mockSetTasks = jest.fn()

var task:string
var tasks:string[] = []

it('gets input from input component',  ()=>{
        render(<Input  setTask={mockSetTask} setTasks={mockSetTasks} tasks={tasks} task={task}/>)
        const ele = screen.getByPlaceholderText("Enter Task") as HTMLInputElement

        fireEvent.change(ele,{target:{value:'Go To Gym'}})
        expect(ele.value).toBe('Go To Gym')
    })
```
Github Repo : [To do list app](https://github.com/YashasaveeKesarwani99/todolist)
Complete Login / Signup System - MongoDB Atlas 🚀
Tags: atlashackathon, javascript, mongodb, webdev
Published: 2022-01-13 18:23:59

### Overview of My Submission:
🎊The purpose of this project, you can build your own complete login system for your website, using MongoDB Atlas...

----

### Submission Category: 📢

**Choose Your Own Adventure** using MongoDB Atlas 

---

### Features: ⚙
please see the video... 😁

---


### Technologies Used: 🛠

- Bootstrap
- JavaScript
- EJS
- NodeJS
- MongoDB Atlas
- Mongoose
- Heroku
- nodemaile

---

### Link to Code: ✨

**GitHub**

 {% github https://github.com/jacksonkasi0/login-system %}

---

### Postman Link: 🍀  [click here!] (https://documenter.getpostman.com/view/17812631/UVJkCDgf)

---

### Video: 🎥

{% youtube https://youtu.be/F4gLWla8Ovs %}
Authentication 
Tags: atlashackathon
Published: 2022-01-13 18:22:25

[Instructions]: # (To submit to the MongoDB Atlas Hackathon on DEV, please fill out all sections.)


### Overview of My Submission
[Note]: # (Please make sure the project links to the appropriate GitHub repository, and includes the [Apache-2 permissive license](https://www.apache.org/licenses/LICENSE-2.0)  and README.)
The project uses a special type of authentication where a mathematical problem is generated on a canvas based captcha which you need to solve in order to enter

### Submission Category: 

[Note]: # (E-Commerce Creation, Prime Time, Action Star, Automation Innovation, or Choose Your Own Adventure)
Own Adventure

### Link to Code
[Super-Auth](https://github.com/ishanjain1502/Super-Auth)
[Note]: # (Our markdown editor supports pretty embeds. Try this syntax: `{% github link_to_your_repo %}` to share a GitHub repository)


### Additional Resources / Info

As of now no open source project is using it.
Django REST FRAMEWORK Tutorial 2 -- quickstart アプリで作った API を curl でテストする
Tags: django, restframework, curl
Published: 2022-01-13 18:21:41


## 前回までの進捗

https://dev.to/kaede_io/docker-compose-de-rest-tutorial-woyaru-22k0

前回の記事はこれ

https://www.django-rest-framework.org/tutorial/quickstart/#project-setup

quickstart の記事はこれ

API 環境構築は前回やった

docker-compose up で api サーバーが立ち上がるようになってる

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

=============


## curl -u で 8002/users/ の API のテストをする

https://www.django-rest-framework.org/tutorial/quickstart/#testing-our-api

ターミナルから curl コマンドでテストができるらしい

```
curl -H 'Accept: application/json; indent=4' \
 -u admin:******** http://127.0.0.1:8002/users/
```

これで

```json
{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "url": "http://127.0.0.1:8002/users/1/",
            "username": "admin",
            "email": "admin@example.com",
            "groups": []
        }
    ]
}
```

ターミナルでアクセスできる

-u で userName:password で basic 認証をした上で中身を見れる

-H で 改行して整形した json を見れる

========


## http -a で テストする

```
http -a admin:password http://127.0.0.1:8000/users/
```

http コマンドは見つからなかった

======
Storebay: An E-commerce Application With Custom Admin And Checkout functionality
Tags: atlashackathon, react, mongodb, node
Published: 2022-01-13 18:14:13

### Overview of My Submission
Storebay is an E-Commerce platform. It is built on the MERN stack (MongoDB, Express, React, Node js). It has features like a custom admin panel to manage users, PayPal checkout, reviews,android and ios app and more.


### Submission Category:
E-Commerce 


### Link to Code
{% github https://github.com/Narottam04/StoreBay %}


### Live Url 🎉🎉🥳
https://storebayapp.herokuapp.com/

### Main Tech Stack

React - For Frontend
Tailwind CSS - For Styling
Node Js, Express - For Backend
PayPal : For Payment
MongoDB Atlas : For Database 
MongoDB Atlas Search : For autocomplete search functionality
Capacitor Js: For converting existing web app to android and ios

## App Preview & Features


#### HomePage

![Home Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xl21965gv6biz6v73x2k.jpeg)
![Home Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mae1w6ctaop2w85dbqj1.jpeg)
  

#### Login Page
Login and Sign up is created using Node Js && MongoDB 

![Login Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ny8tf26rklqy1zy812rr.png)

![Login Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/saw1actpdj0iaccg0r5f.png)
 

#### Profile Page

![Profile Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sxnm9r4au2yu9iwdym6k.png) 

### Admin Page

Using a custom admin panel, a user can make other users admins, manage products, add new ones, update existing ones, and mark a delivery as successful.

![Admin Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6taoxbfrql37w3gfz00e.png)
![Admin Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5rolaythzhu0l32bjm58.png)
  
![Admin Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vy9ava4nzx7kphqf9bjn.png)
 

#### Product overview

![Product](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cajp5u0c7pjfn4owzd48.png)
 

#### Reviews

Each signed in user can only add one review per products.

![review](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jbrpwz038sq6twszqhwb.png)
 
#### Cart

![Cart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hssvtt2plcge6invtn3a.png)
 
## Checkout Process

#### Step1

User must add their shipping address for step 1

![Checkout1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ngo8d2b6s46aoj9cmhqk.png)

#### Step2

User must choose a payment method. Currently only paypal payment method is working

![Checkout2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vh63nnvdqpv6qqhq2mig.png)

#### Step 3 
Step 3 is order summary where you can view your product,shipping and payment details  

#### Step 4 [IMP] 

Payment using paypal

![Checkout3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q2nbsg4urdkhan19hmte.png)
![Checkout4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qjp432a4sff9fk7x79xm.png)

![Checkout5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/osi6yhpf2gcndkn2c86a.png)

That's all folks, I hope you enjoy this project
Excluding Fields in Django Rest Framework Serializers
Tags: django, webdev, drf, python
Published: 2022-01-13 18:03:12

This is a simple way to exclude fields from being returned by a DRF serializer, without creating a separate serializer or installing another package. I needed to exclude a field when using the list action for a ModelViewSet, but because we'll be utilizing the serializer's context, it can be used no matter how you write your views.

## Modifying the serializer

We're going to override the serializer's `get_fields` method to remove any fields we pass through the serializer's context. I like to use a list of strings so that I can easily remove fields without making changes to the serializer later.

```python
class WidgetSerializer(serializers.Serializer):
    name = SomeTypeOfField()
    parts = SomeTypeOfField()

    def get_fields(self):
        fields = super().get_fields()

        exclude_fields = self.context.get('exclude_fields', [])
        for field in exclude_fields:
            # providing a default prevents a KeyError
            # if the field does not exist
            fields.pop(field, default=None)

        return fields
```

You would use the same method with a ModelSerializer if you use those.

## How to use

Let's assume we have a field named `parts` in `WidgetSerializer` that we'd like to exclude from our response in a specific view. All we have to do is include the field name in the `exclude_fields` list passed through the serializer's context.

```python
class ListWidgets(APIView):
    def get(self, request, format=None):
        context = {
            'exclude_fields': [
                'parts'
            ]
        }

        widgets = Widget.objects.all()
        serializer = WidgetSerializer(widgets, many=True, context=context)

        # parts field will not be included
        return Response(serializer.data) 
```

If you are using DRF's ViewSets (including ModelViewSet), you can override the `get_serializer_context` method instead. For example, if you only wanted to exclude fields in the list action, you could do the following:

```python
class WidgetViewSet(viewsets.ModelViewSet):
    queryset = Widget.objects.all()
    serializer_class = WidgetSerializer

    def get_serializer_context(self):
        context = super().get_serializer_context()
        if self.action == 'list':
            context['exclude_fields'] = ['parts']
        return context
```

## Conclusion

Hopefully this little guide helps you easily exclude fields from DRF serializers. I've only tested it with ModelViewSets and excluding fields in the list action, so it may not cover all cases. Feel free to contact me with corrections or suggestions on improvements.
Binary search is not for sorted arrays only !
Published: 2022-01-13 17:56:45

While talking about ' Binary Search ' , we consider that it will only work for "Sorted arrays" , but that's not the condition.

It will work for " Unsorted arrays" also ,

yes but only one kind of "unsorted array" ,
i.e., *The Rotated Array*.

It can be done in O(log n) time complexity , like a binary search , but it uses different method .
It uses "adjusted divide and conquer algorithm"
The DAC👍

And ssshhhh 🤫 ***it will be solved recursively only***
MongoDB Submission Post - Endorsedeck
Published: 2022-01-13 17:05:26

### Introduction
This is my submission for the [atlas hackathon](https://dev.to/devteam/announcing-the-mongodb-atlas-hackathon-on-dev-4b6m). This app allows you to collect testimonials from your customers at a single place. The app is a clone of [testimonial.to](https://testimonial.to/) product.

### Overview of My Submission
I have used the **mongodb serverless instance**.

#### Tech stack
1. Laravel
2. Livewire
3. MongoDB and MySQL
4. Tailwind

This app has following main entities - 
1. Users
2. Walls
3. Testimonials

I have used MySQL for users and all the authentication stuff as it comes in-built in laravel, also it does not need many read and write operations.

I have used [MongoDB serverless instance](https://docs.atlas.mongodb.com/tutorial/create-new-serverless-instance/) for the walls and testimonials entities as they have high number of **read and write** operations.

### Submission Category: 

My submission category is **Automation Innovation**.


### Link to Code

{% github https://github.com/frikishaan/endorsedeck %}


### Additional Resources / Info

The demo of the app is available here at [endorsedeck.herokuapp.com](https://endorsedeck.herokuapp.com/)

User can create walls from the dashboard.

![endorsedeck dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9q2glnz1tcwh8o11svpu.png)

Users can share the public URL of their wall where other users can submit their review and see other review.

![endorsedeck public page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jondnq9kurfi2lfw69h.png)

Every testimonial is associated with a wall. You can see all your reviews by clicking the eye icon form dashboard.

![endorsedeck reviews](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/thd6d3cplhcvdqbhjd4o.png)

I have used MongoDB Serverless instance for this project to store walls and testimonials.

![mongodb atlas database dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e7dnvpp4unyznr74cm89.png)

Write something on my wall [here](https://endorsedeck.herokuapp.com/ishaan/wall/61e10f3c5c114b6d9f2d4f72).
Let's Chat About Contexts in Go
Tags: go, programming, beginners, discuss
Published: 2022-01-13 17:45:33

Today I want to have a brief chat about Contexts in Go. :)

Every Go developer uses Contexts in their coding lifetime.

Read this [profound yet straightforward blog](https://go.dev/blog/context) if you are new to Go and Contexts.

To excel as a developer, we should actively make an effort to understand the **"why"**.

There are many great articles on the web about using Contexts in Go and the how-to.

But, let's mull over **_why_** should Contexts be used in the first place.

---

## Carriers of Metadata

Contexts [carry miscellaneous metadata](https://pkg.go.dev/context#example-WithValue) that is helpful for each invoked function call. This metadata could include the caller's information or general identification information. 

This metadata is also helpful while debugging incoming requests if we log the messages with the context information.

## Resources Saver!

Contexts offer [an ability to cancel an ongoing operation](https://pkg.go.dev/context#CancelFunc) if - 

- The caller invoked a cancellation -

  - Imagine a scene where a flick to the first domino makes all subsequent dominos fall.

  - That is how the parent Context's [CancelFunc](https://pkg.go.dev/context#CancelFunc) cancels derived contexts.

- When the operation takes longer than expected -

  - In this case, the Context's cancel logic is invoked when the [configured deadline](https://pkg.go.dev/context#WithDeadline) exceeds, and this cancellation propagates to the derived contexts.

The advantage of context cancellation is that all goroutines exit immediately, and the application can reclaim used resources such as memory.

> _Using Contexts is a way to safeguard resource consumption._

---

## Further Reading

If you want to understand Contexts in-depth, I recommend you head over to these links - 

[Contexts and Structs](https://go.dev/blog/context-and-structs)

This blog advocates a noteworthy takeaway - 

> Context makes it easy to propagate important cross-library and cross-API information down a calling stack. But, it must be used consistently and clearly in order to remain comprehensible, easy to debug, and effective.

[Context Pkg](https://pkg.go.dev/context)

For the How-To.

Until Later!
What is a Value Object
Tags: php, laravel, ddd, architecture
Published: 2022-01-13 17:37:48

What is the most annoying thing when you're working with legacy code written by php as example? there's a lot of annoying thing, look at this method :

```
public function filter($data)
{
    // filter data
}
```

first thing, we cant detact $data type so we need to jump to the filter method involving to know the type of $data . and we need to know what inside $data . and we need to read filter method to know if $data altered or not. php is weak type language sothat we can change $data type if it is array we can make it int. so this is another problem.

value object come to solve this problems to us. 

value object is a small object that represents a simple entity whose equality is not based on identity: two value objects are equal when they have the same value, not necessarily being the same object. from wiki.

Eric Evans define value object like this, An object that represents a descriptive aspect of the domain with no conceptual identity is called a Value Object. Value Objects are instantiated to represent elements of the design that we care about only for what they are, not who or which they are.

Value objects are used to represent some undividable concept through the app. like, a customer address or currency.  Instead of throwing scalars between classes that cause alot of problem, we send value object. When you receive a value object you don't need to validate it, it is valid by default. The other important thing of value object is immutability. so you pass objects to classes and you be sure this objects not altered.

The benefits of Value Objects:
1- everything is type hinted. so we send value object to class and we know the type.
2- Built in validation, An object contains built-in validators which enforce its internal format. like, an address must have  city, country and street. Whenever you instantiate a new address object, you must give it valid data otherwise the object instantiation fails.
3- immutability An object cannot be changed by anyone. once created it can only be cloned, thus the logic who created the object is confident that the data is never altered.
4- no identity, a corollary of value objects identity-less nature is, obviously, not having an Id property. Unlike entities, value objects should be compared by value, not by identity field.

php example :

```
final class Address
{
    public function __construct(
        private string $country,
        private string $city,
        private string $street,
        private int    $buildingNumber,
        private int    $flatNumber
    )
    {
        if ($this->country != 'USA') {
            throw new \InvalidArgumentException("Not supported country: {$this->country}.");
        }
    }
    
    public function getCountry(){
        return $this->country;
    }
    
    public function isValidateCountry(string $country){
        return $this->country === $country;
    }
} 
```
Online Compress Jpg Tools 
Tags: webdev, tutorial
Published: 2022-01-13 17:27:53

Today I came to discuss with you a free tools online. Many people say that many tools can be found by searching on Google. I would also say yes, but they are full of ads from different companies. That’s why thinking about you, today I came up with a completely free and ad-free website.

Let me give you some descriptions before I share the website with you today. There are no ads on this website. Very simple design user friendly. You can reduce jpg image size without any hassle.

This tool is very important for those of us who are blogging. Because in order to keep a website fast, we need to reduce the size while maintaining the quality of the image. Then we use many websites or plugins. But those who use the blogger website have to do this with the help of various tools online. Basically there are blogger sites they will use these tools the most. If you want, WordPress users can also use this tool to easily reduce the image size while maintaining the image quality.

Try this one:- [Online compress jpg tools](https://OnlineCompressJpg.com)