Snippets Collections
# Import necessary libraries
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, classification_report

# Step 1: Load the dataset
df = pd.read_csv('Iris.csv')  # Replace with the correct path if needed

# Step 1.1: Data Exploration
print("Dataset Preview:")
print(df.head())

# Data Overview
print("\nDataset Information:")
print(df.info())

# Step 1.2: Verify Missing Values
print("\nMissing Values:")
print(df.isnull().sum())

# Step 1.3: Verify Duplicates
print("\nDuplicate Rows:")
print(df.duplicated().sum())

# Step 1.4: Detect and Remove Outliers using IQR method
# IQR method to detect outliers
Q1 = df.select_dtypes(include=[np.number]).quantile(0.25)
Q3 = df.select_dtypes(include=[np.number]).quantile(0.75)
IQR = Q3 - Q1

# Outliers are those outside the range (Q1 - 1.5*IQR) and (Q3 + 1.5*IQR)
outliers_iqr = ((df.select_dtypes(include=[np.number]) < (Q1 - 1.5 * IQR)) | 
                (df.select_dtypes(include=[np.number]) > (Q3 + 1.5 * IQR))).any(axis=1)

# Removing outliers
df_no_outliers_iqr = df[~outliers_iqr]
print(f"\nShape after removing outliers: {df_no_outliers_iqr.shape}")

# Step 1.5: Split Dataset and Perform Naive Bayes Classification
# Define features (X) and target (y)
X = df_no_outliers_iqr.drop(['Id', 'Species'], axis=1)  # Drop 'Id' and 'Species'
y = df_no_outliers_iqr['Species']

# Split the data into training and testing sets (70% training, 30% testing)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Initialize Naive Bayes classifier (GaussianNB for continuous data)
nb_classifier = GaussianNB()

# Train the model
nb_classifier.fit(X_train, y_train)

# Make predictions on the test set
y_pred = nb_classifier.predict(X_test)

# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f"\nAccuracy of the Naive Bayes model: {accuracy * 100:.2f}%")
print("\nClassification Report:")
print(classification_report(y_test, y_pred))

# Optional: Visualize the distribution of data and outliers
plt.figure(figsize=(10, 6))
sns.boxplot(data=df_no_outliers_iqr.drop(['Id', 'Species'], axis=1))
plt.title('Boxplot to Visualize Outliers After Removal')
plt.show()
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
 
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score,confusion_matrix
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
 
# Load the Iris dataset
iris = pd.read_csv('/content/iris.csv')
X = iris.drop(columns=["Species"]) # Features
y = iris["Species"]  # Labels
 
 
 
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
# Train the SVC model with a linear kernel
model = SVC(kernel='linear', random_state=42)
model.fit(X_train, y_train)
 
# Make predictions
y_pred = model.predict(X_test)
 
# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy:.2f}")
 
conf_matrix = confusion_matrix(y_test, y_pred)
print('Confusion Matrix:')
print(conf_matrix)
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# Step 1.1: Convert dictionary to DataFrame
data = {
    'Feature1': [1, 2, np.nan, 4, 5],
    'Feature2': [5, np.nan, np.nan, 8, 9]
}

df = pd.DataFrame(data)


df['Feature1'].fillna(df['Feature1'].mean(), inplace=True)

# Step 1.4: Fill missing values in 'Feature2' with median
df['Feature2'].fillna(df['Feature2'].median(), inplace=True)





df['Target'] = [0, 1, 0, 1, 0]  # Example target values for classification


X = df.drop(columns=['Target'])  # Features (without 'Target')
y = df['Target']  # Target variable

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Step 3: Load Decision Tree Classifier
clf = DecisionTreeClassifier(random_state=42)

# Step 4: Train the model
clf.fit(X_train, y_train)

# Step 5: Make predictions
y_pred = clf.predict(X_test)

# Step 6: Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f"\nDecision Tree Classifier Accuracy: {accuracy * 100:.2f}%")

import java.util.Scanner;

public class Prims {
    private static int N;  // Number of vertices
    
    // Function to get the vertex with the minimum cost that is not yet in MST
    public static int getMin(int[] costs, boolean[] isInMST) {
        int min = Integer.MAX_VALUE;
        int minVertex = -1;
        
        // Iterate over all vertices to find the one with the minimum cost
        for (int i = 0; i < costs.length; i++) {
            if (!isInMST[i] && costs[i] < min) {  // Only consider vertices not in MST
                min = costs[i];
                minVertex = i;
            }
        }
        return minVertex;
    }
    
    // Function to perform Prim's algorithm to find the MST
    public static void solution(int[][] matrix) {
        int[] parent = new int[N];  // To store the parent of each vertex in MST
        int[] costs = new int[N];   // To store the minimum cost for each vertex
        boolean[] isInMST = new boolean[N];  // To check if a vertex is in MST
        
        // Initialize all costs to infinity, and mark all vertices as not in MST
        for (int i = 0; i < N; i++) {
            costs[i] = Integer.MAX_VALUE;
            isInMST[i] = false;
        }
        
        // The starting vertex (0) has cost 0, and no parent
        costs[0] = 0;
        parent[0] = -1;
        
        // Run Prim's algorithm to find the MST
        for (int i = 0; i < N - 1; i++) {
            int curr = getMin(costs, isInMST);  // Get the vertex with the minimum cost
            isInMST[curr] = true;  // Add it to the MST
            
            // Update the costs of the adjacent vertices
            for (int adj = 0; adj < N; adj++) {
                // If there is an edge, and the vertex is not in MST, and the cost is smaller
                if (matrix[curr][adj] != 0 && !isInMST[adj] && matrix[curr][adj] < costs[adj]) {
                    parent[adj] = curr;  // Set the parent
                    costs[adj] = matrix[curr][adj];  // Update the cost
                }
            }
        }
        
        // Print the results (the MST edges and total cost)
        printResults(parent, matrix);
    }
    
    // Function to print the edges and their weights
    public static void printResults(int[] parent, int[][] matrix) {
        int totalCost = 0;
        System.out.println("Edge\tWeight");
        
        // Print each edge in the MST
        for (int i = 1; i < N; i++) {
            System.out.println(parent[i] + " - " + i + " \t" + matrix[i][parent[i]]);
            totalCost += matrix[i][parent[i]];  // Add the edge weight to the total cost
        }
        System.out.println("Total cost of MST: " + totalCost);
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        // Read the number of vertices
        System.out.print("Enter the number of vertices: ");
        N = sc.nextInt();
        
        // Initialize the adjacency matrix
        int[][] matrix = new int[N][N];
        
        System.out.println("Enter the adjacency matrix (0 for no edge):");
        // Read the adjacency matrix from the user
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                matrix[i][j] = sc.nextInt();
            }
        }
        
        // Call Prim's algorithm to find the MST
        solution(matrix);
        
        // Close the scanner
        sc.close();
    }
}
#8. Violin Plot
#Violin plots are used to show the distribution of data across different categories.
# Example: Violin plot for Sales in different regions
import seaborn as sns

# Sample data for different regions
data = {
    'Region': ['North', 'East', 'West', 'South', 'North', 'East', 'West', 'South'],
    'Sales': [12000, 15000, 17000, 13000, 16000, 19000, 18000, 15000]
}

df = pd.DataFrame(data)

sns.violinplot(x='Region', y='Sales', data=df)
plt.title("Violin Plot of Sales by Region")
plt.show()
#7. Heatmap
#Heatmaps are used to visualize the correlation between different variables.
import seaborn as sns
import pandas as pd

# Example: Heatmap of correlations
data = {
    'Sales': sales,
    'Profit': profit,
    'Products Sold': products_sold
}
df = pd.DataFrame(data)
correlation_matrix = df.corr()

sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm')
plt.title("Correlation Heatmap")
plt.show()
#6. Scatter Plot
#Scatter plots are used to visualize relationships between two variables.
# Example: Scatter plot of Sales vs. Profit
profit = [4000, 6000, 7000, 3000, 5000, 8000]

plt.scatter(sales, profit, color='green')
plt.title("Sales vs. Profit")
plt.xlabel("Sales ($)")
plt.ylabel("Profit ($)")
plt.show()
#5. Box Plot
#Box plots are used to show the distribution of data based on quartiles.
# Example: Box plot of Sales
sales = [12000, 15000, 17000, 13000, 16000, 19000]

plt.boxplot(sales)
plt.title("Box Plot of Sales")
plt.ylabel("Sales ($)")
plt.show()
#4. Pie Chart
#Pie charts are used to show proportions of a whole.
# Example: Pie chart of Profit distribution by Region
profit_by_region = [7000, 11000, 7000, 8000]
regions = ["North", "East", "West", "South"]

plt.pie(profit_by_region, labels=regions, autopct='%1.1f%%', colors=['gold', 'lightblue', 'lightgreen', 'pink'])
plt.title("Profit Distribution by Region")
plt.show()

#3. Histogram
#Histograms are used to visualize the distribution of a dataset.
# Example: Histogram of Products Sold
products_sold = [120, 130, 140, 110, 135, 150]

plt.hist(products_sold, bins=5, color='orange')
plt.title("Distribution of Products Sold")
plt.xlabel("Number of Products Sold")
plt.ylabel("Frequency")
plt.show()
#2. Bar Plot
#Bar plots are used to compare different categories.
# Example: Bar plot for Sales by Region
regions = ["North", "East", "West", "South"]
sales_by_region = [25000, 31000, 17000, 19000]

plt.bar(regions, sales_by_region, color='red')
plt.title("Sales by Region")
plt.xlabel("Region")
plt.ylabel("Sales ($)")
plt.show()
#data visulization
#1. Line Plot
#Line plots are used to visualize data points over time.

import matplotlib.pyplot as plt

# Example: Line plot for Sales over months
months = ["January", "February", "March", "April",
          "May", "June"]
sales = [12000, 15000, 17000, 13000, 16000, 19000]

plt.plot(months, sales, marker='*')
plt.title("Sales Over Time")
plt.xlabel("Month")
plt.ylabel("Sales ($)")
plt.show()
import java.util.Arrays;

import java.util.Comparator;

import java.util.Scanner;

class Item {

    int id;

    int weight;

    int profit;

    double cost;

    public Item(int id, int weight, int profit) {

        this.id = id;

        this.weight = weight;

        this.profit = profit;

        this.cost = (double) profit / weight;

    }

}

public class FractionalKnapsack {

    public static double fractionalKnapsack(Item[] items, int capacity, float[] solutionVector) {

        Arrays.sort(items, Comparator.comparingDouble(item -> -item.cost));

        double totalProfit = 0.0;

        for (Item item : items) {

            if (capacity == 0) {

                break;

            }

            if (item.weight <= capacity) {

                totalProfit += item.profit;

                capacity -= item.weight;

                solutionVector[item.id - 1] = 1.0f;

            } else {

                float fraction = (float) capacity / item.weight;

                totalProfit += item.profit * fraction;

                solutionVector[item.id - 1] = fraction;

                capacity = 0;

            }

        }

        return totalProfit;

    }

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of items: ");

        int n = scanner.nextInt();

        System.out.print("Enter the capacity of the knapsack: ");

        int capacity = scanner.nextInt();

        Item[] items = new Item[n];

        float[] solutionVector = new float[n];

        for (int i = 0; i < n; i++) {

            System.out.print("Enter weight and profit of item " + (i + 1) + ": ");

            int weight = scanner.nextInt();

            int profit = scanner.nextInt();

            items[i] = new Item(i + 1, weight, profit);

            solutionVector[i] = 0.0f;

        }

        double maxProfit = fractionalKnapsack(items, capacity, solutionVector);

        System.out.printf("Maximum profit in Knapsack = %.2f\n", maxProfit);

        System.out.print("Solution vector (ID: fraction included): ");

        for (int i = 0; i < n; i++) {

            System.out.printf(" %d: %.2f ", items[i].id, solutionVector[i]);

        }

        System.out.println();

        

    }

}
from sklearn import datasets

from sklearn.model_selection import train_test_split

from sklearn.svm import SVC

from sklearn.metrics import accuracy_score, confusion_matrix

# Step 1: Load the Iris dataset

iris = datasets.load_iris()

X = iris.data

y = iris.target

# Step 2: Select only two classes ('setosa' and 'versicolor')

X = X[y != 2]   # Remove 'virginica' class

y = y[y != 2]   # Keep only classes 0 and 1

# Step 3: Split the dataset

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Step 4: Train the SVC model

model = SVC(kernel='linear')

model.fit(X_train, y_train)

# Step 5: Make predictions and evaluate

y_pred = model.predict(X_test)

accuracy = accuracy_score(y_test, y_pred)

conf_matrix = confusion_matrix(y_test, y_pred)

print("Accuracy:", accuracy)

print("Confusion Matrix:\n", conf_matrix)
#include <stdio.h>

void SumOfSub(int s, int k, int r, int w[], int n, int x[]) {
    // Base case: if the sum of weights equals the target
    if (s == r) {
        printf("Subset found: { ");
        for (int i = 0; i < k; i++) {
            if (x[i] == 1) {
                printf("%d ", w[i]);
            }
        }
        printf("}\n");
        return;
    }

    // If we exceed the number of weights or if the sum exceeds the target
    if (k >= n || s > r) {
        return;
    }

    // Generate left child: include current weight
    x[k] = 1; // Include w[k]
    SumOfSub(s + w[k], k + 1, r, w, n, x);

    // Generate right child: exclude current weight
    x[k] = 0; // Exclude w[k]
    SumOfSub(s, k + 1, r, w, n, x);
}

int main() {
    int n;
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int w[n];
    printf("Enter the elements (non-decreasing order): ");
    for (int i = 0; i < n; i++) {
        scanf("%d", &w[i]);
    }
    
    int m;
    printf("Enter the target sum: ");
    scanf("%d", &m);

    int x[n]; // Array to store inclusion/exclusion of weights
    SumOfSub(0, 0, m, w, n, x); // Start with sum 0 and index 0

    return 0;
}
INPUT:
Enter the number of elements: 5
Enter the elements (non-decreasing order): 1 2 3 4 5
Enter the target sum: 5
OUTPUT:
Subset found: { 1 4 }
Subset found: { 2 3 }
Subset found: { 5 }

import java.util.Scanner;

public class Main {

    // Method to find all subsets with sum equal to the target sum
    public static void SumOfSub(int s, int k, int r, int[] w, int n, int[] x) {
        // Base case: if the sum of weights equals the target
        if (s == r) {
            System.out.print("Subset found: { ");
            for (int i = 0; i < k; i++) {
                if (x[i] == 1) {
                    System.out.print(w[i] + " ");
                }
            }
            System.out.println("}");
            return;
        }

        // If we exceed the number of weights or if the sum exceeds the target
        if (k >= n || s > r) {
            return;
        }

        // Generate left child: include current weight
        x[k] = 1; // Include w[k]
        SumOfSub(s + w[k], k + 1, r, w, n, x);

        // Generate right child: exclude current weight
        x[k] = 0; // Exclude w[k]
        SumOfSub(s, k + 1, r, w, n, x);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input for number of elements
        System.out.print("Enter the number of elements: ");
        int n = scanner.nextInt();

        // Input for the elements (weights)
        int[] w = new int[n];
        System.out.print("Enter the elements (non-decreasing order): ");
        for (int i = 0; i < n; i++) {
            w[i] = scanner.nextInt();
        }

        // Input for the target sum
        System.out.print("Enter the target sum: ");
        int m = scanner.nextInt();

        // Array to store inclusion/exclusion of weights
        int[] x = new int[n];

        // Start the recursion
        SumOfSub(0, 0, m, w, n, x);

        // Close the scanner
        scanner.close();
    }
}
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Add numbers</title>
</head>
<body>
	
	<form action="add" method="get">
		enter num1:<input type="text" name="num1"><br>
		Enter num2:<input type="text" name="num2">
		
		<br>
		<input type="submit" value="Add">
	</form>
</body>
</html>

Add.java:
package com.Add;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet( urlPatterns={"/add"})
public class Add extends HttpServlet {
    public void service(HttpServletRequest req, HttpServletResponse res) throws IOException {
    	
    	int i=Integer.parseInt(req.getParameter("num1"));
    	int j=Integer.parseInt(req.getParameter("num2"));
    	
    	int k=i+j;
    	PrintWriter out=res.getWriter();
    	out.println(k);
    			
    }

}

web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>ParamDemo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>default.htm</welcome-file>
  </welcome-file-list>
</web-app>

HelloServlet.java:
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.annotation.WebServlet;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        response.getWriter().println("<h1>Hello, World!</h1>");
    }
}

web.xml:
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

Output:
It displays in Web Browser:
Hello, World

Demo.java:
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/Demo")
public class Demo extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    public Demo() {
        super();
        
    }

	
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        // Initialization code here
        System.out.println("Servlet init() method called.");
    }


    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        // Handle request
        System.out.println("Servlet service() method called.");
        super.service(req, res);
    }
    @Override
    public void destroy() {
        // Cleanup code here
        System.out.println("Servlet destroy() method called.");
    }

}

web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>Demo1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>default.htm</welcome-file>
  </welcome-file-list>
</web-app>
jQuery('.testimonialsSlider').slick({
  slidesToShow: 1,
  slidesToScroll: 1,
  arrows: true,
  prevArrow: "<button type='button' class='slick-prev pull-left'><span class='list-icon fas fa-chevron-left'></span></button>",
  nextArrow: "<button type='button' class='slick-next pull-right'><span class='list-icon fas fa-chevron-right'></span></button>",
  dots: false,
  autoplay: false,
  autoplaySpeed: 2000,
  infinite: true,
  adaptiveHeight: false,

  responsive: [
    {
      breakpoint: 1024,
      settings: {
        slidesToShow: 1,
        slidesToScroll: 1,
      }
    },
    {
      breakpoint: 768,
      settings: {
        slidesToShow: 1,
        slidesToScroll: 1
      }
    },
    {
      breakpoint: 480,
      settings: {
        slidesToShow: 1,
        slidesToScroll: 1
      }
    }
  ]
});

For arrows copy paste this link in header.php
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />


     jQuery('.ser-content').slick({
                slidesToShow: 2,
                slidesToScroll: 1,
                arrows: false,
                // prevArrow:\"<button type='button' class='slick-prev pull-left'><span class='list-icon fas fa-chevron-left'></span></button>\",
                // nextArrow:\"<button type='button' class='slick-next pull-right'><span class='list-icon fas fa-chevron-right'></span></button>\",
                dots: false,
                autoplay: true,
                autoplaySpeed: 2000,
                infinite: true,
                adaptiveHeight: false,
                responsive: [
                    {
                        breakpoint: 1024,
                        settings: {
                            slidesToShow: 3,
                            slidesToScroll: 1,
                        }
                    },
                    {
                        breakpoint: 768,
                        settings: {
                            slidesToShow: 2,
                            slidesToScroll: 1
                        }
                    },
                    {
                        breakpoint: 480,
                        settings: {
                            slidesToShow: 1,
                            slidesToScroll: 1
                        }
                    }
                ]
            });
import pandas as pd
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
import matplotlib.pyplot as plt
import seaborn as sns

# Step 1.1: Load the Iris dataset
iris = datasets.load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df['target'] = iris.target
df['species'] = df['target'].map({0: 'setosa', 1: 'versicolor', 2: 'virginica'})
print("Original Iris DataFrame:\n", df.head())

# Step 1.2: Select two classes ('setosa' and 'versicolor')
df_binary = df[df['species'].isin(['setosa', 'versicolor'])]
X = df_binary.iloc[:, :-2].values  # Features
y = df_binary['target'].values     # Target labels

# Step 1.3: Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Step 1.4: Load the SVC Model
svc_model = SVC(kernel='linear', random_state=42)
svc_model.fit(X_train, y_train)

# Step 1.5: Perform prediction
y_pred = svc_model.predict(X_test)

# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print("\nAccuracy of SVC Model:", accuracy)

# Confusion Matrix
conf_matrix = confusion_matrix(y_test, y_pred)
print("\nConfusion Matrix:\n", conf_matrix)

# Classification Report
print("\nClassification Report:\n", classification_report(y_test, y_pred, target_names=['setosa', 'versicolor']))

# Plot the Confusion Matrix
plt.figure(figsize=(6, 4))
sns.heatmap(conf_matrix, annot=True, cmap='Blues', fmt='d', xticklabels=['setosa', 'versicolor'], yticklabels=['setosa', 'versicolor'])
plt.title('Confusion Matrix')
plt.xlabel('Predicted Labels')
plt.ylabel('True Labels')
plt.show()
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of elements:");
        int n = sc.nextInt();
        int[] arr = new int[n];
        System.out.println("Enter the elements:");
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        System.out.println("Enter the target sum:");
        int target = sc.nextInt();
        System.out.println("Subsets with sum equal to " + target + " are:");
        findSubsets(arr, n, target);
        sc.close();
    }
    private static void findSubsets(int[] arr, int n, int target) {
        List<Integer> currentSubset = new ArrayList<>();
        subsetSumHelper(arr, n, 0, 0, target, currentSubset);
    }
    private static void subsetSumHelper(int[] arr, int n, int index, int currentSum, int target, List<Integer> currentSubset) {
        if (currentSum == target) {
            System.out.println(currentSubset);
            return;
        }
        if (index >= n || currentSum > target) {
            return;
        }
        currentSubset.add(arr[index]);
        subsetSumHelper(arr, n, index + 1, currentSum + arr[index], target, currentSubset);
        currentSubset.remove(currentSubset.size() - 1);
        subsetSumHelper(arr, n, index + 1, currentSum, target, currentSubset);
    }
}
#include <stdio.h>
#include <limits.h>

#define INF INT_MAX 

int Prim(int cost[][100], int n, int t[][2]) {
    int near[100], mincost = 0;
    int i, j, k, l;

    for (i = 1; i <= n; i++) {
        near[i] = 0;
    }

    mincost = INF;
    for (i = 1; i <= n; i++) {
        for (j = i + 1; j <= n; j++) {
            if (cost[i][j] < mincost) {
                mincost = cost[i][j];
                k = i;
                l = j;
            }
        }
    }

    t[1][0] = k;
    t[1][1] = l;

    for (i = 1; i <= n; i++) {
        if (cost[i][l] < cost[i][k]) {
            near[i] = l;
        } else {
            near[i] = k;
        }
    }
    near[k] = near[l] = 0;

    for (i = 2; i <= n; i++) {
        int min_edge_cost = INF;
        for (j = 1; j <= n; j++) {
            if (near[j] != 0 && cost[j][near[j]] < min_edge_cost) {
                min_edge_cost = cost[j][near[j]];
                k = j;
                l = near[j];
            }
        }

        t[i][0] = k;
        t[i][1] = l;

        mincost += cost[k][l];

        near[k] = 0;

        for (j = 1; j <= n; j++) {
            if (near[j] != 0 && cost[j][near[j]] > cost[j][k]) {
                near[j] = k;
            }
        }
    }

    return mincost;
}

int main() {
    int cost[100][100], t[100][2], n, i, j;

    printf("Enter the number of vertices: ");
    scanf("%d", &n);

    printf("Enter the cost adjacency matrix:\n");
    for (i = 1; i <= n; i++) {
        for (j = 1; j <= n; j++) {
            scanf("%d", &cost[i][j]);
            if (cost[i][j] == 0) {
                cost[i][j] = INF;
            }
        }
    }

    int mincost = Prim(cost, n, t);

    printf("Minimum cost of the spanning tree: %d\n", mincost);

    printf("Edges in the minimum spanning tree:\n");
    for (i = 1; i < n; i++) {
        printf("Edge: (%d, %d)\n", t[i][0], t[i][1]);
    }

    return 0;
}
import java.util.*;
public class Main {
 
    private static void sumOfSubSet(int[] set, int n, int targetSum, int index, List<Integer> currentSubset) {
        if (index == n) {
            int sum = 0;
            for (int num : currentSubset) {
                sum += num;
            }
 
            if (sum == targetSum) {
                System.out.println(currentSubset);
            }
            return;
        }
 
        currentSubset.add(set[index]);
        sumOfSubSet(set, n, targetSum, index + 1, currentSubset);
 
        currentSubset.remove(currentSubset.size() - 1);
        sumOfSubSet(set, n, targetSum, index + 1, currentSubset);
    }
 
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
 
        System.out.print("Enter the number of elements in the set: ");
        int n = scanner.nextInt();
 
        int[] set = new int[n];
        
        System.out.println("Enter the elements of the set: ");
        for (int i = 0; i < n; i++) {
            set[i] = scanner.nextInt();
        }
 
        System.out.print("Enter the target sum: ");
        int targetSum = scanner.nextInt();
 
        System.out.println("Subsets whose sum equals " + targetSum + ":");
        List<Integer> currentSubset = new ArrayList<>();
        sumOfSubSet(set, n, targetSum, 0, currentSubset);
 
        scanner.close();
    }
}
import java.util.*; 
 
public class Articulation { 
    private int n; 
    private int[][] arr; 
    private int[] dfn; 
    private int[] low; 
    private int num; 
    private Set<Integer> s; 
 
    public Articulation(int n) { 
        this.n = n; 
        arr = new int[n][n]; 
        dfn = new int[n]; 
        low = new int[n]; 
        num = 1; 
        s = new HashSet<>(); 
    } 
 
    public void read(Scanner scan) { 
        for (int i = 0; i < n; i++) { 
            for (int j = 0; j < n; j++) 
                arr[i][j] = scan.nextInt(); 
            dfn[i] = 0; 
        } 
    } 
 
    public void art(int u, int v) { 
        dfn[u] = num; 
        low[u] = num; 
        num++; 
        int child = 0; 
        for (int j = 0; j < n; j++) { 
            if (arr[u][j] == 1 && dfn[j] == 0) { 
                if (v == -1) 
                    child++; 
                art(j, u); 
                if (v != -1 && low[j] >= dfn[u]) 
                    s.add(u); 
                low[u] = Math.min(low[u], low[j]); 
            } else if (arr[u][j] == 1 && j != v) 
                low[u] = Math.min(low[u], dfn[j]); 
        } 
        if (v == -1 && child > 1) 
            s.add(u); 
    } 
 
    public void printVisited() { 
        System.out.println("articulation points" + s); 
        for (int i = 0; i < n; i++) 
            System.out.print(dfn[i] - 1 + " "); 
        System.out.println(); 
    } 
 
    public static void main(String[] args) { 
        Scanner scan = new Scanner(System.in); 
        System.out.println("enter no of vertices"); 
        int n = scan.nextInt(); 
        Articulation art = new Articulation(n); 
        System.out.println("adjacent matrix"); 
        art.read(scan); 
        art.art(0, -1); 
        System.out.println("vertices"); 
        art.printVisited(); 
    } 
} 
/@version=5
indicator("LMR with Bullish and Bearish Arrows", overlay=true)

// --- Price and Volume Definitions for Previous Days ---
price1 = close[1]
price2 = close[2]
price3 = close[3]

volume1 = volume[1]
volume2 = volume[2]
volume3 = volume[3]

// --- LMR Calculations ---
MR1 = (price1 - close) / volume1  // Price change relative to previous volume
LMR2 = (price2 - price1) / (volume2 + volume1)  // Price change relative to combined volume of last two days
LMR3 = (price3 - price2) / (volume3 + volume2 + volume1)  // Price change relative to combined volume of last three days

// --- Plot Raw LMR Values ---
plot(MR1, color=color.green, title="MR1 (Raw)")
plot(LMR2, color=color.orange, title="LMR2 (Raw)")
plot(LMR3, color=color.purple, title="LMR3 (Raw)")

// --- Simplified Bullish Signal Condition ---
bullishSignal = (close > price1 and volume > ta.sma(volume, 20))  // Bullish if current price is higher than previous and volume is above average

// --- Simplified Bearish Signal Condition ---
bearishSignal = (close < price1 and volume > ta.sma(volume, 20))  // Bearish if current price is lower than previous and volume is above average

// --- Plot Bullish Signal as Background Color ---
bgcolor(bullishSignal ? color.new(color.green, 90) : na, title="Bullish Signal") // Green: Bullish Signal

// --- Plot Bullish Arrow (Below Bar) ---
plotshape(bullishSignal, title="Bullish Signal Arrow", location=location.belowbar, color=color.green, style=shape.arrowup, size=size.small)

// --- Plot Bearish Arrow (Above Bar) ---
plotshape(bearishSignal, title="Bearish Signal Arrow", location=location.abovebar, color=color.red, style=shape.arrowdown, size=size.small)

// --- Optional: Adding Alerts for Bullish and Bearish Signals ---
alertcondition(bullishSignal, title="Bullish Signal Alert", message="Bullish signal detected!")
alertcondition(bearishSignal, title="Bearish Signal Alert", message="Bearish signal detected!")

// --- Optional: Smoothed LMR Values for Reduced Noise ---
LMR1_smooth = ta.sma(MR1, 10)  // Smooth MR1 over 10 periods
LMR2_smooth = ta.sma(LMR2, 10)  // Smooth LMR2 over 10 periods
LMR3_smooth = ta.sma(LMR3, 10)  // Smooth LMR3 over 10 periods

// --- Plot Smoothed LMR Values ---
plot(LMR1_smooth, color=color.green, title="Smoothed MR1")
plot(LMR2_smooth, color=color.orange, title="Smoothed LMR2")
plot(LMR3_smooth, color=color.purple, title="Smoothed LMR3")
/@version=5
indicator("LMR with Bullish and Bearish Arrows", overlay=true)

// --- Price and Volume Definitions for Previous Days ---
price1 = close[1]
price2 = close[2]
price3 = close[3]

volume1 = volume[1]
volume2 = volume[2]
volume3 = volume[3]

// --- LMR Calculations ---
MR1 = (price1 - close) / volume1  // Price change relative to previous volume
LMR2 = (price2 - price1) / (volume2 + volume1)  // Price change relative to combined volume of last two days
LMR3 = (price3 - price2) / (volume3 + volume2 + volume1)  // Price change relative to combined volume of last three days

// --- Plot Raw LMR Values ---
plot(MR1, color=color.green, title="MR1 (Raw)")
plot(LMR2, color=color.orange, title="LMR2 (Raw)")
plot(LMR3, color=color.purple, title="LMR3 (Raw)")

// --- Simplified Bullish Signal Condition ---
bullishSignal = (close > price1 and volume > ta.sma(volume, 20))  // Bullish if current price is higher than previous and volume is above average

// --- Simplified Bearish Signal Condition ---
bearishSignal = (close < price1 and volume > ta.sma(volume, 20))  // Bearish if current price is lower than previous and volume is above average

// --- Plot Bullish Signal as Background Color ---
bgcolor(bullishSignal ? color.new(color.green, 90) : na, title="Bullish Signal") // Green: Bullish Signal

// --- Plot Bullish Arrow (Below Bar) ---
plotshape(bullishSignal, title="Bullish Signal Arrow", location=location.belowbar, color=color.green, style=shape.arrowup, size=size.small)

// --- Plot Bearish Arrow (Above Bar) ---
plotshape(bearishSignal, title="Bearish Signal Arrow", location=location.abovebar, color=color.red, style=shape.arrowdown, size=size.small)

// --- Optional: Adding Alerts for Bullish and Bearish Signals ---
alertcondition(bullishSignal, title="Bullish Signal Alert", message="Bullish signal detected!")
alertcondition(bearishSignal, title="Bearish Signal Alert", message="Bearish signal detected!")

// --- Optional: Smoothed LMR Values for Reduced Noise ---
LMR1_smooth = ta.sma(MR1, 10)  // Smooth MR1 over 10 periods
LMR2_smooth = ta.sma(LMR2, 10)  // Smooth LMR2 over 10 periods
LMR3_smooth = ta.sma(LMR3, 10)  // Smooth LMR3 over 10 periods

// --- Plot Smoothed LMR Values ---
plot(LMR1_smooth, color=color.green, title="Smoothed MR1")
plot(LMR2_smooth, color=color.orange, title="Smoothed LMR2")
plot(LMR3_smooth, color=color.purple, title="Smoothed LMR3")
{"version":"2.0.126.1","settings":{"blur":0,"brightness":100,"contrast":100,"grayscale":0,"huerotate":0,"invert":0,"saturate":100,"sepia":0,"applyvideofilters":false,"backgroundcolor":"#000000","backgroundopacity":85,"blackbars":false,"blockautoplay":true,"blockhfrformats":false,"blockwebmformats":false,"boostvolume":false,"cinemamode":false,"cinemamodewideplayer":true,"controlbar":{"active":true,"autohide":false,"centered":true,"position":"absolute"},"controls":["loop","reverse-playlist","volume-booster","cards-end-screens","cinema-mode","size","pop-up-player","speed","video-filters","screenshot","keyboard-shortcuts","options"],"controlsvisible":false,"controlspeed":true,"controlspeedmousebutton":false,"controlvolume":false,"controlvolumemousebutton":false,"convertshorts":false,"customcolors":{"--main-color":"#00adee","--main-background":"#111111","--second-background":"#181818","--hover-background":"#232323","--main-text":"#eff0f1","--dimmer-text":"#cccccc","--shadow":"#000000"},"customcssrules":"","customscript":"","customtheme":false,"darktheme":false,"date":1703498547766,"defaultvolume":false,"disableautoplay":false,"executescript":false,"expanddescription":false,"filter":"none","hidecardsendscreens":false,"hidechat":false,"hidecomments":false,"hiderelated":false,"hideshorts":false,"ignoreplaylists":true,"ignorepopupplayer":true,"localecode":"en_US","localedir":"ltr","message":false,"miniplayer":true,"miniplayerposition":"_top-left","miniplayersize":"_400x225","newestcomments":false,"overridespeeds":true,"pauseforegroundtab":false,"pausevideos":true,"popuplayersize":"640x360","qualityembeds":"medium","qualityembedsfullscreen":"hd1080","qualityplaylists":"hd720","qualityplaylistsfullscreen":"hd1080","qualityvideos":"hd720","qualityvideosfullscreen":"hd1080","reload":false,"reversemousewheeldirection":false,"selectquality":false,"selectqualityfullscreenoff":false,"selectqualityfullscreenon":false,"speed":1,"speedvariation":0.1,"stopvideos":false,"theatermode":false,"theme":"default-dark","themevariant":"youtube-deep-dark.css","update":1717756335131,"volume":50,"volumemultiplier":3,"volumevariation":5,"wideplayer":false,"wideplayerviewport":false}}
clc; 
clear all; 
close all;

Fs = 1e6;  % Sampling frequency
fd = 100;  % Doppler frequency

% Custom Rayleigh fading implementation
n = 1000; % Number of samples
pathDelays = [0 1e-5 2e-5];
pathGains_dB = [0 -3 -6];
pathGains = 10.^(pathGains_dB/10); % Convert to linear scale

% Generate Rayleigh fading samples
t = (0:n-1)/Fs; % Time vector
rayleigh_fading = zeros(n, length(pathDelays));
for i = 1:length(pathDelays)
    doppler_phase = 2 * pi * fd * t; % Doppler effect
    rayleigh_fading(:, i) = sqrt(pathGains(i)) * ...
        abs(1/sqrt(2) * (randn(1, n) + 1j * randn(1, n))) .* exp(1j * doppler_phase);
end

% Custom Rician fading implementation
k = 10; % Rician K-factor
rician_fading = sqrt(k/(k+1)) + sqrt(1/(k+1)) * rayleigh_fading;

% Generate random input signal
x = randn(n, 1);

% Pass the signal through the custom Rayleigh and Rician channels
y_rayleigh = sum(rayleigh_fading, 2) .* x;
y_rician = sum(rician_fading, 2) .* x;

% Extract impulse responses
impulse_response_rayleigh = rayleigh_fading;
impulse_response_rician = rician_fading;

% Plot Rayleigh channel impulse response
figure;
subplot(2, 1, 1);
plot(abs(impulse_response_rayleigh));
title('Rayleigh Fading Channel Impulse Response');
xlabel('Sample Number');
ylabel('Amplitude');

% Plot Rician channel impulse response
subplot(2, 1, 2);
plot(abs(impulse_response_rician));
title('Rician Fading Channel Impulse Response');
xlabel('Sample Number');
ylabel('Amplitude');

% Calculate and plot Rician channel power delay profile
Pd_rician = mean(abs(impulse_response_rician).^2, 1); % Average power per path
figure;
stem(10*log10(Pd_rician), 'filled'); % Power in dB
title('Rician Fading Channel Power Delay Profile');
xlabel('Path Index');
ylabel('Power (dB)');

% Compute FFT of the Rayleigh and Rician faded signals
fft_rayleigh = fft(y_rayleigh);
fft_rician = fft(y_rician);

% Plot frequency spectrum
figure;
subplot(2, 1, 1);
plot(abs(fft_rayleigh));
title('Frequency Spectrum of Rayleigh Fading Signal');
xlabel('Frequency Index');
ylabel('Amplitude');

subplot(2, 1, 2);
plot(abs(fft_rician));
title('Frequency Spectrum of Rician Fading Signal');
xlabel('Frequency Index');
ylabel('Amplitude');
Viterbi Decoding Algorithm for Convolutional Codes 
Program1: 
input_seq = [1 0 1]; % Original input sequence 
input_seq = [1 0 1]; % Original input sequence 
g = [1 0 1; 1 1 1]; % Generator polynomials for (2,1) code 
% Create trellis structure 
trellis = poly2trellis(3,[5,7]); 
% Convolutional encoding 
encoded_seq = convenc(input_seq, trellis); 
disp('Encoded Sequence:'); 
disp(encoded_seq); 
% Simulate transmission with noise (introducing errors) 
received_seq = encoded_seq; 
% error_indices = randperm(length(encoded_seq), 2); % Introduce 
2 errors 
% received_seq(error_indices) = ~received_seq(error_indices); % 
Flip bits 
% disp('Received Sequence (with errors):'); 
disp(received_seq); 
% Viterbi decoding 
decoded_seq = vitdec(received_seq, trellis, 2, 'trunc','hard'); 
disp('Decoded Sequence:'); 
disp(decoded_seq); 
Program2 
trellis = poly2trellis([4 3],[4 5 17;7 4 2]); 
x = ones(100,1); 
code = convenc(x,trellis); 
tb = 2; 
decoded = vitdec(code,trellis,tb,'trunc','hard'); 
isequal(decoded,ones(100,1))
clc
clear

% Generation of Sample bits
sequence=round(rand(1,20));    % Generating 20 bits
input_signal=[];                 % input signal declaration                
carrier_signal=[];               % carrier signal declaration  
time=[0:2*pi/119:2*pi];          % Number of samples - Creating a vector of 120 total values including end point [0:0.052:6.28]  


for k = 1 :20
    if sequence(1,k)==0
        sig=-ones(1,120);    % -1 value for binary input 0
    else
        sig=ones(1,120);     % +1 value for binary input 1
    end
    c=cos(time);             % Carrier frequency is calculated.  
    carrier_signal = [carrier_signal c];  %signal that is generated which will transmitted with input signal
    input_signal = [input_signal sig];    %Original signal to be transmitted
end



figure(1)
subplot(4,1,1);               
plot(input_signal);    % Plotting input signal
axis([-100 2400 -1.5 1.5]);   
title('\bf\it Original 20 bit Sequence');

% BPSK Modulation of the signal
bpsk_mod_signal=input_signal.*carrier_signal;   % Modulating the signal
subplot(4,1,2);   
plot(bpsk_mod_signal);  %Plotting BPSK Modulated signal
axis([-100 2400 -1.5 1.5]);
title('\bf\it BPSK Modulated Signal');

% Preparation of 6 new carrier frequencies
%6 frequencies are randomly selected by the PN sequence generator
time1=[0:2*pi/9:2*pi];  %[0:0.698:6.28]
time2=[0:2*pi/19:2*pi]; %[0:0.331:6.28]
time3=[0:2*pi/29:2*pi]; %[0:0.217:6.28]
time4=[0:2*pi/39:2*pi]; %[0:0.161:6.28]
time5=[0:2*pi/59:2*pi]; %[0:0.106:6.28]
time6=[0:2*pi/119:2*pi];%[0:0.052:6.28]
carrier1=cos(time1);
carrier1=[carrier1 carrier1 carrier1 carrier1 carrier1 carrier1 carrier1 carrier1 carrier1 carrier1 carrier1 carrier1];
carrier2=cos(time2);
carrier2=[carrier2 carrier2 carrier2 carrier2 carrier2 carrier2];
carrier3=cos(time3);
carrier3=[carrier3 carrier3 carrier3 carrier3];
carrier4=cos(time4);
carrier4=[carrier4 carrier4 carrier4];
carrier5=cos(time5);
carrier5=[carrier5 carrier5];
carrier6=cos(time6);

% Random frequency hopps to form a spread signal
spread_signal=[];
for n=1:20
    c=randi([1 6],1,1);     %6 frequencies are randomly are selected by the PN generator
    switch(c)
        case(1)
            spread_signal=[spread_signal carrier1];
        case(2)
            spread_signal=[spread_signal carrier2];
        case(3)
            spread_signal=[spread_signal carrier3];
        case(4)
            spread_signal=[spread_signal carrier4];
        case(5)        
            spread_signal=[spread_signal carrier5];
        case(6)
            spread_signal=[spread_signal carrier6];
    end
end
subplot(4,1,3)
plot([1:2400],spread_signal);
axis([-100 2400 -1.5 1.5]);
title('\bf\it Spread Signal with 6 frequencies');

% Spreading BPSK Signal
freq_hopped_sig=bpsk_mod_signal.*spread_signal;    %This is the signal which is being finallay transmitted
subplot(4,1,4)
plot([1:2400],freq_hopped_sig);
axis([-100 2400 -1.5 1.5]);
title('\bf\it Frequency Hopped Spread Spectrum Signal');      

% Demodulation of BPSK Signal
bpsk_demodulated=freq_hopped_sig./spread_signal;        %The received signal is FFH demodualted
figure(2)
subplot(2,1,1)
plot([1:2400],bpsk_demodulated);
axis([-100 2400 -1.5 1.5]);
title('\bf Demodulated BPSK Signal from Wide Spread');

original_BPSK_signal=bpsk_demodulated./carrier_signal;     %FFH demodulated signal is data demodulated by means of BPSK Signal 
subplot(2,1,2)
plot([1:2400],original_BPSK_signal);
axis([-100 2400 -1.5 1.5]);
title('\bf Transmitted Original Bit Sequence');
import java.util.*;

class Solution {
    private static void merge(int[] arr, int low, int mid, int high) {
        ArrayList<Integer> temp = new ArrayList<>();
        int left = low;
        int right = mid + 1;

        while (left <= mid && right <= high) {
            if (arr[left] <= arr[right]) {
                temp.add(arr[left]);
                left++;
            } else {
                temp.add(arr[right]);
                right++;
            }
        }

        while (left <= mid) {
            temp.add(arr[left]);
            left++;
        }

        while (right <= high) {
            temp.add(arr[right]);
            right++;
        }

        for (int i = low; i <= high; i++) {
            arr[i] = temp.get(i - low);
        }
    }

    public static void mergeSort(int[] arr, int low, int high) {
        if (low >= high) return;
        int mid = (low + high) / 2;
        mergeSort(arr, low, mid);
        mergeSort(arr, mid + 1, high);
        merge(arr, low, mid, high);
    }
}

public class tUf {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = 7;
        int arr[] = { 9, 4, 7, 6, 3, 1, 5 };
        System.out.println("Before sorting array: ");
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
        Solution.mergeSort(arr, 0, n - 1);
        System.out.println("After sorting array: ");
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }
}

import matplotlib.pyplot as plt

# Example data points: input sizes and their corresponding execution times
input_sizes = [1000, 5000, 10000, 50000, 100000]
execution_times_quick = [1.8, 9.5, 21.3, 110.7, 250.3]  # Replace these with actual results

plt.plot(input_sizes, execution_times_quick, marker='o', linestyle='-', color='r', label='Quick Sort')
plt.title('Quick Sort Time Complexity')
plt.xlabel('Input Size (n)')
plt.ylabel('Execution Time (ms)')
plt.grid(True)
plt.legend()
plt.show()
OFDM     clc; close all; clear all;

% Parameters
numsubcar = 64;          % Number of subcarriers
numofsym = 100;          % Number of OFDM symbols
cplen = 16;              % Cyclic prefix length
snrange = 0:2:20;        % SNR range in dB
ifft_size = numsubcar;   % IFFT size (equal to number of subcarriers)

% Generate random data bits
databits = randi([0, 1], numsubcar * numofsym, 1); % Generate random bits

% Plot the first 10 bits
figure;
subplot(4, 1, 1);
stem(databits(1:10));
xlabel('Bit Index');
ylabel('Bit Value');
title('Input Data Bits');

% BPSK Modulation (map 0 -> -1, 1 -> +1)
mod_data = 2 * databits - 1;

% Reshape modulated data to match subcarriers and symbols
mod_data = reshape(mod_data, numsubcar, numofsym);

% Perform IFFT
ifft_data = ifft(mod_data, ifft_size);

% Plot the IFFT (real part of the first symbol)
subplot(4, 1, 2);
plot(real(ifft_data(:, 1)));
xlabel('Sample Index');
ylabel('Amplitude');
title('IFFT Output (First Symbol)');

% Add Cyclic Prefix
ofdm_symbols = [ifft_data(end-cplen+1:end, :); ifft_data];

% Serialize OFDM symbols to form the transmit signal
tx_signal = ofdm_symbols(:);

% Plot the real part of the transmitted signal
subplot(4, 1, 3);
plot(real(tx_signal(1:200))); % Plot first 200 samples
xlabel('Sample Index');
ylabel('Amplitude');
title('Transmitted OFDM Signal');

% Initialize BER values
bervalues = zeros(size(snrange));

% Loop over SNR values to compute BER
for idx = 1:length(snrange)
    snr = snrange(idx);
    
    % Calculate signal power
    signal_power = mean(abs(tx_signal).^2);
    
    % Calculate noise power
    noise_power = signal_power / (10^(snr / 10));
    
    % Generate AWGN
    noise = sqrt(noise_power) * randn(size(tx_signal));
    
    % Add noise to the signal
    rx_signal = tx_signal + noise;
    
    % Reshape received signal to matrix form and remove cyclic prefix
    rx_ofdm_symbols = reshape(rx_signal, numsubcar + cplen, []);
    rx_ofdm_symbols = rx_ofdm_symbols(cplen+1:end, :);
    
    % Perform FFT on received symbols
    fft_data = fft(rx_ofdm_symbols, ifft_size);
    
    % BPSK Demodulation (decision rule: > 0 -> 1, <= 0 -> 0)
    demod_data = real(fft_data(:)) > 0;
    
    % Compute BER
    numerrors = sum(databits ~= demod_data);
    ber = numerrors / length(databits);
    bervalues(idx) = ber;
end

% Plot BER vs SNR
subplot(4, 1, 4);
semilogy(snrange, bervalues, '-o');
xlabel('SNR (dB)');
ylabel('BER');
title('BER vs. SNR for OFDM System');
grid on;
lambda=0.3;
ht100=100;
ht30=30;
ht2=2;
hr=2;
axis=[];
p100=[];
p30=[];
p2=[];
pfs1=[];
for i=1000:5000
    d=10^(i/1000);
    axis=[axis d];
    fspower=(lambda/(4*3.1415*d))^2;
    power100=fspower*4*(sin(2*3.1415*hr*ht100/(lambda*d)))^2;
    power30=fspower*4*(sin(2*3.1415*hr*ht30/(lambda*d)))^2;
    power2=fspower*4*(sin(2*3.1415*hr*ht2/(lambda*d)))^2;
    p100=[p100,10*log10(power100)];
    p30=[p30,10*log10(power30)];
    p2=[p2,10*log10(power2)];
    pfs1=[pfs1,10*log10(fspower)];
end
text('FontSize',18);
semilogx(axis,p100,'g-',axis,p30,'b-',axis,p2,'r',axis,pfs1,'y-');
xlabel('distance in m');
ylabel('pathloss');
text(1000,-66,'blue: hr=30m');
text(1000,-74,'red: hr=2m');
text(1000,-58,'green: hr=100m');
text(1000,-50,'yellow:freespace');
text(50,-180,'lambda=0.30m');
text(50,-190,'hr=2m');
//@version=5
indicator("LMR with Flat Candles and Rising/Falling Band Logic", overlay=true)

// --- Input for Donchian Channel Period ---
donchianPeriod = input.int(20, title="Donchian Channel Period", minval=1)
flatCandleCount = input.int(3, title="Number of Flat Candles", minval=1)  // Number of candles to check for flatness

// --- Donchian Channel Calculations ---
donchianHigh = ta.highest(high, donchianPeriod)
donchianLow = ta.lowest(low, donchianPeriod)
donchianMid = (donchianHigh + donchianLow) / 2

// --- Plot Donchian Channel ---
plot(donchianHigh, color=color.new(color.blue, 0), title="Donchian High")
plot(donchianLow, color=color.new(color.red, 0), title="Donchian Low")
plot(donchianMid, color=color.new(color.gray, 0), title="Donchian Midline", linewidth=1)

// --- Flat Candle Detection (Checking multiple candles for flatness) ---
isFlatCandle(candleIndex) =>
    math.abs(close[candleIndex] - close[candleIndex-1]) < (high[candleIndex] - low[candleIndex]) * 0.2  // Price change is small compared to range

flatCandles = true
for i = 1 to flatCandleCount
    flatCandles := flatCandles and isFlatCandle(i)  // All previous candles must be flat

// --- Current Band Movement Detection ---
isUpperBandRising = donchianHigh > donchianHigh[1]  // Upper band is rising in the current candle
isUpperBandFlat = donchianHigh == donchianHigh[1]  // Upper band is flat in the current candle
isLowerBandFalling = donchianLow < donchianLow[1]  // Lower band is falling in the current candle

// --- Debugging: Plot the band changes to visualize them ---
plotshape(isUpperBandRising, title="Upper Band Rising", location=location.abovebar, color=color.green, style=shape.triangledown, size=size.small)
plotshape(isUpperBandFlat, title="Upper Band Flat", location=location.abovebar, color=color.blue, style=shape.triangledown, size=size.small)
plotshape(isLowerBandFalling, title="Lower Band Falling", location=location.belowbar, color=color.red, style=shape.triangleup, size=size.small)

// --- Long Condition (Flat candles + Rising Upper Band) ---
longCondition = flatCandles and isUpperBandRising  // Flat candles and upper band rising in current candle

// --- Short Condition (Flat candles + Falling Lower Band + Upper Band Flat) ---
shortCondition = flatCandles and isUpperBandFlat and isLowerBandFalling  // Flat candles and upper band flat + lower band falling

// --- Plot Background Colors for Signals ---
bgcolor(longCondition ? color.new(color.green, 90) : na, title="Long Condition Signal")
bgcolor(shortCondition ? color.new(color.red, 90) : na, title="Short Condition Signal")

// --- Plot Arrows for Signals ---
plotshape(longCondition, title="Long Signal Arrow", location=location.belowbar, color=color.green, style=shape.arrowup, size=size.small)
plotshape(shortCondition, title="Short Signal Arrow", location=location.abovebar, color=color.red, style=shape.arrowdown, size=size.small)

// --- Alerts ---
alertcondition(longCondition, title="Long Signal Alert", message="Flat candles detected, and upper band is rising.")
alertcondition(shortCondition, title="Short Signal Alert", message="Flat candles detected, and upper band is flat and lower band is falling.")

import java.util.Scanner;

public class QuickSort {
    
    public static void quickSort(int[] a, int lb, int ub) {
        if (lb < ub) {
            int pivotIndex = partition(a, lb, ub);
            quickSort(a, lb, pivotIndex - 1);
            quickSort(a, pivotIndex + 1, ub);
        }
    }

    public static int partition(int[] a, int lb, int ub) {
        int pivot = a[lb];
        int start = lb;
        int end = ub;
        while (start < end) {
            while (start <= ub && a[start] <= pivot) {
                start++;
            }
            while (a[end] > pivot) {
                end--;
            }
            if (start < end) {
                int temp = a[start];
                a[start] = a[end];
                a[end] = temp;
            }
        }
        int temp = a[end];
        a[end] = a[lb];
        a[lb] = temp;
        return end;
    }

    public static void display(int[] a) {
        System.out.println("Sorted array:");
        for (int i : a) {
            System.out.print(i + "\t");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter array size:");
        int n = sc.nextInt();
        int[] a = new int[n];
        
        System.out.println("Enter elements into array:");
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        
        quickSort(a, 0, n - 1);
        display(a);
        
        sc.close();
    }
}

import matplotlib.pyplot as plt
import numpy as np

n = np.linspace(1, 1000, 100)
best_case = n * np.log2(n) 
average_case = n * np.log2(n)  
worst_case = n ** 2  

plt.figure(figsize=(10, 6))
plt.plot(n, best_case, label='Best Case (O(n log n))', color='green')
plt.plot(n, average_case, label='Average Case (O(n log n))', color='blue')
plt.plot(n, worst_case, label='Worst Case (O(n^2))', color='red')

plt.title('Quick Sort Time Complexity')
plt.xlabel('Input Size (n)')
plt.ylabel('Number of Operations')
plt.legend()
plt.grid(True)
plt.show()

% Parameters
bitStream = [1 0 1 1 0 1];  % Example bit stream
chipSequence = [1 -1 1 -1]; % Example chip sequence
 
% DSSS Encoding (Spreading)
spreadSignal = dsss_spread(bitStream, chipSequence);
 
% DSSS Decoding (Despreading)
recoveredBits = dsss_despread(spreadSignal, chipSequence);
 
% Display results
disp('Original bit stream:');
disp(bitStream);
disp('Spread signal:');
disp(spreadSignal);
disp('Recovered bit stream:');
disp(recoveredBits);
 
 
% Function for DSSS Spreading(dsss_spread.m)
function spreadSignal = dsss_spread(bitStream, chipSequence)
    numBits = length(bitStream);
    numChips = length(chipSequence);
    spreadSignal = zeros(1, numBits * numChips);
    
    idx = 1;
    for bit = bitStream
        % Encode each bit with the chip sequence
        if bit == 0
            spreadSignal(idx:idx+numChips-1) = -chipSequence;
        else
            spreadSignal(idx:idx+numChips-1) = chipSequence;
        end
        idx = idx + numChips;
    end
end

% Function for DSSS Despreading(dsss_despread.m)
function recoveredBits = dsss_despread(spreadSignal, chipSequence)
    numChips = length(chipSequence);
    numBits = length(spreadSignal) / numChips;
    recoveredBits = zeros(1, numBits);
    
    for i = 1:numBits
        % Extract the corresponding chips
        chipValues = spreadSignal((i-1)*numChips + :i*numChips);
        
        % Perform correlation with the chip sequence
        correlation = dot(chipValues, chipSequence);
        
        % Decision logic based on correlation
        if correlation > 0
            recoveredBits(i) = 1;
        else
            recoveredBits(i) = 0;
        end
    end
end
import java.util.*; 
 
public class ShortestPath { 
    public static void main(String[] args) { 
        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter number of vertices: "); 
        int n = sc.nextInt(); 
        System.out.println("Enter the adjacency matrix: "); 
        int[][] g = new int[n][n]; 
        for (int i = 0; i < n; i++) { 
            for (int j = 0; j < n; j++) { 
                g[i][j] = sc.nextInt(); 
            } 
        } 
 
        System.out.println("Enter source vertex: "); 
        int v = sc.nextInt(); 
        dijkstras(v, g, n); 
    } 
 
    public static void dijkstras(int v, int[][] cost, int n) { 
        boolean[] s = new boolean[n]; 
        int[] dist = new int[n]; 
        for (int i = 0; i < n; i++) { 
            dist[i] = cost[v][i] == 0 ? Integer.MAX_VALUE : cost[v][i]; 
            s[i] = false; 
        } 
 
        s[v] = true; 
        dist[v] = 0; 
 
        for (int i = 1; i < n - 1; i++) { 
            int u = minDist(dist, s); 
            s[u] = true; 
 
            for (int w = 0; w < n; w++) { 
                if (!s[w] && cost[u][w] != 0) { 
                    if (dist[w] > dist[u] + cost[u][w]) { 
                        dist[w] = dist[u] + cost[u][w]; 
                    } 
                } 
            } 
        } 
 
        System.out.println("Shortest distances from source " + v + " :"); 
        for (int i = 0; i < n; i++) { 
            System.out.println("To node " + i + " - Distance : " + dist[i]); 
        } 
    } 
 
    private static int minDist(int[] dis, boolean[] s) { 
        int min = Integer.MAX_VALUE, idx = -1; 
 
        for (int i = 0; i < dis.length; i++) { 
            if (!s[i] && dis[i] <= min) { 
                min = dis[i]; 
                idx = i; 
            } 
        } 
        return idx; 
    } 
}
import java.util.*; 
 
public class OBST { 
    public static void bst(double[] p, double[] q, int n) { 
        double[][] w = new double[n + 1][n + 1]; 
        double[][] c = new double[n + 1][n + 1]; 
        int[][] r = new int[n + 1][n + 1]; 
 
        for (int i = 0; i <= n; i++) { 
            w[i][i] = q[i]; 
            c[i][i] = 0; 
            r[i][i] = 0; 
        } 
 
        for (int m = 1; m <= n; m++) { 
            for (int i = 0; i <= n - m; i++) { 
                int j = i + m; 
                w[i][j] = w[i][j - 1] + p[j] + q[j]; 
                double mincost = Double.MAX_VALUE; 
                int root = -1; 
 
                for (int k = (i < j - 1 ? r[i][j - 1] : i); k <= (j > i + 1 ? r[i + 1][j] : j); k++) { 
                    double cost = (i <= k - 1 ? c[i][k - 1] : 0) + (k <= j ? c[k][j] : 0) + w[i][j]; 
                    if (cost < mincost) { 
                        mincost = cost; 
                        root = k; 
                    } 
                } 
 
                c[i][j] = mincost; 
                r[i][j] = root; 
            } 
        } 
 
        System.out.println("Minimum cost: " + c[0][n]); 
        System.out.println("Weight : " + w[0][n]); 
    } 
 
    public static void main(String[] args) { 
        Scanner sc = new Scanner(System.in); 
        System.out.print("Enter the number of keys: "); 
        int n = sc.nextInt(); 
 
        double[] p = new double[n + 1]; 
        double[] q = new double[n + 1]; 
 
        System.out.println("Enter probabilities for the keys:"); 
        for (int i = 1; i <= n; i++) { 
            System.out.print("p[" + i + "]: "); 
            p[i] = sc.nextDouble(); 
        } 
 
        System.out.println("Enter probabilities for the dummy keys:"); 
        for (int i = 0; i <= n; i++) { 
            System.out.print("q[" + i + "]: "); 
            q[i] = sc.nextDouble(); 
        } 
 
        bst(p, q, n); 
    } 
}
% Clear workspace, close figures, clear command window
clear all;
close all;
clc;

% Parameters
n = 10;              % Number of symbols
m = 4;               % QPSK has 4 symbols (0, 1, 2, 3)
snr = 20;            % Signal-to-Noise Ratio (dB)
bit_rate = 10^3;     % Bit rate in bits per second
f = bit_rate;        % Carrier frequency
tb = 1 / bit_rate;   % Bit duration
t = 0:(tb/1000):tb;  % Time vector for one symbol

% Generate random data
data = randi([0 m-1], 1, n); % Random symbols (0, 1, 2, 3)

% Perform QPSK modulation
s = exp(1j * (2 * pi * data / m + pi/4)); % QPSK symbols with phase offset of pi/4

% Generate the transmitted QPSK signal
txsig = []; % Initialize transmitted signal
for l = 1:length(data)
    % Modulate using I and Q components
    tx = real(s(l)) * cos(2 * pi * f * t) - imag(s(l)) * sin(2 * pi * f * t);
    txsig = [txsig tx]; % Append the modulated signal for the current symbol
end

% Add noise to the transmitted signal (Noisy QPSK signal)
rxsig = txsig + sqrt(0.5 / (10^(snr/10))) * randn(size(txsig)); % Add noise to the real part

% Add noise to QPSK symbols for constellation diagram
r = s + sqrt(0.5 / (10^(snr/10))) * (randn(size(s)) + 1j * randn(size(s)));

% Plot results
figure;

% Plot message signal (original symbols)
subplot(3, 1, 1);
stairs(data, 'LineWidth', 1.5); % Staircase plot for message symbols
grid minor;
ylim([-0.5, m-0.5]); 
xlim([0, n]);
title('Message Signal (Symbols)');
xlabel('Symbol Index');
ylabel('Symbol Value');

% Plot QPSK modulated signal
subplot(3, 1, 2);
plot(txsig, 'LineWidth', 1.5);
grid minor;
title('QPSK Modulated Signal');
xlabel('Time (samples)');
ylabel('Amplitude');
ylim([-1.5, 1.5]);
xlim([0, length(txsig)]);

% Plot noisy QPSK modulated signal
subplot(3, 1, 3);
plot(rxsig, 'LineWidth', 1.5);
grid minor;
title('Noisy QPSK Signal (AWGN Added)');
xlabel('Time (samples)');
ylabel('Amplitude');
xlim([0, length(rxsig)]);

% Constellation diagram
figure;
scatter(real(r), imag(r), 'filled'); % Scatter plot of noisy received symbols
grid minor;
title('Constellation Diagram of QPSK');
xlabel('In-phase (I)');
ylabel('Quadrature (Q)');
axis([-2 2 -2 2]); % Set axis limits for clarity
import java.util.*; 
 
class Job { 
    private int id; 
    private int deadline; 
    private int profit; 
 
    Job(int id, int deadline, int profit) { 
        this.id = id; 
        this.deadline = deadline; 
        this.profit = profit; 
    } 
 
    public int getId() { 
        return id; 
    } 
 
    public int getDeadline() { 
        return deadline; 
    } 
 
    public int getProfit() { 
        return profit; 
    } 
} 
 
public class JobSeq { 
    public static void main(String[] args) { 
        Scanner scan = new Scanner(System.in); 
        System.out.println("enter no of jobs"); 
        int n = scan.nextInt(); 
        Job[] jobs = new Job[n]; 
        System.out.println("emter job id,deadline,profit"); 
        for (int i = 0; i < n; i++) { 
            jobs[i] = new Job(scan.nextInt(), scan.nextInt(), scan.nextInt()); 
        } 
        js(jobs); 
    } 
 
    public static void js(Job[] jobs) { 
        Arrays.sort(jobs, new Comparator<Job>() { 
            public int compare(Job j1, Job j2) { 
                return j2.getProfit() - j1.getProfit(); 
            } 
        }); 
 
        int maxDeadline = 0; 
        for (Job job : jobs) { 
            if (job.getDeadline() > maxDeadline) { 
                maxDeadline = job.getDeadline(); 
            } 
        } 
 
        Job[] result = new Job[maxDeadline]; 
        boolean[] slot = new boolean[maxDeadline]; 
 
        for (Job job : jobs) { 
            for (int j = Math.min(maxDeadline, job.getDeadline()) - 1; j >= 0; j--) { 
                if (!slot[j]) { // If the slot is free 
                    result[j] = job; 
                    slot[j] = true; 
                    break; 
                } 
            } 
        } 
 
        int totalProfit = 0; 
        System.out.println("Scheduled jobs:"); 
        for (Job job : result) { 
            if (job != null) { 
                System.out.println("Job ID: " + job.getId() + ", Profit: " + job.getProfit()); 
                totalProfit += job.getProfit(); 
            } 
        } 
        System.out.println("Total profit: " + totalProfit); 
    } 
 
} 
import java.util.*; 
 
public class Knapsack { 
    public static double greedyKnapSack(ItemValue[] arr, int capacity) { 
        Arrays.sort(arr, new Comparator<ItemValue>() { 
            public int compare(ItemValue item1, ItemValue item2) { 
                double cpr1 = (double) item1.profit / item1.weight; 
                double cpr2 = (double) item2.profit / item2.weight; 
 
                if (cpr1 < cpr2) 
                    return 1; 
                else 
                    return -1; 
 
            } 
        }); 
 
        double total = 0; 
 
        for (ItemValue i : arr) { 
            if ((capacity - i.weight) >= 0) { 
                capacity -= i.weight; 
                total += i.profit; 
            } else { 
                double fract = (double) capacity / (double) i.weight; 
                total += fract * (i.profit); 
                capacity = 0; 
                break; 
            } 
        } 
        return total; 
    } 
 
    public static void main(String[] args) { 
        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter the number of items: "); 
        int n = sc.nextInt(); 
        ItemValue[] arr = new ItemValue[n]; 
        System.out.println("Enter weight, profit of each item: "); 
        for (int i = 0; i < n; i++) { 
            arr[i] = new ItemValue(sc.nextInt(), sc.nextInt()); 
        } 
        System.out.println("Enter capacity :"); 
        int m = sc.nextInt(); 
 
        double pro = greedyKnapSack(arr, m); 
        System.out.println(pro); 
    } 
 
} 
 
class ItemValue { 
    public int weight; 
    public int profit; 
 
    public ItemValue(int weight, int profit) { 
        this.weight = weight; 
        this.profit = profit; 
    } 
 
} 
#include<stdio.h>

void merge(int a[],int b[],int low,int mid,int high){
    int h = low;
    int j = mid+1;
    int i = low;
    while(h<=mid && j<=high){
        if(a[h]<=a[j]){
            b[i] = a[h];
            h += 1;
        }
        else{
            b[i] = a[j];
            j += 1;
        }
        i += 1;
    }
    if(h>mid){
        for(int k=j;k<=high;k++){
            b[i] = a[k];
            i += 1;
        }
    }
    else{
        for(int k=h;k<=mid;k++){
            b[i] = a[k];
            i += 1;
        }
    }
    for(int k=low;k<=high;k++){
        a[k] = b[k];
    }
}

void mergeSort(int a[],int b[] , int low,int high){
    if(low<high){
        int mid = (low+high)/2;
        mergeSort(a,b,low,mid);
        mergeSort(a,b,mid+1,high);
        merge(a,b,low,mid,high);
    }
}

int main(){
    int n;
    printf("\n Enter size:");
    scanf("%d",&n);
    int a[n],b[n];
    printf("\n Enter elements:");
    for(int i = 0 ;i<n;i++){
        scanf("%d",&a[i]);
    }
    mergeSort(a,b,0,n-1);
    printf("\n Sorted Elements:");
    for(int i=0;i<n;i++){
        printf("%d \t",a[i]);
    }
    printf("\n");
    return 0;
}
#include<stdio.h>

void interchange(int a[],int i,int j){
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

int partition(int a[],int p, int q){
    int v = a[p];
    int i = p,j = q+1;
    do{
        do{
            i = i+1;
        }while(a[i]<v &&  i<=q);
        
        do{
            j = j-1;
        }while(a[j]>v && j>=p);
        
        if(i<j){
            interchange(a,i,j);
        }
    }while(i<j);
    
    interchange(a,p,j);
    return j;
}

void quickSort(int a[] ,int p, int q){
    if(p<q){
        int j = partition(a,p,q);
        quickSort(a,p,j-1);
        quickSort(a,j+1,q);
    }
}

int main(){
    int n;
    printf("\n Enter size:");
    scanf("%d",&n);
    int a[n];
    printf("Enter elements:");
    for(int i=0;i<n;i++){
        scanf("%d",&a[i]);
    }
    quickSort(a,0,n-1);
    printf("\n Sorted Array:");
    for(int i=0;i<n;i++){
        printf("%d \t",a[i]);
    }
    printf("\n");
    return 0;
}

import pandas as pd
from sklearn.preprocessing import MinMaxScaler

data = {'Age': [20, 25, 30, 35, 40],
 'Salary': [20000, 25000, 30000, 35000, 40000]}

df = pd.DataFrame(data)

scaler = MinMaxScaler()


df[['Age_minmax', 'Salary_minmax']] = scaler.fit_transform(df[['Age', 'Salary']])
print(df)
from sklearn.preprocessing import StandardScaler
import pandas as pd

data = {'Age': [20, 25, 30, 35, 40],
 'Salary': [20000, 25000, 30000, 35000, 40000]}

df = pd.DataFrame(data)

scaler = StandardScaler()

df[['Age_scaled', 'Salary_scaled']] = scaler.fit_transform(df[['Age', 'Salary']])
print(df)
from sklearn.preprocessing import OrdinalEncoder

data = {'Size': ['Small', 'Medium', 'Large', 'Medium']}
df = pd.DataFrame(data)

encoder = OrdinalEncoder(categories=[['Small', 'Medium', 'Large']])

df['Size_encoded'] = encoder.fit_transform(df[['Size']])
print(df)
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
data = {
  'City': ['New York', 'Los Angeles', 'Chicago']
		}

df = pd.DataFrame(data)
df_encoded = OneHotEncoder()
df_encoded = pd.get_dummies(df, columns=['City'])
print(df_encoded)
import pandas as pd
from sklearn.preprocessing import LabelEncoder
# Sample DataFrame
data = {'City': ['New York', 'Los Angeles', 'Chicago', 'New York']}
df = pd.DataFrame(data)
# Initialize the label encoder
label_encoder = LabelEncoder()
# Fit and transform the 'City' column
df['City_encoded'] = label_encoder.fit_transform(df['City'])
print(df)
SumOfSub(s, k, r)
{
    // Generate left child
    x[k] = 1
    if (s + w[k] == m) then
        write(x[1 : k]) // Subset found
    else if (s + w[k] + w[k + 1] <= m) then
        SumOfSub(s + w[k], k + 1, r - w[k])

    // Generate right child and evaluate conditions
    if ((s + r - w[k] >= m) and (s + w[k + 1] <= m)) then
    {
        x[k] = 0
        SumOfSub(s, k + 1, r - w[k])
    }
}
star

Tue Nov 19 2024 04:41:24 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 04:40:19 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 04:39:45 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 02:58:49 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Tue Nov 19 2024 02:51:44 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 02:51:13 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 02:50:42 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 02:50:13 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 02:49:48 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 02:49:17 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 02:48:48 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 02:48:15 GMT+0000 (Coordinated Universal Time)

@login123

star

Tue Nov 19 2024 02:44:19 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Tue Nov 19 2024 02:37:16 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Tue Nov 19 2024 01:53:35 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Tue Nov 19 2024 01:09:33 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Tue Nov 19 2024 01:08:19 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Tue Nov 19 2024 00:57:58 GMT+0000 (Coordinated Universal Time)

@shahmeeriqbal

star

Tue Nov 19 2024 00:57:39 GMT+0000 (Coordinated Universal Time)

@shahmeeriqbal

star

Tue Nov 19 2024 00:27:43 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Mon Nov 18 2024 21:20:35 GMT+0000 (Coordinated Universal Time)

@signin

star

Mon Nov 18 2024 20:46:29 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 20:35:31 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 20:17:40 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 19:09:41 GMT+0000 (Coordinated Universal Time)

@pk20

star

Mon Nov 18 2024 19:08:49 GMT+0000 (Coordinated Universal Time)

@pk20

star

Mon Nov 18 2024 19:00:54 GMT+0000 (Coordinated Universal Time)

@zily

star

Mon Nov 18 2024 18:49:50 GMT+0000 (Coordinated Universal Time)

@lord

star

Mon Nov 18 2024 18:37:36 GMT+0000 (Coordinated Universal Time)

@lord

star

Mon Nov 18 2024 18:07:42 GMT+0000 (Coordinated Universal Time)

@lord

star

Mon Nov 18 2024 17:54:53 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 17:47:54 GMT+0000 (Coordinated Universal Time)

@lord

star

Mon Nov 18 2024 17:46:48 GMT+0000 (Coordinated Universal Time)

@lord

star

Mon Nov 18 2024 17:38:48 GMT+0000 (Coordinated Universal Time)

@pk20

star

Mon Nov 18 2024 17:34:22 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 17:32:37 GMT+0000 (Coordinated Universal Time)

@lord

star

Mon Nov 18 2024 17:32:13 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 17:31:15 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 17:28:49 GMT+0000 (Coordinated Universal Time)

@lord

star

Mon Nov 18 2024 17:28:37 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 17:25:43 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 17:24:39 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 17:23:21 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 16:02:00 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 15:59:00 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 15:52:32 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 15:48:11 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 15:41:11 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 15:25:33 GMT+0000 (Coordinated Universal Time)

@wtlab

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension