রবিবার, ৩ মার্চ, ২০২৪

Implementing a simple asynchronous web scraper using asyncio.**

 Implementing a simple asynchronous web scraper using asyncio.**

- **Solution:** Use asyncio to fetch multiple web pages concurrently, parse their content, and extract relevant information.

To implement a simple asynchronous web scraper using asyncio and incorporating the Factory Method design pattern, we can define an interface for web page scraping and concrete scraper classes for different websites. Here's how we can do it: ```python import asyncio import aiohttp from abc import ABC, abstractmethod class WebScraper(ABC): @abstractmethod async def scrape(self): pass class WikipediaScraper(WebScraper): async def scrape(self): async with aiohttp.ClientSession() as session: async with session.get('https://en.wikipedia.org/wiki/Main_Page') as response: html = await response.text() # Add parsing logic here print("Scraped content from Wikipedia:", html[:100]) class RedditScraper(WebScraper): async def scrape(self): async with aiohttp.ClientSession() as session: async with session.get('https://www.reddit.com/') as response: html = await response.text() # Add parsing logic here print("Scraped content from Reddit:", html[:100]) class WebScraperFactory: @staticmethod def get_scraper(scraper_type): if scraper_type == 'Wikipedia': return WikipediaScraper() elif scraper_type == 'Reddit': return RedditScraper() else: raise ValueError("Invalid scraper type") async def main(): scraper_types = ['Wikipedia', 'Reddit'] scrapers = [WebScraperFactory.get_scraper(scraper_type) for scraper_type in scraper_types] tasks = [scraper.scrape() for scraper in scrapers] await asyncio.gather(*tasks) asyncio.run(main()) ``` In this solution: - We define the `WebScraper` interface with an abstract method `scrape()`, which concrete scraper classes must implement. - `WikipediaScraper` and `RedditScraper` are concrete scraper classes that implement the `scrape()` method to scrape content from Wikipedia and Reddit, respectively. - The `WebScraperFactory` class provides a factory method `get_scraper()` to create instances of specific scraper classes based on the provided scraper type. - In the `main()` function, we create instances of scraper classes using the factory method, and then asynchronously call the `scrape()` method for each scraper using asyncio. This solution demonstrates the use of the Factory Method design pattern to create web scraper objects dynamically based on the provided type, allowing for easy extension and addition of new scraper types in the future.

শনিবার, ১৯ আগস্ট, ২০২৩

Implementing Google Social Authentication in a FastAPI backend with a React frontend involves several steps.

Implementing Google Social Authentication in a FastAPI backend with a React frontend involves several steps. In this example, I'll walk you through the process, starting with the backend and then the frontend. Please note that this example assumes you have a basic understanding of FastAPI, React, and JavaScript.

**Backend (FastAPI):**

1. **Set up a FastAPI Project:**

   Make sure you have FastAPI installed. You can create a FastAPI project using a tool like `cookiecutter` or manually create one.

2. **Install Required Libraries:**

   Install the necessary libraries for authentication:
   
   ```bash
   pip install fastapi uvicorn python-oauthlib httpx authlib
   ```

3. **Create a Google OAuth2 App:**

   Go to the Google Developer Console (https://console.developers.google.com/), create a new project, and set up OAuth2 credentials. Make sure to set the redirect URI to match your FastAPI server's endpoint (e.g., `http://localhost:8000/login/callback` for local development).

4. **Configure OAuth2 in FastAPI:**

   Create a file (e.g., `auth.py`) to handle OAuth2 authentication:

   ```python
   from fastapi import FastAPI, Depends, HTTPException
   from authlib.integrations.starlette_client import OAuth
   from fastapi.security.oauth2 import OAuth2PasswordBearer
   from authlib.integrations.httpx_client import AsyncOAuth2Client
   from fastapi.middleware.cors import CORSMiddleware

   app = FastAPI()

   origins = ["http://localhost:3000"]  # Update with your React app's URL.

   app.add_middleware(
       CORSMiddleware,
       allow_origins=origins,
       allow_credentials=True,
       allow_methods=["*"],
       allow_headers=["*"],
   )

   oauth = OAuth(app, AsyncOAuth2Client)

   oauth.register(
       name="google",
       client_id="YOUR_GOOGLE_CLIENT_ID",
       client_secret="YOUR_GOOGLE_CLIENT_SECRET",
       authorize_url="https://accounts.google.com/o/oauth2/auth",
       authorize_params=None,
       authorize_extra_params=None,
       token_url="https://accounts.google.com/o/oauth2/token",
   )
   ```

   Make sure to replace `"YOUR_GOOGLE_CLIENT_ID"` and `"YOUR_GOOGLE_CLIENT_SECRET"` with your actual Google OAuth credentials.

5. **Create Authentication Routes:**

   Create routes for OAuth2 authentication and callback:

   ```python
   @app.get("/login/google")
   async def login_with_google():
       redirect_uri = url_for("auth", _external=True)
       return await oauth.google.authorize_redirect(redirect_uri)

   @app.get("/login/callback")
   async def auth():
       token = await oauth.google.authorize_access_token()
       user = await oauth.google.parse_id_token(token)
       # Handle user data (e.g., store in a database)
       return {"user": user}
   ```

6. **Run the FastAPI Server:**

   Start the FastAPI server using Uvicorn:

   ```bash
   uvicorn main:app --host 0.0.0.0 --port 8000 --reload
   ```

**Frontend (React):**

1. **Create a React App:**

   Set up a React app using Create React App or your preferred method.

2. **Install Required Libraries:**

   Install the necessary libraries for handling OAuth2 in your React app:

   ```bash
   npm install axios react-oauth/google
   ```

3. **Implement Google Login Button:**

   In your React component, create a button to initiate the Google OAuth2 login:

   ```jsx
   import React from "react";
   import { GoogleLoginButton } from "react-oauth/google";

   const App = () => {
     const handleGoogleLogin = () => {
       // Redirect to your FastAPI login route
       window.location.href = "http://localhost:8000/login/google";
     };

     return (
       <div>
         <h1>My App</h1>
         <GoogleLoginButton onClick={handleGoogleLogin} />
       </div>
     );
   };

   export default App;
   ```

4. **Handle Redirect from FastAPI:**

   When the user returns from the FastAPI server after Google authentication, you can extract the user data from the URL or use an authentication state management library like Redux or React Context to handle the user data.

That's it! This example demonstrates how to implement Google Social Authentication in a FastAPI backend with a React frontend. Make sure to adjust the URLs, credentials, and error handling according to your specific requirements and production environment.


In the example I provided earlier, the first URL that can be hit is the login URL for Google OAuth2 authentication. This URL is defined in your FastAPI backend as follows:

```python
@app.get("/login/google")
async def login_with_google():
   redirect_uri = url_for("auth", _external=True)
   return await oauth.google.authorize_redirect(redirect_uri)
```

In this code, when a user navigates to the `/login/google` route in your FastAPI application, it triggers the `login_with_google` function. Inside this function, it prepares a redirect URL to Google's OAuth2 authorization page and then redirects the user to that URL.

The Google OAuth2 authorization URL is constructed based on the OAuth configuration you provided when registering your OAuth2 client with Google. This URL is where users will log in with their Google accounts and grant permission to your application.

Once users complete the Google login and authorization process, they will be redirected back to your FastAPI application's callback URL, which is defined as `/login/callback` in the example:

```python
@app.get("/login/callback")
async def auth():
   token = await oauth.google.authorize_access_token()
   user = await oauth.google.parse_id_token(token)
   # Handle user data (e.g., store in a database)
   return {"user": user}
```

In this `/login/callback` route, your FastAPI application receives the authorization code from Google, exchanges it for an access token, and retrieves user information.

So, to initiate the Google OAuth2 authentication process, you would navigate to `http://localhost:8000/login/google` (assuming you are running your FastAPI server locally on port 8000). This URL triggers the login process with Google, and upon successful authentication, users are redirected back to your FastAPI application's `/login/callback` route to complete the authentication flow. 

বুধবার, ৮ ফেব্রুয়ারী, ২০১৭

Fibonacci series Dynamically

Code:
#include<bits/stdc++.h>
using namespace std;
//int ar[]={1,2,3,4,5},sum;
//int x;
int n;
int f(int i)
{
    //int i=1;
//cout<<i<<" "<<x<<endl;
//x+=i;

    if(i<2)
        return i;
        return f(i-1)+f(i-2);

}
int main()
{

    while(cin>>n)
    {
        for(int i=0;i<=n;i++)
        cout<<f(i)<<" "<<endl;
    }
}

Find Factorial dynamically

#include<bits/stdc++.h>
using namespace std;
//int ar[]={1,2,3,4,5},sum;
//int x;
int n;
int f(int i,int x)
{
    //int i=1;
//cout<<i<<" "<<x<<endl;
//x+=i;

    if(i==n)
        return x*i;
        return x=f(i+1,x*i);

}
int main()
{

    while(cin>>n)
    {
        cout<<f(1,1)<<endl;
    }
}
Another code:
#include<bits/stdc++.h>
using namespace std;
//int ar[]={1,2,3,4,5},sum;
//int x;
int n;
int f(int i)
{
    //int i=1;
//cout<<i<<" "<<x<<endl;
//x+=i;

    if(i==0)
        return 1;
        return i*f(i-1);

}
int main()
{

    while(cin>>n)
    {
        cout<<f(n)<<endl;
    }
}

Summation of nth Integer number Dynamically

#include<bits/stdc++.h>
using namespace std;
//int ar[]={1,2,3,4,5},sum;
//int x;
int n;
int f(int i,int x)
{
    //int i=1;
//cout<<i<<" "<<x<<endl;
//x+=i;

    if(i==n)
        return x+i;
        return x=f(i+1,x+i);

}
int main()
{

    while(cin>>n)
    {
        cout<<f(1,0)<<endl;
    }
}

Another code:
#include<bits/stdc++.h>
using namespace std;
//int ar[]={1,2,3,4,5},sum;
//int x;
int n;
int f(int i)
{
    //int i=1;
//cout<<i<<" "<<x<<endl;
//x+=i;

    if(i==0)
        return i;
        return i+f(i-1);

}
int main()
{

    while(cin>>n)
    {
        cout<<f(n)<<endl;
    }
}


বৃহস্পতিবার, ১১ আগস্ট, ২০১৬

UVA 10013 - Super long sums

#include<bits/stdc++.h>
using namespace std;
#include<string.h>
#define mx 1000009
long long s1[mx],s2[mx];
long long s3[mx];
int main()
{
    long long i,j,k,n,m,l1,l2,a,b,s,carry,c,ll1,ll2;
   
    cin>>n;
    for(i=1; i<=n; i++)
    {

        cin>>m;
        for(j=0; j<m; j++)
            cin>>s1[j]>>s2[j];
        carry=0;
        c=0;
        for(j=m-1; j>=0; j--)
        {
            a=s1[j];
            b=s2[j];
           
            s=a+b+carry;
            if(s>9)
            {

                s3[c]=s%10;
                carry=1;
             
                c++;
            }
            else
            {
                s3[c]=s;
                carry=0;
             
                c++;
            }
        }
        if(carry==1)
            s3[c++]=carry;
            if(i!=1)
              cout<<endl;
        for(k=c-1; k>=0; k--)
            cout<<s3[k];
        cout<<endl;
    }
    return 0;
}

শুক্রবার, ২৪ জুন, ২০১৬

Recursive Functions বাংলায় শিখুন ২

এখানে আমি আর ভাল ভাবে বুঝানোর চেষ্টা করব কি ভাবে recursion কাজ করে_

পূর্বে আমরা recursive function সম্পর্কে দেখেছি। আরও ভালো ভাবে বুঝার জন্য নিচের post টা দেকতে পারেন_

recursive function টা অনেকটা একসঙ্গে  অনেকগুলো plate রাখার মতো  কাজ করে ।যেটা আগে রাখা হয়  সেটা সবার পরে বের করতে হয়।


এবার code টা দেখা যাক-

#include<stdio.h>
#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;
int a=1;
int b=10;
int c=20;
int f(int a)
{
    if(a>5)
        return 0;
    else
    {
        return a+f(a+1);
    }
}
int main()
{
    int s;
    s=f(1);
    printf("%d",s);
}

Output: 15

এখন প্রশ্ন হল কিভাবে code টা কাজ করছে তাই না ?

  1. main function এ গিয়া f(1) function টাকে call করবে। সুতরাং a=1 প্রথম অবস্থায়
  2. f(int a) function এ গিয়ে condition check করবে। condition মিথ্যা তাই সে return a+f(a+1); এ f(a+1) দ্বারা পুনরায় call করবে।
  3.  প্রতি call এ  যদি a এর মান  5 এর চে কম হয় তবে প্রতিবার a+f(a+1) return করবে।
  4. আবার condition check করবে। condition মিথ্যা ববে a+f(a+1) return করবে।
  5. এভাবে যখন না condition সত্য হয় ততোক্ষণ return  করবে।
  6. প্রতিবার এ f(a+1) function টা a এর মান ১ বৃদ্ধি করে দিচ্ছে এবং সেই মান দিয়েই call করছে। বেপারটা এরকম।
 1+f(a+1)        a=1;
2+f(a+1)         a=2
3+f(a+1)         a=3
4+f(a+1)         a=4
5+f(a+1)         a=5
a এর মান যখন 6 তখন return 0 করবে। ভাল ভাবে বঝার জন্য f(a+1) এর মান ans ধরে নেই , তাহলে বেপারটাএমন হয় 
 1+ans       a=1;
2+ans         a=2
3+ans        a=3
4+ans         a=4
5+ans         a=5
যেহেতু সবার শেষে 0 return করছে সেহেতু ans=0.

আমি আগেই বলেছি যে recursive function টা অনেকটা একসঙ্গে  অনেকগুলো plate রাখার মতো  কাজ করে ।যেটা আগে রাখা হয়  সেটা সবার পরে বের করতে হয়। 

 কাজ সম্পাদন করার সময় অনুযায়ী উপর থেকে নিচে  সাজালে আমরা পাই
ans=0;
5+ans         a=5
4+ans         a=4
3+ans        a=3
2+ans         a=2
1+ans          a=1;
তাহলে কাজ টা এমন হবে-
ans=5+0     [ যেহেতু ans=0 ছিল]
ans=4+5    [ যেহেতু ans=5=5+0 ছিল]
ans=3+9    [ যেহেতু ans=9=4+5 ছিল]
ans=2+12    [ যেহেতু ans=12=3+9 ছিল]
ans=1+14    [ যেহেতু ans=14=2+12ছিল]
ans=15    [ যেহেতু ans=15=1+14 ছিল]