Snippets Collections
Task-3
Implement Job Sequencing with deadlines algorithm
Algorithm
Algorithm GreedyJob(d, J, n)
// J is a set of jobs that can be completed by their deadlines.
{
  J := {1};
  for i := 2 to n do
  {
    if (all jobs in J ∪ {i} can be completed
        by their deadlines) then J := J ∪ {i};
  }
}
AlgorithmJS(d,j,n)
{
 // d[i] >1,1<i <n arethedeadlines, n >1.Thejobs
 // areorderedsuchthat p[\\] >p[2]>>......p[n].J[i]
 // istheith jobin theoptimalsolution,1<i <k.
 // Also,at terminationd[J[i]] <d[J[i+1]], 1<i <k.
  {
d[0] := J[0] := 0; // Initialize.
J[1] := 1; // Include job 1.
k := 1;
for i := 2 to n do
{
    // Consider jobs in nonincreasing order of p[i]. Find
    // position for i and check feasibility of insertion.
    r := k;
    while ((d[J[r]] > d[i]) and (d[J[r]] ≠ r)) do r := r - 1;
    if ((d[J[r]] ≤ d[i]) and (d[i] > r)) then
    {
        // Insert i into J[ ].
        for q := k to (r + 1) step -1 do J[q + 1] := J[q];
        J[r + 1] := i; k := k + 1;
    }
}
return k;
}
Program:
class Job:
    def __init__(self, job_id, deadline, profit):
        self.job_id = job_id
        self.deadline = deadline
        self.profit = profit

# Function to schedule jobs to maximize profit
def job_sequencing(jobs):
    # Step 1: Sort jobs by profit in descending order
    jobs.sort(key=lambda job: job.profit, reverse=True)
    
    # Step 2: Initialize an array to keep track of free time slots
    max_deadline = max(job.deadline for job in jobs)
    slots = [-1] * max_deadline  # -1 indicates the slot is free
    
    total_profit = 0
    job_sequence = []
    
    # Step 3: Place jobs in available slots to maximize profit
    for job in jobs:
        # Find a slot for the job, starting from the latest possible slot (deadline)
        for j in range(min(job.deadline, max_deadline) - 1, -1, -1):
            if slots[j] == -1:
                # Slot found
                slots[j] = job.job_id
                job_sequence.append(job.job_id)
                total_profit += job.profit
                break
    
    # Output the sequence and profit
    return job_sequence, total_profit

# Example usage
jobs = [
    Job('Job1', 2, 100),
    Job('Job2', 1, 50),
    Job('Job3', 2, 10),
    Job('Job4', 1, 20),
    Job('Job5', 3, 15)
]

# Get the job sequence and total profit
sequence, profit = job_sequencing(jobs)
print("Job sequence:", sequence)
print("Total Profit:", profit)
OUTPUT:
Job Sequence: ['Job1', 'Job2', 'Job5']
Total Profit: 165


(VIVEK'S CODE)
# greedy job sequencing

def greedyJS(d,j,n):
    d[0]=j[0]=0
    j[1]=1
    k=1
    for i in range(2,n):
        r = k
        while d[j[r]]>d[i] and d[j[r]]!=r:
            r-=1
        if d[j[r]]<=d[i] and d[i]>r:
            for q in range(r+1,k-1,-1):
                j[q+1]=j[q]
            j[r+1]=i
            k+=1
    return k
            

def sort(p,d,n):
    for i in range(1,n):
        k = i
        m = p[i]
        for j in range(i+1,n):
            if(p[j]>m):
                m = p[j]
                k = j
        if i!=k:
            d[i],d[k] = d[k],d[i]
            p[i],p[k] = p[k],p[i]

n = int(input())
p = [-1]*(n+1)
d = [-1]*(n+1)
for i in range(1,n+1):
    p[i],d[i] = map(int,input().split())
sort(p,d,n+1)
print(p[1:])
print(d[1:])
j = [0]*(n+1)
k = greedyJS(d,j,n+1)
print(k)
for i in range(1,k+1):
    print(j[i],end=" ")
print()
profit = 0
for i in range(1,k+1):
    profit+=p[j[i]]
print(profit)

'''
INPUT:
5
15 2
20 2
10 1
1 3
5 3

OUTPUT:
[20, 15, 10, 5, 1]
[2, 2, 1, 3, 3]
3
1 2 4
40
'''
//SQL:
CREATE TABLE Users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL
);

//INSERT
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class InsertUser {
    private static final String INSERT_USER_SQL = "INSERT INTO Users (username, password, email) VALUES (?, ?, ?)";

    public static void main(String[] args) {
        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
             PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USER_SQL)) {

            preparedStatement.setString(1, "john_doe");
            preparedStatement.setString(2, "securepassword");
            preparedStatement.setString(3, "john@example.com");

            int rowsAffected = preparedStatement.executeUpdate();
            System.out.println(rowsAffected + " row(s) inserted.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

//SELECT
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class SelectUsers {
    private static final String SELECT_ALL_USERS_SQL = "SELECT * FROM Users";

    public static void main(String[] args) {
        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
             PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_USERS_SQL);
             ResultSet resultSet = preparedStatement.executeQuery()) {

            while (resultSet.next()) {
                System.out.println("ID: " + resultSet.getInt("id") +
                                   ", Username: " + resultSet.getString("username") +
                                   ", Email: " + resultSet.getString("email"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

//UPDATE
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class UpdateUserEmail {
    private static final String UPDATE_EMAIL_SQL = "UPDATE Users SET email = ? WHERE username = ?";

    public static void main(String[] args) {
        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
             PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_EMAIL_SQL)) {

            preparedStatement.setString(1, "new_email@example.com");
            preparedStatement.setString(2, "john_doe");

            int rowsAffected = preparedStatement.executeUpdate();
            System.out.println(rowsAffected + " row(s) updated.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

//OUTPUT:
ID: 1, Username: john_doe, Email: john@example.com
package login;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * Servlet implementation class RequestExample
 */
@WebServlet("/RequestExample")
public class RequestExample extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RequestExample() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void init(ServletConfig config) throws ServletException
    {
    	super.init(config);
    	System.out.println("initialised");
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		response.setContentType("text/html");
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String course = request.getParameter("course");
		String branch = request.getParameter("branch");
		String hobbies = request.getParameter("hobbies");
		String fname = request.getParameter("fname");
		PrintWriter out = response.getWriter();
		out.println("<html><body>");
		out.println("<h2>Welcome"+name+"</h2>");
		out.println("<h2>Email: "+email+"</h2>");
		out.println("<h2>Course: "+course+"</h2>");
		out.println("<h2>"+branch+"</h2>");
		out.println("<h2>"+hobbies+"</h2>");
		out.println("<h2>"+fname+"</h2>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	public void destroy() {
		System.out.println("Destory");
	}
}


<html>
 
<body>
 
<form action="UserServlet" method="POST">
 
Name: <input type="text" name="name"><br>
 
Email: <input type="text" name="email"><br>
 
Course: <input type="text" name="course"><br>
 
Branch: <input type="text" name="branch"><br>
 
Hobbies: <input type="text" name="hobbies"><br>
 
<input type="submit" value="Submit">
 
</form>
 
</body>
 
</html>
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sorting and Reversing Arrays</title>
</head>
<body>
    <h1>Sorting and Reversing Arrays</h1>
    <pre id="output"></pre> <!-- Preformatted text area for output -->

    <script>
        // Define an array of numbers
        const numbers = [4, 2, 5, 1, 3];
        let result = "Original Numbers: " + numbers.join(", ") + "\n";

        // Sort numbers in ascending order
        const sortedNumbers = [...numbers].sort((a, b) => a - b);
        result += "Sorted Numbers (Ascending): " + sortedNumbers.join(", ") + "\n";

        // Reverse the sorted numbers
        const reversedNumbers = [...sortedNumbers].reverse();
        result += "Reversed Numbers: " + reversedNumbers.join(", ") + "\n\n";

        // Define an array of fruits
        const fruits = ["Banana", "Orange", "Apple", "Mango"];
        result += "Original Fruits: " + fruits.join(", ") + "\n";

        // Sort fruits alphabetically
        const sortedFruits = [...fruits].sort();
        result += "Sorted Fruits: " + sortedFruits.join(", ") + "\n";

        // Reverse the sorted fruits
        const reversedFruits = [...sortedFruits].reverse();
        result += "Reversed Fruits: " + reversedFruits.join(", ");

        // Display the result in the HTML page
        document.getElementById("output").textContent = result;
    </script>
</body>
</html>
package com.example;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

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


@WebServlet(description = "Checks the hard coded UserName and Password by the user credentials", urlPatterns = { "/LoginServletNew" })
public class LoginServletNew extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String validUsername = "Ramesh";
   private final String validPassword = "chand#123";
   public LoginServletNew() {
       super();
       System.out.println("Servlet Constructor is called once @ instantiation");
   }

   @Override
   protected void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {


       String username = request.getParameter("username");
       String password = request.getParameter("password");


       if (validUsername.equals(username) && validPassword.equals(password)) {

           response.setContentType("text/html");
           PrintWriter out = response.getWriter();
           

           SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
           Date date = new Date();
           
           out.println("<html><body>");
           out.println("<h1>Welcome, " + username + "!</h1>");
           out.println("<p>Current Date and Time: " + formatter.format(date) + "</p>");
           out.println("</body></html>");
       } else {
     
           response.setContentType("text/html");
           PrintWriter out = response.getWriter();
           out.println("<html><body>");
           out.println("<h1>Invalid username or password!</h1>");
           out.println("<a href=\"LoginServletNew.html\">Try Again</a>");
           out.println("</body></html>");
       }
   }

}

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   <h2>Login Page</h2>
   <form action="LoginServletNew" method="post">
       <label for="username">Username:</label>
       <input type="text" id="username" name="username" required><br><br>
       <label for="password">Password:</label>
       <input type="password" id="password" name="password" required><br><br>
       <input type="submit" value="Login">
   </form>
</body>
</html>\
package Manish;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * Servlet implementation class LifeCycleExample
 */
@WebServlet("/LifeCycleExample")
public class LifeCycleExample extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LifeCycleExample() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		System.out.println("Iam from init() method");
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("Iam from destroy() method");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		response.setContentType("text/html");
		try(PrintWriter out = response.getWriter())
		{
			out.println("<h3>Response from doGet() method</h3>");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
		response.setContentType("text/html");
		try(PrintWriter out = response.getWriter())
		{
			out.println("<h3>Response from doPost() method</h3>");
		}
	}

}
<!--DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Company Information</title>
</head>
<body>
    <h1>Company Information</h1>
    <pre id="output"></pre>

    <script>
        // Define a nested object for a company
        const company = {
            name: "GeeksforGeeks",
            location: "Noida",
            employees: {
                count: 100,
                departments: ["Development", "Design", "Marketing"],
                details: [
                    { name: "John Doe", position: "Developer" },
                    { name: "Jane Smith", position: "Designer" }
                ]
            }
        };

        // Function to display company information
        function displayCompanyInfo(company) {
            let output = "";
            output += "Company Name: " + company.name + "\n";
            output += "Location: " + company.location + "\n";
            output += "Employee Count: " + company.employees.count + "\n";
            output += "Departments: " + company.employees.departments.join(", ") + "\n\n";
            output += "Employee Details:\n";
            company.employees.details.forEach(employee => {
                output += `- ${employee.name}, Position: ${employee.position}\n`;
            });
            return output;
        }

        // Function to add a new employee
        function addEmployee(company, employeeName, employeePosition) {
            const newEmployee = { name: employeeName, position: employeePosition };
            company.employees.details.push(newEmployee);
            company.employees.count++;
        }

        // Function to update the department list
        function addDepartment(company, departmentName) {
            if (!company.employees.departments.includes(departmentName)) {
                company.employees.departments.push(departmentName);
                return `Department "${departmentName}" added.`;
            } else {
                return `Department "${departmentName}" already exists.`;
            }
        }

        // Display original company info
        let result = "Original Company Information:\n";
        result += displayCompanyInfo(company);

        // Add a new employee
        addEmployee(company, "Alice Johnson", "Project Manager");
        result += "\nAfter Adding New Employee:\n";
        result += displayCompanyInfo(company);

        // Add a new department
        result += addDepartment(company, "Sales") + "\n";
        result += "\nAfter Adding New Department:\n";
        result += displayCompanyInfo(company);

        // Attempt to add an existing department
        result += addDepartment(company, "Development") + "\n";

        // Display the result in the HTML page
        document.getElementById("output").textContent = result;
    </script>
</body>
</html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Company Info</title>
</head>
<body>
    <h1>Company Information</h1>
    <pre id="output"></pre>

    <script>
        // Define a simple nested object for a company
        const company = {
            name: "GeeksforGeeks",
            location: "Noida",
            employees: {
                count: 100,
                departments: ["Development", "Design", "Marketing"]
            }
        };

        // Function to display company information
        function displayCompanyInfo(company) {
            return `Company Name: ${company.name}\nLocation: ${company.location}\nEmployee Count: ${company.employees.count}\nDepartments: ${company.employees.departments.join(", ")}`;
        }

        // Display the company information in the HTML page
        document.getElementById("output").textContent = displayCompanyInfo(company);
    </script>
</body>
</html>
// Define a nested object for a company
const company = {
    name: "GeeksforGeeks",
    location: "Noida",
    employees: {
        count: 100,
        departments: ["Development", "Design", "Marketing"],
        details: [
            { name: "John Doe", position: "Developer" },
            { name: "Jane Smith", position: "Designer" }
        ]
    }
};

// Function to display company information
function displayCompanyInfo(company) {
    console.log("Company Name:", company.name);
    console.log("Location:", company.location);
    console.log("Employee Count:", company.employees.count);
    console.log("Departments:", company.employees.departments.join(", "));
    
    console.log("Employee Details:");
    company.employees.details.forEach(employee => {
        console.log(`- ${employee.name}, Position: ${employee.position}`);
    });
}

// Function to add a new employee
function addEmployee(company, employeeName, employeePosition) {
    const newEmployee = { name: employeeName, position: employeePosition };
    company.employees.details.push(newEmployee);
    company.employees.count++;
}

// Function to update the department list
function addDepartment(company, departmentName) {
    if (!company.employees.departments.includes(departmentName)) {
        company.employees.departments.push(departmentName);
        console.log(`Department "${departmentName}" added.`);
    } else {
        console.log(`Department "${departmentName}" already exists.`);
    }
}

// Display original company info
console.log("Original Company Information:");
displayCompanyInfo(company);

// Add a new employee
addEmployee(company, "Alice Johnson", "Project Manager");
console.log("\nAfter Adding New Employee:");
displayCompanyInfo(company);

// Add a new department
addDepartment(company, "Sales");
console.log("\nAfter Adding New Department:");
displayCompanyInfo(company);

// Attempt to add an existing department
addDepartment(company, "Development");

/*OUTPUT
Original Company Information:
Company Name: GeeksforGeeks
Location: Noida
Employee Count: 100
Departments: Development, Design, Marketing
Employee Details:
- John Doe, Position: Developer
- Jane Smith, Position: Designer

After Adding New Employee:
Company Name: GeeksforGeeks
Location: Noida
Employee Count: 101
Departments: Development, Design, Marketing
Employee Details:
- John Doe, Position: Developer
- Jane Smith, Position: Designer
- Alice Johnson, Position: Project Manager

After Adding New Department:
Company Name: GeeksforGeeks
Location: Noida
Employee Count: 101
Departments: Development, Design, Marketing, Sales
Employee Details:
- John Doe, Position: Developer
- Jane Smith, Position: Designer
- Alice Johnson, Position: Project Manager

Department "Development" already exists.*/
// Define an array of numbers
const numbers = [4, 2, 5, 1, 3];
console.log("Original Numbers:", numbers);

// Sort numbers in ascending order
numbers.sort((a, b) => a - b);
console.log("Sorted Numbers (Ascending):", numbers);

// Reverse the sorted numbers
const reversedNumbers = [...numbers].reverse();
console.log("Reversed Numbers:", reversedNumbers);

// Define an array of fruits
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log("Original Fruits:", fruits);

// Sort fruits alphabetically
fruits.sort();
console.log("Sorted Fruits:", fruits);

// Reverse the sorted fruits
const reversedFruits = [...fruits].reverse();
console.log("Reversed Fruits:", reversedFruits);

//OUTPUT
Original Numbers: [4, 2, 5, 1, 3]
Sorted Numbers (Ascending): [1, 2, 3, 4, 5]
Reversed Numbers: [5, 4, 3, 2, 1]
Original Fruits: ["Banana", "Orange", "Apple", "Mango"]
Sorted Fruits: ["Apple", "Banana", "Mango", "Orange"]
Reversed Fruits: ["Orange", "Mango", "Banana", "Apple"]
//Callable Statement

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.CallableStatement;
import java.sql.Connection;

public class StatementDemo {
    public static void main(String[] args) {
        String DB_URL = "jdbc:oracle:thin:@//localhost:1521/XE";
        String user = "system";
        String pass = "1234";

        try (Connection conn = DriverManager.getConnection(DB_URL, user, pass)) {
            String insertQuery = "{call insert_employee(?, ?)}";
            try (CallableStatement cstmt = conn.prepareCall(insertQuery)) {
                cstmt.setString(1, "Queen");
                cstmt.setDouble(2, 400000);
                cstmt.execute();
                System.out.println("Sucessfully Inserted a record");
            }

        } catch (SQLException se) {
            System.out.println("An error occured");
            se.printStackTrace();
        }
    }
}

//Procedure

CREATE OR REPLACE PROCEDURE insert_employee(
    p_name IN VARCHAR2,
    p_salary IN NUMBER
) IS
BEGIN
    -- Insert the employee with the given name and salary
    INSERT INTO employees (name, salary)
    VALUES (p_name, p_salary);

    -- Commit the transaction
    COMMIT;

    DBMS_OUTPUT.PUT_LINE('Employee inserted successfully!');
EXCEPTION
    WHEN OTHERS THEN
        -- Handle exceptions
        ROLLBACK;
        DBMS_OUTPUT.PUT_LINE('Error inserting employee: ' || SQLERRM);
END;
/
//Prepared Statement

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Connection;

public class StatementDemo {
    public static void main(String[] args) {
        String DB_URL = "jdbc:oracle:thin:@//localhost:1521/XE";
        String user = "system";
        String pass = "1234";

        try (Connection conn = DriverManager.getConnection(DB_URL, user, pass)) {
            String insertQuery = "INSERT INTO employee(name, salary) VALUES (?, ?)";
            try (PreparedStatement pstmt = conn.prepareStatement(insertQuery)) {
                pstmt.setString(1, "Jack");
                pstmt.setDouble(2, 300000);
                pstmt.executeUpdate();
                System.out.println("Sucessfully Inserted a record");
            }

            String getQuery = "SELECT * FROM employee WHERE salary > ?";
            try (PreparedStatement pstmt = conn.prepareStatement(getQuery)) {
                pstmt.setDouble(1, 350000);
                ResultSet rs = pstmt.executeQuery();
                while (rs.next()) {
                    String str = rs.getString("name");
                    double sal = rs.getDouble("salary");

                    System.out.println("Employee Name: " + str + ", Salary is: " + sal);

                }
            }

        } catch (SQLException se) {
            System.out.println("An error occured");
            se.printStackTrace();
        }
    }
}
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Connection;

public class StatementDemo {
    public static void main(String[] args) {
        String DB_URL = "jdbc:oracle:thin:@//localhost:1521/XE";
        String user = "system";
        String pass = "1234";

        try (Connection conn = DriverManager.getConnection(DB_URL, user, pass)) {
            Statement stmt = conn.createStatement();
            String insertQuery = "INSERT INTO employee(name, salary) VALUES ('Alice', 500000)";
            stmt.executeUpdate(insertQuery);
            System.out.println("Sucessfully Inserted a record");

            String getQuery = "SELECT * FROM employee";

            ResultSet rs = stmt.executeQuery(getQuery);
            while (rs.next()) {
                String str = rs.getString("name");
                double sal = rs.getDouble("salary");

                System.out.println("Employee Name: " + str + ", Salary is: " + sal);

            }

        } catch (SQLException se) {
            System.out.println("An error occured");
            se.printStackTrace();
        }
    }
}
//External DTD

//books.dtd
<!ELEMENT catalog (book+)>
<!ELEMENT book (title, author, year, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT price (#PCDATA)>


//name.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE catalog SYSTEM "books.dtd">
<catalog>
    <book>
        <title>Learning XML</title>
        <author>John Doe</author>
        <year>2024</year>
        <price>29.99</price>
    </book>
    <book>
        <title>Mastering XML</title>
        <author>Jane Smith</author>
        <year>2023</year>
        <price>39.99</price>
    </book>
</catalog>
//Internal DTD
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE catalog [
    <!ELEMENT catalog (book+)>
    <!ELEMENT book (title, author, year, price)>
    <!ELEMENT title (#PCDATA)>
    <!ELEMENT author (#PCDATA)>
    <!ELEMENT year (#PCDATA)>
    <!ELEMENT price (#PCDATA)>
]>
<catalog>
    <book>
        <title>Learning XML</title>
        <author>John Doe</author>
        <year>2024</year>
        <price>29.99</price>
    </book>
    <book>
        <title>Mastering XML</title>
        <author>Jane Smith</author>
        <year>2023</year>
        <price>39.99</price>
    </book>
</catalog>
// Example object
const person = {
    name: "Alice",
    age: 25,
    location: {
        city: "Wonderland",
        country: "Fantasy"
    }
};

// Destructuring the object
const { name, age } = person;

console.log("Name:", name); // Output: "Name: Alice"
console.log("Age:", age);   // Output: "Age: 25"

// Destructuring nested objects
const { city, country } = person.location;

console.log("City:", city);     // Output: "City: Wonderland"
console.log("Country:", country); // Output: "Country: Fantasy"

// Assigning to new variable names
const { name: fullName, age: years } = person;
console.log("Full Name:", fullName); // Output: "Full Name: Alice"
console.log("Years:", years);         // Output: "Years: 25"

// Rest parameter in object destructuring
const { name: personName, ...restOfPerson } = person;
console.log("Person Name:", personName); // Output: "Person Name: Alice"
console.log("Rest of Person:", restOfPerson); // Output: "Rest of Person: { age: 25, location: { city: 'Wonderland', country: 'Fantasy' } }"
// Creating a nested object
const person = {
    name: "John Doe",
    age: 30,
    address: {
        street: "123 Main St",
        city: "Anytown",
        country: "USA"
    },
    hobbies: ["reading", "traveling", "gaming"],
    contact: {
        email: "john.doe@example.com",
        phone: {
            home: "555-555-5555",
            mobile: "555-555-1234"
        }
    }
};

// Accessing properties of the nested object
console.log("Name:", person.name); // Output: "Name: John Doe"
console.log("Age:", person.age); // Output: "Age: 30"

// Accessing nested object properties
console.log("Street Address:", person.address.street); // Output: "Street Address: 123 Main St"
console.log("City:", person.address.city); // Output: "City: Anytown"
console.log("Country:", person.address.country); // Output: "Country: USA"

// Accessing hobbies
console.log("Hobbies:", person.hobbies.join(", ")); // Output: "Hobbies: reading, traveling, gaming"

// Accessing contact information
console.log("Email:", person.contact.email); // Output: "Email: john.doe@example.com"
console.log("Home Phone:", person.contact.phone.home); // Output: "Home Phone: 555-555-5555"
console.log("Mobile Phone:", person.contact.phone.mobile); // Output: "Mobile Phone: 555-555-1234"
// sortAndReverse.js

// Example arrays for demonstration
const numArray = [5, 3, 8, 1, 2];
const strArray = ["banana", "apple", "cherry", "date"];

// 1. Sort an array of numbers in ascending order
const sortedNumArray = numArray.sort((a, b) => a - b);
console.log('1. Sorted Number Array (Ascending):', sortedNumArray); // Output: [1, 2, 3, 5, 8]

// 2. Sort an array of strings in alphabetical order
const sortedStrArray = strArray.sort();
console.log('2. Sorted String Array (Alphabetical):', sortedStrArray); // Output: ["apple", "banana", "cherry", "date"]

// 3. Reverse the sorted array of numbers
const reversedNumArray = sortedNumArray.reverse();
console.log('3. Reversed Sorted Number Array:', reversedNumArray); // Output: [8, 5, 3, 2, 1]

// 4. Reverse the sorted array of strings
const reversedStrArray = sortedStrArray.reverse();
console.log('4. Reversed Sorted String Array:', reversedStrArray); // Output: ["date", "cherry", "banana", "apple"]
// stringMethods.js

// Example string for demonstration
const str = "  Hello World  ";

// 1. charAt(index): Returns the character at the specified index
console.log('1. charAt(1):', str.charAt(1)); // Output: "e"

// 2. concat(string1, string2, ...): Combines two or more strings
const str2 = " from JavaScript!";
console.log('2. concat():', str.concat(str2)); // Output: "  Hello World  from JavaScript!"

// 3. includes(searchString, position): Checks if the string contains the specified substring
console.log('3. includes("World"):', str.includes("World")); // Output: true

// 4. indexOf(searchValue, fromIndex): Returns the index of the first occurrence of a specified value
console.log('4. indexOf("o"):', str.indexOf("o")); // Output: 4

// 5. lastIndexOf(searchValue, fromIndex): Returns the index of the last occurrence of a specified value
console.log('5. lastIndexOf("o"):', str.lastIndexOf("o")); // Output: 7

// 6. slice(start, end): Extracts a section of the string
console.log('6. slice(0, 5):', str.slice(0, 5)); // Output: "  Hel"

// 7. split(separator, limit): Splits the string into an array of substrings
console.log('7. split(" "):', str.split(" ")); // Output: ["", "", "Hello", "World", "", ""]

// 8. toLowerCase(): Converts the string to lowercase
console.log('8. toLowerCase():', str.toLowerCase()); // Output: "  hello world  "

// 9. toUpperCase(): Converts the string to uppercase
console.log('9. toUpperCase():', str.toUpperCase()); // Output: "  HELLO WORLD  "

// 10. trim(): Removes whitespace from both ends of the string
console.log('10. trim():', str.trim()); // Output: "Hello World"
//Array Methods

// arrays.js

// 1. push(): Adds one or more elements to the end of an array
const fruits = ['apple', 'banana'];
console.log('Initial array:', fruits);
fruits.push('orange');
console.log('After push("orange"):', fruits); // ['apple', 'banana', 'orange']

// 2. pop(): Removes the last element from an array
const lastFruit = fruits.pop();
console.log('After pop():', fruits); // ['apple', 'banana']
console.log('Popped fruit:', lastFruit); // 'orange'

// 3. shift(): Removes the first element from an array
const firstFruit = fruits.shift();
console.log('After shift():', fruits); // ['banana']
console.log('Shifted fruit:', firstFruit); // 'apple'

// 4. unshift(): Adds one or more elements to the beginning of an array
fruits.unshift('kiwi');
console.log('After unshift("kiwi"):', fruits); // ['kiwi', 'banana']

// 5. slice(): Returns a shallow copy of a portion of an array
const citrus = fruits.slice(0, 1);
console.log('Citrus slice:', citrus); // ['kiwi']
console.log('Original array after slice():', fruits); // ['kiwi', 'banana']

// 6. splice(): Changes the contents of an array by removing or replacing existing elements
fruits.splice(1, 1, 'mango'); // Removes 1 element at index 1 and adds 'mango'
console.log('After splice(1, 1, "mango"):', fruits); // ['kiwi', 'mango']

// 7. forEach(): Executes a provided function once for each array element
console.log('Using forEach to log each fruit:');
fruits.forEach(fruit => console.log(fruit));

// 8. map(): Creates a new array populated with the results of calling a provided function on every element
const fruitLengths = fruits.map(fruit => fruit.length);
console.log('Fruit lengths:', fruitLengths); // [4, 5] for ['kiwi', 'mango']

// 9. filter(): Creates a new array with all elements that pass the test implemented by the provided function
const filteredFruits = fruits.filter(fruit => fruit.startsWith('m'));
console.log('Filtered fruits (starting with "m"):', filteredFruits); // ['mango']

// 10. concat(): Merges two or more arrays
const moreFruits = ['pineapple', 'grape'];
const allFruits = fruits.concat(moreFruits);
console.log('After concat(moreFruits):', allFruits); // ['kiwi', 'mango', 'pineapple', 'grape']
//Nav Bar

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Navbar</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        .navbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #333;
            padding: 15px 20px;
        }
        .navbar a {
            color: white;
            text-decoration: none;
            padding: 14px 20px;
            transition: background-color 0.3s;
        }
        .navbar a:hover {
            background-color: #575757;
        }
        .logo {
            font-size: 24px;
            font-weight: bold;
        }
        .navbar-links {
            display: flex;
        }
        .navbar-links a {
            margin-left: 20px;
        }
        .navbar-toggle {
            display: none;
            font-size: 24px;
            cursor: pointer;
        }
        @media (max-width: 600px) {
            .navbar-links {
                display: none; /* Hide links by default on small screens */
                flex-direction: column;
                width: 100%;
            }
            .navbar-links.show {
                display: flex; /* Show links when toggle is active */
            }
            .navbar-toggle {
                display: block; /* Show hamburger icon */
            }
            .navbar {
                flex-direction: column;
                align-items: flex-start;
            }
            .navbar a {
                margin-left: 0; /* Remove left margin for links in small view */
                text-align: left; /* Align text to the left */
                padding: 10px 20px; /* Adjust padding for better touch targets */
            }
        }
    </style>
</head>
<body>
    <div class="navbar">
        <div class="logo">MyLogo</div>
        <div class="navbar-toggle" onclick="toggleNavbar()">☰</div>
        <div class="navbar-links" id="navbarLinks">
            <a href="#home">Home</a>
            <a href="#about">About</a>
            <a href="#services">Services</a>
            <a href="#contact">Contact</a>
        </div>
    </div>

    <script>
        function toggleNavbar() {
            const navbarLinks = document.getElementById('navbarLinks');
            navbarLinks.classList.toggle('show'); // Toggle the "show" class on click
        }
    </script>
</body>
</html>
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import com.google.android.material.snackbar.Snackbar
class MainActivity : AppCompatActivity() {
private lateinit var startBtn : Button
private lateinit var stopBtn : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var task = LongOperation()
startBtn = findViewById(R.id.start)
stopBtn = findViewById(R.id.end)
startBtn.setOnClickListener {
val contextView = findViewById<View>(R.id.root)
val snack = Snackbar.make(contextView, "Demonstration of Asynchronous Task",
Snackbar.LENGTH_SHORT)
snack.show()
task.execute()
}
stopBtn.setOnClickListener {
task.cancel(true)
val contextView = findViewById<View>(R.id.root)
val snack = Snackbar.make(contextView, "Asynchronous Task Interrupted",
Snackbar.LENGTH_SHORT)
snack.show()
}
}
}
Long Operation:
import android.content.Context
import android.os.AsyncTask
import android.util.Log
import android.widget.Toast
import androidx.core.content.ContextCompat
import kotlin.coroutines.coroutineContext
class LongOperation : AsyncTask<String?, Void?, String>() {
protected override fun doInBackground(vararg params: String?): String? {
try {
Thread.sleep(100000)
} catch (e: InterruptedException) {
Log.e("LongOperation", "Interrupted", e)
return "Interrupted"
}
return "Executed"
}
override fun onPostExecute(result: String) {}
companion object {
fun execute() {}
}
}
Activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.button.MaterialButton
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="54dp"
android:layout_margin="8dp"
android:text="Start Task"
app:layout_constraintBottom_toTopOf="@+id/end"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />
<com.google.android.material.button.MaterialButton
android:id="@+id/end"
android:layout_width="wrap_content"
android:layout_height="54dp"
android:layout_margin="8dp"
android:text=" End Task "
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/start" />
</androidx.constraintlayout.widget.ConstraintLayout>



// App type: Empty Activity
// download the dice images form online and store it in Resource manager
// File: MainActivity.kt
// rename the package name in the below line with your folder name

package com.example.diceroller

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            DiceRollerApp()
            DiceWithButtonAndImage(
                    modifier = Modifier.fillMaxSize().wrapContentSize(Alignment.Center)
            )
        }
    }
}

@Preview
@Composable
fun DiceRollerApp() {
    DiceWithButtonAndImage(modifier = Modifier.fillMaxSize().wrapContentSize(Alignment.Center))
}

@Composable
fun DiceWithButtonAndImage(modifier: Modifier = Modifier) {
    var result by remember { mutableStateOf(1) }
    val imageResource =
            when (result) {
                1 -> R.drawable.dice_1
                2 -> R.drawable.dice_2
                3 -> R.drawable.dice_3
                4 -> R.drawable.dice_4
                5 -> R.drawable.dice_5
                else -> R.drawable.dice_6
            }
    Column(modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally) {
        Image(painter = painterResource(imageResource), contentDescription = result.toString())
        Spacer(modifier = Modifier.height(10.dp))
        Button(
                onClick = { result = (1..6).random() },
        ) { Text(text = "Roll", fontSize = 24.sp) }
    }
}
// App type: Empty Activity
// File: MainActivity.kt
// rename the package name in the below line with your folder name

package com.example.studentdata

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.text.font.FontWeight

data class Student(
    val name: String,
    val rollNumber: Int,
    val marks: Map<String, Int>
) {
    val totalMarks: Int = marks.values.sum()
    val percentage: Float = totalMarks / marks.size.toFloat()
}

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val student = Student(
            name = "John Doe",
            rollNumber = 12345,
            marks = mapOf(
                "Mathematics" to 85,
                "Physics" to 90,
                "Chemistry" to 78,
                "English" to 88,
                "Computer Science" to 95
            )
        )

        setContent {
            StudentInfoApp(student = student)
        }
    }
}

@Composable
fun StudentInfoApp(student: Student) {
    MaterialTheme {
        Surface(
            modifier = Modifier.fillMaxSize(),
            color = MaterialTheme.colorScheme.background
        ) {
            StudentInfo(student)
        }
    }
}

@Composable
fun StudentInfo(student: Student) {
    Column(
        modifier = Modifier
            .padding(16.dp)
            .fillMaxSize()
    ) {
        Text(
            text = "Student Information",
            fontSize = 24.sp,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.padding(bottom = 16.dp)
        )

        Text(
            text = "Name: ${student.name}",
            fontSize = 18.sp,
            modifier = Modifier.padding(bottom = 8.dp)
        )

        Text(
            text = "Roll Number: ${student.rollNumber}",
            fontSize = 18.sp,
            modifier = Modifier.padding(bottom = 16.dp)
        )

        Text(
            text = "Marks:",
            fontSize = 20.sp,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.padding(bottom = 8.dp)
        )

        student.marks.forEach { (subject, mark) ->
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 4.dp),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(text = subject, fontSize = 18.sp)
                Text(text = "$mark", fontSize = 18.sp)
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        Text(
            text = "Total Marks: ${student.totalMarks}",
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold
        )

        Text(
            text = "Percentage: %.2f%%".format(student.percentage),
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.padding(top = 8.dp)
        )
    }
}


// App type: Empty Activity
// include the below line in dependencies in the build.gradle.kts (module) in gradle scripts
// implementation("androidx.navigation:navigation-compose:2.8.3")
// rename the package name in the below line with your folder name
// File: MainActivity.kt

package com.example.login

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.mynavigation.ui.theme.MyNavigationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyNavigationTheme {
                MyApplicationNavigation()
            }
        }
    }
}

@Composable
fun ScreenA(navController: NavController) {
    var email by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var message by remember { mutableStateOf("") }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        val loginImage: Painter = painterResource(id = R.drawable.dice_1)

        Image(
            painter = loginImage,
            contentDescription = "login image",
            modifier = Modifier.size(200.dp)
        )
        Text(text = "Login")
        Spacer(modifier = Modifier.height(16.dp))

        OutlinedTextField(
            value = email,
            onValueChange = { email = it },
            label = { Text(text = "Email") }
        )
        Spacer(modifier = Modifier.height(8.dp))

        OutlinedTextField(
            value = password,
            onValueChange = { password = it },
            label = { Text(text = "Password") }
        )
        Spacer(modifier = Modifier.height(16.dp))

        Button(onClick = {
            if (email == "cse" && password == "cse") {
                navController.navigate("screenB/$email/$password")
            } else {
                navController.navigate("screenC/$email/$password")
            }
            Log.i("Credential", "email: $email password: $password")
        }) {
            Text(text = "Login")
        }
        Spacer(modifier = Modifier.height(4.dp))

        Text(text = "Forgot Password?", modifier = Modifier.clickable { })
        Spacer(modifier = Modifier.height(4.dp))
        Text(text = "or sign in with")
        Spacer(modifier = Modifier.height(16.dp))
        Text(text = message)
    }
}

@Composable
fun ScreenB(email: String, password: String) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(text = "Email is: $email")
        Text(text = "Password is: $password")
        Text(text = "Valid")
    }
}

@Composable
fun ScreenC(email: String, password: String) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        val errorImage: Painter = painterResource(id = R.drawable.dice_1)
        Image(
            painter = errorImage,
            contentDescription = "Invalid email or password",
            modifier = Modifier.size(200.dp)
        )

        Text(text = "Invalid email or password.")
    }
}

@Composable
fun MyApplicationNavigation() {
    val navController = rememberNavController()
    NavHost(navController = navController, startDestination = "/screenA") {
        composable("/screenA") {
            ScreenA(navController)
        }
        composable("screenB/{email}/{password}") {
            val email = it.arguments?.getString("email") ?: ""
            val password = it.arguments?.getString("password") ?: ""
            ScreenB(email, password)
        }
        composable("screenC/{email}/{password}") {
            val email = it.arguments?.getString("email") ?: ""
            val password = it.arguments?.getString("password") ?: ""
            ScreenC(email, password)
        }
    }
}
package com.example.tipcalculator

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            TipCal()
        }
    }
}

@Composable
fun TipCal() {
    var billAmount by remember {
        mutableStateOf("")
    }
    var tipPercentage by remember {
        mutableStateOf("")
    }
    var tipAmount by remember {
        mutableStateOf("")
    }
    var totalAmount by remember {
        mutableStateOf("")
    }
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        OutlinedTextField(value = billAmount, onValueChange = {
            billAmount = it
        }, label = {
            Text(text = "Enter bill amount")
        })
        Spacer(modifier = Modifier.height(4.dp))
        OutlinedTextField(value = tipPercentage, onValueChange = {
            tipPercentage  = it
        }, label = {
            Text(text = "Enter tip percentage")
        })
        Spacer(modifier = Modifier.height(4.dp))
        OutlinedTextField(enabled=false,value = tipAmount, onValueChange = {
            tipAmount  = it
        }, label = {
            Text(text = "Tip Amount")
        })
        Spacer(modifier = Modifier.height(4.dp))
        OutlinedTextField(enabled = false, value = totalAmount, onValueChange = {
            tipPercentage  = it
        }, label = {
            Text(text = "Total Amount")
        })
        Spacer(modifier = Modifier.height(4.dp))
        Button(modifier = Modifier.width(270.dp), onClick = {
            Log.i("Bill","Bill amount: ${billAmount}, Tip Percentage: ${tipPercentage}")
            val bill = billAmount.toDoubleOrNull() ?: 0.0
            val percentage = tipPercentage.toDoubleOrNull() ?: 0.0
            val tp = bill * (percentage / 100)
            tipAmount = tp.toString()
            totalAmount = (bill+tp).toString()
        }) {
            Text(text = "Pay Bill")
        }
    }
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    TipCal()
}
// MainActivity.kt
package com.example.helloworld

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            HelloWorld()
        }
    }
}

@Composable
fun HelloWorld() {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = "Hello World",
            color = Color.Red,
            fontSize = 24.sp,
            textAlign = TextAlign.Center
        )
    }
}

@Preview(showBackground = true)
@Composable
fun HelloWorldPreview() {
    HelloWorld()
}
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
public class javaupdate {
    public static void main(String[] args) throws ClassNotFoundException,SQLException{
        Connection conn = null;
        Statement st = null;
        String username = "system";
        String password = "1808";
        String QUERY = "UPDATE employee set job = 'manager' where empno=7999";
        try{
            conn = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/XE", username, password);
            st = conn.createStatement();
            int rows = st.executeUpdate(QUERY);
            System.out.println(rows);
        }catch(SQLException e)
        {
            e.printStackTrace();
        }
    }
}
import java.sql.Statement;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Date;
public class jdbcInsert {
    public static void main(String[] args) throws ClassNotFoundException,SQLException{
        Connection conn = null;
        Statement st = null;
        try
        {
            conn = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/XE", "system", "1808");
            st = conn.createStatement();
            int row= st.executeUpdate("Insert into employee values (7990,'manish','salesman',7755,TO_DATE('17-DEC-24', 'DD-MON-RRRR'),1000,30,25)");
            ResultSet rs1 = st.executeQuery("select * from employee");
            while (rs1.next()) {
                int id=rs1.getInt(1);
                String ename = rs1.getString(2);
                String job = rs1.getString(3);
                int mgr = rs1.getInt(4);
                Date hiredate = rs1.getDate(5);
                int sal = rs1.getInt(6);
                int com = rs1.getInt(7);
                int deptno = rs1.getInt(8);
                System.out.println(id+" "+ename+" "+job+" "+mgr+" "+hiredate+" "+sal + " "+com+" "+deptno);
            }
        }catch(SQLException e)
        {
            e.printStackTrace();
        }
    }
}
import java.sql.Statement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class jdbcselect {
    public static void main(String[] args) {
        Connection conn = null;
        Statement st = null;
        try{
            conn = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/XE", "system", "1808");
            st = conn.createStatement();
            ResultSet rs1 = st.executeQuery("select * from employee");
            while(rs1.next())
            {
                int id = rs1.getInt(1);
                String name = rs1.getString(2);
                String job = rs1.getString(3);
                int mgr = rs1.getInt(4);
                Date date = rs1.getDate(5);
                int sal = rs1.getInt(6);
                int com = rs1.getInt(7);
                int deptno = rs1.getInt(8);
                System.out.println(
                        id + "," + name + "," + job + "," + mgr + "," + date + "," + sal + "," + com + "," + deptno); 
            }
        }catch(SQLException e)
        {
            e.printStackTrace();
        }
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Grid Layout</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        header {
            background-color: #4CAF50;
            color: white;
            padding: 15px;
            text-align: center;
        }
        .grid-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 10px;
            padding: 20px;
        }
        .card {
            background-color: #f9f9f9;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>
    <header>
        <h1>Simple Grid Layout</h1>
    </header>
    <main>
        <div class="grid-container">
            <div class="card">
                <h2>Card 1</h2>
                <p>This is a simple card.</p>
            </div>
            <div class="card">
                <h2>Card 2</h2>
                <p>This is another simple card.</p>
            </div>
            <div class="card">
                <h2>Card 3</h2>
                <p>This is yet another simple card.</p>
            </div>
            <div class="card">
                <h2>Card 4</h2>
                <p>This is an additional card.</p>
            </div>
        </div>
    </main>
</body>
</html>
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import seaborn as sns

df_petrol = pd.read_csv('petrol_consumption.csv')
print(df_petrol.head())
df_petrol.info()
#
df_petrol.isnull().sum()
#
df_petrol.fillna(df_petrol.mean(),inplace=True)
#
sns.pairplot(df_petrol,hue="Petrol_Consumption")
plt.show()
#
#PCA
scaler = StandardScaler()
df = scaler.fit_transform(df)

pca = PCA(n_components=2)
df_pca = pca.fit_transform(df)
df = pd.DataFrame(data = df_pca,columns=['PC1','PC2'])
df["Petrol_Consumption"] = df_petrol["Petrol_Consumption"]
sns.scatterplot(x='PC1',y='PC2',data = df,hue="Petrol_Consumption")
plt.show()

#Rfe
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import RFE
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

df = pd.read_csv("Fish.csv")
print(df.head())
df.info()
#
X = df.drop('Species',axis=1)
y = df['Species']

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

dtc = DecisionTreeClassifier()
dtc.fit(X_train,y_train)
y_pred = dtc.predict(X_test)
print(y_pred)
print(y_test)

accuracy = accuracy_score(y_test,y_pred)
print(accuracy)
#
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import LabelEncoder

df = pd.read_csv('Iris.csv')
df.info()
#
encoder = LabelEncoder()
df["Species"] = encoder.fit_transform(df["Species"])
#
df.info()
#
X = df.iloc[:,:-1] #df.drop(columns=["speices"])
y = df.iloc[:,-1] #df["species"]
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
dtc = DecisionTreeClassifier()
dtc.fit(X_train,y_train)
y_pred = dtc.predict(X_test)
print(y_test,y_pred)
#
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix

accuracy = accuracy_score(y_pred,y_test)
print(accuracy)
print(classification_report(y_pred,y_test))
print(confusion_matrix(y_pred,y_test))
#
# prompt: Visualize insights of Above decision tree classification on iris dataset

from sklearn import tree
import matplotlib.pyplot as plt

plt.figure(figsize=(15,10))
tree.plot_tree(dtc,filled=True,feature_names=X.columns,class_names=['0','1','2'])
plt.show()
#from sklearn.neighbors import KNeighborsClassifier

df = pd.read_csv('diabetes.csv')
df.info()
#
X = df.iloc[:,:-1] #df.drop("Outcome",axis=1)
y = df.iloc[:,-1]
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
knn = KNeighborsClassifier(n_neighbors=2)
knn.fit(X_train,y_train)
y_pred = knn.predict(X_test)
print(y_test,y_pred)
#
accuracy = accuracy_score(y_pred,y_test)
print(accuracy)
print(classification_report(y_pred,y_test))
print(confusion_matrix(y_pred,y_test))
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flexbox Layout Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        header {
            background-color: #4CAF50;
            color: white;
            padding: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        nav {
            display: flex;
            gap: 15px;
        }
        .container {
            display: flex;
            justify-content: space-around;
            margin: 20px;
            flex-wrap: wrap;
        }
        .card {
            background-color: #f9f9f9;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 20px;
            width: 30%;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            text-align: center;
            margin: 10px;
        }
        @media (max-width: 768px) {
            .card {
                width: 100%; /* Full width on small screens */
            }
        }
    </style>
</head>
<body>
    <header>
        <h1>Flexbox Layout</h1>
        <nav>
            <a href="#" style="color: white;">Home</a>
            <a href="#" style="color: white;">About</a>
            <a href="#" style="color: white;">Services</a>
            <a href="#" style="color: white;">Contact</a>
        </nav>
    </header>
    <main>
        <div class="container">
            <div class="card">
                <h2>Card 1</h2>
                <p>This is a simple card.</p>
            </div>
            <div class="card">
                <h2>Card 2</h2>
                <p>This is another simple card.</p>
            </div>
            <div class="card">
                <h2>Card 3</h2>
                <p>This is yet another simple card.</p>
            </div>
        </div>
    </main>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Demo</title>
    <link rel="stylesheet" href="styles.css"> <!-- Link to external CSS -->
    <style>
        /* Internal CSS */
        h2 {
            color: green;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1 style="color: blue; text-align: center;">Welcome to CSS Demo</h1> <!-- Inline CSS -->

    <h2>Internal CSS Example</h2>
    <p>This paragraph demonstrates the use of internal CSS for styling headings.</p>

    <h2 style="color: orange;">Inline CSS Example</h2>
    <p>This paragraph is styled using inline CSS for the heading.</p>

    <h2 class="external-header">External CSS Example</h2>
    <p>This paragraph demonstrates the use of external CSS for styling.</p>
</body>
</html>


/* External CSS */
body {
    background-color: #f4f4f4;
    font-family: Arial, sans-serif;
}

.external-header {
    color: purple;
    text-align: center;
}
#Decision Tree Classification

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
import pandas as pd

iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df['species'] = iris.target
print(df.head())
print(df.info())
X = df.drop('species', axis=1)
y = df['species']
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
model = DecisionTreeClassifier()
model.fit(x_train,y_train)
y_pred = model.predict(x_test)
accuracy = accuracy_score(y_test,y_pred)
print("Accuracy:",accuracy)
print("Classification Report:\n",classification_report(y_test,y_pred))
print("Confusion Matrix:\n",confusion_matrix(y_test,y_pred))
output:
   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)  \
0                5.1               3.5                1.4               0.2   
1                4.9               3.0                1.4               0.2   
2                4.7               3.2                1.3               0.2   
3                4.6               3.1                1.5               0.2   
4                5.0               3.6                1.4               0.2   

   species  
0        0  
1        0  
2        0  
3        0  
4        0  
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   sepal length (cm)  150 non-null    float64
 1   sepal width (cm)   150 non-null    float64
 2   petal length (cm)  150 non-null    float64
 3   petal width (cm)   150 non-null    float64
 4   species            150 non-null    int64  
dtypes: float64(4), int64(1)
memory usage: 6.0 KB
None
Accuracy: 1.0
Classification Report:
               precision    recall  f1-score   support

           0       1.00      1.00      1.00        10
           1       1.00      1.00      1.00         9
           2       1.00      1.00      1.00        11

    accuracy                           1.00        30
   macro avg       1.00      1.00      1.00        30
weighted avg       1.00      1.00      1.00        30

Confusion Matrix:
 [[10  0  0]
 [ 0  9  0]
 [ 0  0 11]]
2.#K-Neareast Nrighbour
#K-Neareast Nrighbour
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
df = pd.DataFrame(data=iris.data,columns=iris.feature_names)
df['species']=iris.target
print(df.head())
print(df.info())
x = df.drop('species',axis=1)
y = df['species']
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=42)
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(x_train,y_train)
y_pred = knn.predict(x_test)
accuracy = accuracy_score(y_test,y_pred)
print("Accuracy:",accuracy)
print("Classification Report:\n",classification_report(y_test,y_pred))
print("Confusion Matrix:\n",confusion_matrix(y_test,y_pred))
output:
]
#K-Neareast Nrighbour
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
df = pd.DataFrame(data=iris.data,columns=iris.feature_names)
df['species']=iris.target
print(df.head())
…print("Confusion Matrix:\n",confusion_matrix(y_test,y_pred))
   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)  \
0                5.1               3.5                1.4               0.2   
1                4.9               3.0                1.4               0.2   
2                4.7               3.2                1.3               0.2   
3                4.6               3.1                1.5               0.2   
4                5.0               3.6                1.4               0.2   

   species  
0        0  
1        0  
2        0  
3        0  
4        0  
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   sepal length (cm)  150 non-null    float64
 1   sepal width (cm)   150 non-null    float64
 2   petal length (cm)  150 non-null    float64
 3   petal width (cm)   150 non-null    float64
 4   species            150 non-null    int64  
dtypes: float64(4), int64(1)
memory usage: 6.0 KB
None
Accuracy: 1.0
Classification Report:
               precision    recall  f1-score   support

           0       1.00      1.00      1.00        10
           1       1.00      1.00      1.00         9
           2       1.00      1.00      1.00        11

    accuracy                           1.00        30
   macro avg       1.00      1.00      1.00        30
weighted avg       1.00      1.00      1.00        30

Confusion Matrix:
 [[10  0  0]
 [ 0  9  0]
 [ 0  0 11]]
1.
from sklearn.datasets import load_iris
import pandas as pd
iris=load_iris()
df=pd.DataFrame(data=iris.data, columns=iris.feature_names)
print("DataFrame Head:\n",df.head())
print("DataInfo:\n",df.info())

output
DataFrame Head:
    sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
0                5.1               3.5                1.4               0.2
1                4.9               3.0                1.4               0.2
2                4.7               3.2                1.3               0.2
3                4.6               3.1                1.5               0.2
4                5.0               3.6                1.4               0.2
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 4 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   sepal length (cm)  150 non-null    float64
 1   sepal width (cm)   150 non-null    float64
 2   petal length (cm)  150 non-null    float64
 3   petal width (cm)   150 non-null    float64
dtypes: float64(4)
memory usage: 4.8 KB
DataInfo:
 None
2.
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
x_scaled=scaler.fit_transform(df)
from sklearn.cluster import KMeans
Kmeans=KMeans(n_clusters=3, random_state=42)
Kmeans.fit((x_scaled))
clusters_labels=Kmeans.labels_
df['cluster']=clusters_labels
cluster_centers=Kmeans.cluster_centers_
print("cluster centers:\n",cluster_centers)

ouput

cluster centers:
 [[ 1.13597027  0.08842168  0.99615451  1.01752612]
 [-1.01457897  0.85326268 -1.30498732 -1.25489349]
 [-0.05021989 -0.88337647  0.34773781  0.2815273 ]]

3.

from sklearn.metrics import adjusted_rand_score,silhouette_score
true_labels=iris.target
ari=adjusted_rand_score(true_labels,clusters_labels)
print(f"Adjusted Rand_Index(ARI):{ari}")
silhouette_avg=silhouette_score(x_scaled,clusters_labels)
print(f"sithouette score : {silhouette_avg}")

ouput

Adjusted Rand_Index(ARI):0.6201351808870379
sithouette score : 0.45994823920518635

ll.1

#Hierarchial clustering
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from scipy.cluster.hierarchy import dendrogram,linkage
from scipy.cluster.hierarchy import fcluster
iris=load_iris()
data=pd.DataFrame(iris.data,columns=iris.feature_names)
scaler=StandardScaler()
scaled_data=scaler.fit_transform(data)
z=linkage(scaled_data,method="ward")
plt.figure(figsize=(10,7))
plt.title("Dendogram for Iris dataset")
dendrogram(z,labels=iris.target)
plt.show()
clusters=fcluster(z,3,criterion="maxclust")
data['cluster']=clusters
data['species']=iris.target
print(data.groupby(['cluster','species']).size())
silhouette_avg=silhouette_score(scaled_data,clusters)
print(f"Silhouette score: {silhouette_avg}")

output
 

cluster  species
1        0          49
2        0           1
         1          27
         2           2
3        1          23
         2          48
dtype: int64
Silhouette score: 0.446689041028591
import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
import seaborn as sns 
from sklearn.preprocessing import StandardScaler 
from sklearn.cluster import AgglomerativeClustering 
from sklearn.metrics import accuracy_score, confusion_matrix 
from scipy.cluster.hierarchy import dendrogram, linkage 
from sklearn.decomposition import PCA 
# Load the Iris dataset 
df = pd.read_csv('Iris.csv') 
# Display the first few rows to understand the structure (optional) 
print(df.head()) 
# Remove the 'Id' column if present 
df = df.drop(columns=['Id']) 
# Separate features and the actual labels (for comparison) 
X = df.drop(columns=['Species']) 
y_true = df['Species'] 
# Standardize the features 
scaler = StandardScaler() 
X_scaled = scaler.fit_transform(X) 
# Generate a dendrogram to visualize hierarchical clustering structure 
plt.figure(figsize=(10, 7)) 
linked = linkage(X_scaled, method='ward') 
dendrogram(linked, labels=y_true.values, orientation='top', distance_sort='descending', show_leaf_counts=True) 
plt.title("Dendrogram for Iris Dataset") 
plt.xlabel("Samples") 
plt.ylabel("Euclidean Distance") 
plt.show() 
# Apply Hierarchical Clustering 
hc = AgglomerativeClustering(n_clusters=3, affinity='euclidean', linkage='ward') 
y_hc = hc.fit_predict(X_scaled) 
# Map cluster labels to actual classes for accuracy estimation 
y_hc_mapped = np.zeros_like(y_hc) 
for i in range(3): 
mask = (y_hc == i) 
y_hc_mapped[mask] = np.bincount(y_true[mask].factorize()[0]).argmax() 
# Estimate accuracy by comparing clusters to actual labels 
accuracy = accuracy_score(y_true.factorize()[0], y_hc_mapped) 
print("Estimated Accuracy of Hierarchical Clustering:", accuracy) 
# Confusion matrix to visualize clustering performance 
conf_matrix = confusion_matrix(y_true.factorize()[0], y_hc_mapped) 
plt.figure(figsize=(6, 4)) 
sns.heatmap(conf_matrix, annot=True, fmt="d", cmap="Blues", xticklabels=['Setosa', 'Versicolor', 'Virginica'], 
yticklabels=['Setosa', 'Versicolor', 'Virginica']) 
plt.xlabel("Cluster Label") 
plt.ylabel("True Label") 
plt.title("Confusion Matrix of Hierarchical Clustering") 
plt.show() 
# Visualize clusters using PCA (reduce to 2D for plotting) 
pca = PCA(n_components=2) 
X_pca = pca.fit_transform(X_scaled) 
# Plot the clusters and actual labels 
plt.figure(figsize=(12, 5)) 
# Plot hierarchical clusters 
plt.subplot(1, 2, 1) 
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_hc, cmap="viridis", s=50) 
plt.title("Hierarchical Clustering on Iris Dataset (PCA-reduced)") 
plt.xlabel("Principal Component 1") 
plt.ylabel("Principal Component 2") 
plt.colorbar(label="Cluster") 
# Plot actual species 
species_to_num = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2} 
y_true_numeric = y_true.map(species_to_num) 
plt.subplot(1, 2, 2) 
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_true_numeric, cmap="viridis", s=50) 
plt.title("Actual Species Labels (PCA-reduced)") 
plt.xlabel("Principal Component 1") 
plt.ylabel("Principal Component 2") 
plt.colorbar(label="Species") 
plt.tight_layout() 
plt.show()
import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
import seaborn as sns 
from sklearn.preprocessing import StandardScaler 
from sklearn.cluster import KMeans 
from sklearn.metrics import accuracy_score, confusion_matrix 
from sklearn.decomposition import PCA 
# Load the Iris dataset 
df = pd.read_csv('Iris.csv') 
# Display the first few rows (optional) 
print(df.head()) 
# Remove the 'Id' column if present 
df = df.drop(columns=['Id']) 
# Separate features and the actual labels (for comparison) 
X = df.drop(columns=['Species']) 
y_true = df['Species'] 
# Standardize the features 
scaler = StandardScaler() 
X_scaled = scaler.fit_transform(X) 
# Apply k-Means clustering 
kmeans = KMeans(n_clusters=3, random_state=42) 
kmeans.fit(X_scaled) 
y_kmeans = kmeans.labels_ 
# Map cluster labels to the actual classes for accuracy estimation 
# Since k-means labels are arbitrary, we map them using the most common species in each cluster. 
y_kmeans_mapped = np.zeros_like(y_kmeans) 
for i in range(3): 
mask = (y_kmeans == i) 
y_kmeans_mapped[mask] = np.bincount(y_true[mask].factorize()[0]).argmax() 
# Estimate accuracy by comparing clusters to actual labels 
accuracy = accuracy_score(y_true.factorize()[0], y_kmeans_mapped) 
print("Estimated Accuracy of k-Means Clustering:", accuracy) 
# Confusion matrix to visualize clustering performance 
conf_matrix = confusion_matrix(y_true.factorize()[0], y_kmeans_mapped) 
plt.figure(figsize=(6, 4)) 
sns.heatmap(conf_matrix, annot=True, fmt="d", cmap="Blues", xticklabels=['Setosa', 'Versicolor', 'Virginica'], 
yticklabels=['Setosa', 'Versicolor', 'Virginica']) 
plt.xlabel("Cluster Label") 
plt.ylabel("True Label") 
plt.title("Confusion Matrix of k-Means Clustering") 
plt.show() 
# Visualize clusters using PCA (reduce to 2D for plotting) 
pca = PCA(n_components=2) 
X_pca = pca.fit_transform(X_scaled) 
# Plot the clusters and actual labels 
plt.figure(figsize=(12, 5)) 
# Plot k-Means clusters 
plt.subplot(1, 2, 1) 
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_kmeans, cmap="viridis", s=50) 
plt.title("k-Means Clustering on Iris Dataset (PCA-reduced)") 
plt.xlabel("Principal Component 1") 
plt.ylabel("Principal Component 2") 
plt.colorbar(label="Cluster") 
# Plot actual species 
species_to_num = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2} 
y_true_numeric = y_true.map(species_to_num) 
plt.subplot(1, 2, 2) 
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_true_numeric, cmap="viridis", s=50) 
plt.title("Actual Species Labels (PCA-reduced)") 
plt.xlabel("Principal Component 1") 
plt.ylabel("Principal Component 2") 
plt.colorbar(label="Species") 
plt.tight_layout() 
plt.show()
import pandas as pd 
import matplotlib.pyplot as plt 
import seaborn as sns 
from sklearn.model_selection import train_test_split 
from sklearn.ensemble import RandomForestClassifier 
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix 
from sklearn.preprocessing import StandardScaler 
# Load the dataset 
df = pd.read_csv('bank_loans.csv') 
# Display the first few rows to understand the structure (optional) 
print(df.head()) 
print(df.info()) 
# Check for missing values (optional) 
print("Missing values:\n", df.isnull().sum()) 
# Handle missing values if any (optional, assuming numerical columns filled with mean) 
df.fillna(df.mean(), inplace=True) 
# Encode categorical variables (assuming 'Gender', 'Married', etc. as example categorical features) 
df = pd.get_dummies(df, drop_first=True) 
# Separate features and target variable 
X = df.drop(columns=['Loan_Status'])  # Assuming 'Loan_Status' is the target column (1 = Approved, 0 = Not Approved) 
y = df['Loan_Status'] 
# Split the data 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) 
# Standardize the features 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
# Initialize and train the Random Forest Classifier 
rf_model = RandomForestClassifier(n_estimators=100, random_state=42) 
rf_model.fit(X_train_scaled, y_train) 
# Predict on the test set 
y_pred = rf_model.predict(X_test_scaled) 
# Calculate accuracy and other performance metrics 
accuracy = accuracy_score(y_test, y_pred) 
print("Random Forest Model Accuracy:", accuracy) 
print("\nClassification Report:\n", classification_report(y_test, y_pred)) 
# Plot confusion matrix for better insight into model performance 
conf_matrix = confusion_matrix(y_test, y_pred) 
plt.figure(figsize=(6, 4)) 
sns.heatmap(conf_matrix, annot=True, fmt="d", cmap="Blues", xticklabels=['Not Approved', 'Approved'], 
yticklabels=['Not Approved', 'Approved']) 
plt.xlabel("Predicted") 
plt.ylabel("Actual") 
plt.title("Confusion Matrix") 
plt.show() 
# Feature importance visualization 
feature_importances = rf_model.feature_importances_ 
features = X.columns 
# Create a dataframe for feature importances 
feature_df = pd.DataFrame({'Feature': features, 'Importance': feature_importances}) 
feature_df = feature_df.sort_values(by='Importance', ascending=False) 
# Plot feature importances 
plt.figure(figsize=(10, 6)) 
sns.barplot(x='Importance', y='Feature', data=feature_df, palette="viridis") 
plt.title("Feature Importances in Random Forest Model") 
plt.xlabel("Importance") 
plt.ylabel("Feature") 
plt.show()
import pandas as pd 
from sklearn.model_selection import train_test_split 
from sklearn.preprocessing import StandardScaler 
from sklearn.neighbors import KNeighborsClassifier 
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report 
# Load the dataset 
df = pd.read_csv('diabetes.csv') 
# Display the first few rows to understand the dataset structure (optional) 
print(df.head()) 
# Separate features and target 
X = df.drop(columns=['Outcome'])  # Assuming 'Outcome' is the target column (0 = No Diabetes, 1 = Diabetes) 
y = df['Outcome'] 
# Split the data 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) 
# Standardize the features 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
# Initialize and train the k-NN classifier 
k = 5  # You can tune this value 
knn = KNeighborsClassifier(n_neighbors=k) 
knn.fit(X_train_scaled, y_train) 
# Predict on the test set 
y_pred = knn.predict(X_test_scaled) 
# Calculate performance measures 
accuracy = accuracy_score(y_test, y_pred) 
precision = precision_score(y_test, y_pred) 
recall = recall_score(y_test, y_pred) 
f1 = f1_score(y_test, y_pred) 
# Display the performance measures 
print("Performance Measures for k-NN Classifier:") 
print(f"Accuracy: {accuracy:.4f}") 
print(f"Precision: {precision:.4f}") 
print(f"Recall: {recall:.4f}") 
print(f"F1-Score: {f1:.4f}") 
# Detailed classification report 
print("\nClassification Report:\n", classification_report(y_test, y_pred)) 
import pandas as pd 
# Load the dataset 
df = pd.read_csv('Iris.csv') 
# Display the first few rows and basic information 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
from sklearn.model_selection import train_test_split 
from sklearn.preprocessing import LabelEncoder 
# Encode the target variable 
label_encoder = LabelEncoder() 
df['Species'] = label_encoder.fit_transform(df['Species']) 
# Separate features and target variable 
X = df.drop(columns=['Species']) 
y = df['Species'] 
# Split the data 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) 
from sklearn.tree import DecisionTreeClassifier 
from sklearn.metrics import accuracy_score 
# Initialize the Decision Tree Classifier 
model = DecisionTreeClassifier(random_state=42) 
model.fit(X_train, y_train) 
# Predict on the test set 
y_pred = model.predict(X_test) 
# Estimate the accuracy of the model 
accuracy = accuracy_score(y_test, y_pred) 
print("Accuracy of Decision Tree Classifier:", accuracy) 
from sklearn.tree import plot_tree 
import matplotlib.pyplot as plt 
# Plot the decision tree 
plt.figure(figsize=(12, 8)) 
plot_tree(model, feature_names=X.columns, class_names=label_encoder.classes_, filled=True) 
plt.title("Decision Tree Structure") 
plt.show() 
importances = model.feature_importances_ 
feature_names = X.columns 
# Plot feature importances 
plt.figure(figsize=(8, 6)) 
plt.barh(feature_names, importances, color='skyblue') 
plt.xlabel("Feature Importance") 
plt.ylabel("Feature") 
plt.title("Feature Importances in Decision Tree Model") 
plt.show() 
import numpy as np 
from matplotlib.colors import ListedColormap 
# Define a function to plot decision boundaries 
def plot_decision_boundary(model, X, y): 
# Set up the grid for plotting decision boundaries 
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), 
np.arange(y_min, y_max, 0.02)) 
# Predict over the grid 
Z = model.predict(np.c_[xx.ravel(), yy.ravel()]) 
Z = Z.reshape(xx.shape) 
# Plot the contour and training examples 
plt.figure(figsize=(10, 6)) 
plt.contourf(xx, yy, Z, alpha=0.3, cmap=ListedColormap(('red', 'green', 'blue'))) 
scatter = plt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap=ListedColormap(('red', 'green', 'blue'))) 
plt.xlabel("Petal Length") 
plt.ylabel("Petal Width") 
plt.title("Decision Boundary (Petal Length vs Petal Width)") 
plt.legend(handles=scatter.legend_elements()[0], labels=label_encoder.classes_) 
plt.show() 
# Extract PetalLength and PetalWidth for visualization 
X_2d_train = X_train[['PetalLengthCm', 'PetalWidthCm']].values 
y_train_2d = y_train.values 
# Train a new model on these two features for simplicity 
model_2d = DecisionTreeClassifier(random_state=42) 
model_2d.fit(X_2d_train, y_train_2d) 
# Plot the decision boundary 
plot_decision_boundary(model_2d, X_2d_train, y_train_2d)
import pandas as pd 
# Load the dataset 
df = pd.read_csv('student_scores.csv') 
# Display the first few rows and basic information 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
from sklearn.model_selection import train_test_split 
# Separate features and target 
X = df.drop(columns=['Score'])  # Assuming 'Score' is the target column 
y = df['Score'] 
# Split 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) 
from sklearn.preprocessing import StandardScaler 
# Initialize and fit the scaler on training data 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
from sklearn.linear_model import LinearRegression 
from sklearn.metrics import mean_absolute_error, mean_squared_error 
import numpy as np 
# Initialize and train the model 
model = LinearRegression() 
model.fit(X_train_scaled, y_train) 
# Predict on the test set 
y_pred = model.predict(X_test_scaled) 
# Evaluate performance 
mae = mean_absolute_error(y_test, y_pred) 
rmse = np.sqrt(mean_squared_error(y_test, y_pred)) 
print("Without Dimensionality Reduction") 
print("Mean Absolute Error (MAE):", mae) 
print("Root Mean Squared Error (RMSE):", rmse) 
from sklearn.decomposition import PCA 
# Initialize PCA and fit on the scaled training data 
pca = PCA(n_components=0.95)  # Retain 95% variance 
X_train_pca = pca.fit_transform(X_train_scaled) 
X_test_pca = pca.transform(X_test_scaled) 
# Check the number of components 
print("Number of components selected:", pca.n_components_) 
# Train the regression model on PCA-reduced data 
model_pca = LinearRegression() 
model_pca.fit(X_train_pca, y_train) 
# Predict on the PCA-transformed test set 
y_pred_pca = model_pca.predict(X_test_pca) 
# Evaluate performance 
mae_pca = mean_absolute_error(y_test, y_pred_pca) 
rmse_pca = np.sqrt(mean_squared_error(y_test, y_pred_pca)) 
print("With Dimensionality Reduction (PCA)") 
print("Mean Absolute Error (MAE):", mae_pca) 
print("Root Mean Squared Error (RMSE):", rmse_pca) 
print("Comparison of Model Performance:") 
print("Without Dimensionality Reduction - MAE:", mae, ", RMSE:", rmse) 
print("With Dimensionality Reduction (PCA) - MAE:", mae_pca, ", RMSE:", rmse_pca)
import pandas as pd 
# Load the dataset 
df = pd.read_csv('Pune_rent.csv') 
# Display the first few rows and basic information 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
# Check for missing values 
print(df.isnull().sum()) 
# Convert categorical variables to dummy/indicator variables if necessary 
# For demonstration, assuming 'location', 'house_type' are categorical variables 
df = pd.get_dummies(df, columns=['location', 'house_type'], drop_first=True) 
from sklearn.model_selection import train_test_split 
# Separate features and target 
X = df.drop(columns=['Rent']) 
y = df['Rent'] 
# Split 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) 
from sklearn.preprocessing import StandardScaler 
# Standardize the features 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
from sklearn.linear_model import LinearRegression 
# Initialize and train the model 
model = LinearRegression() 
model.fit(X_train_scaled, y_train) 
# Predict on the test set 
y_pred = model.predict(X_test_scaled) 
from sklearn.metrics import mean_absolute_error, mean_squared_error 
import numpy as np 
# Calculate MAE and RMSE 
mae = mean_absolute_error(y_test, y_pred) 
rmse = np.sqrt(mean_squared_error(y_test, y_pred)) 
print("Mean Absolute Error (MAE):", mae) 
print("Root Mean Squared Error (RMSE):", rmse)
import pandas as pd 
# Load the dataset 
df = pd.read_csv('Fish.csv') 
# Display the first few rows and basic information 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
from sklearn.model_selection import train_test_split 
from sklearn.preprocessing import LabelEncoder 
# Encode the target variable if it's categorical 
label_encoder = LabelEncoder() 
df['Species'] = label_encoder.fit_transform(df['Species']) 
# Separate the features and target variable 
X = df.drop(columns=['Species']) 
y = df['Species'] 
# Split 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) 
from sklearn.preprocessing import StandardScaler 
# Standardize the features 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
from sklearn.svm import SVC 
from sklearn.feature_selection import RFE 
# Initialize the classifier and RFE 
svc = SVC(kernel="linear", random_state=42) 
rfe = RFE(estimator=svc, n_features_to_select=3)  # Choose 3 features for demonstrate on 
# Fit RFE 
rfe.fit(X_train_scaled, y_train) 
# Print the ranking of features 
print("Feature ranking (1 indicates selected features):", rfe.ranking_) 
print("Selected features:", X.columns[rfe.support_]) 
from sklearn.metrics import accuracy_score, classification_report 
# Select the features indicated by RFE 
X_train_rfe = X_train_scaled[:, rfe.support_] 
X_test_rfe = X_test_scaled[:, rfe.support_] 
# Train the classifier on the selected features 
svc.fit(X_train_rfe, y_train) 
# Make predictions and evaluate performance 
y_pred = svc.predict(X_test_rfe) 
print("Accuracy:", accuracy_score(y_test, y_pred)) 
print("Classification Report:\n", classification_report(y_test, y_pred)) 
import pandas as pd 
# Load the dataset 
df = pd.read_csv('petrol_consumption.csv') 
# Display basic information about the dataset 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
from sklearn.preprocessing import StandardScaler 
# Separate the features and target variable if there's one 
X = df.drop(columns=['Petrol_Consumption'])  # Assuming 'Petrol_Consumption' is the target variable 
y = df['Petrol_Consumption'] 
# Standardize the features 
scaler = StandardScaler() 
X_scaled = scaler.fit_transform(X) 
from sklearn.decomposition import PCA 
# Apply PCA 
pca = PCA(n_components=2) 
X_pca = pca.fit_transform(X_scaled) 
# Check the explained variance 
print("Explained variance by each component:", pca.explained_variance_ratio_) 
print("Cumulative explained variance:", pca.explained_variance_ratio_.cumsum())
Task-6
Implement OBST using dynamic programming
Algorithm:
Algorithm OBST(p, q, n)
// Given n distinct identifiers a1 < a2 < ··· < an and probabilities
// p[i], 1 ≤ i ≤ n, and q[i], 0 ≤ i ≤ n, this algorithm computes
// the cost c[i, j] of optimal binary search tree for identifiers
// a_i, ..., a_j. It also computes r[i, j], the root of t[i, j].
// w[i, j] is the weight of t[i, j].
{
  for i := 0 to n do
  { 
    // Initialize.
    w[i, i] := q[i]; r[i, i] := 0; c[i, i] := 0.0;
    // Optimal trees with one node
    w[i, i + 1] := q[i] + q[i + 1] + p[i + 1];
    c[i, i + 1] := w[i, i + 1]; r[i, i + 1] := i + 1;
  }
  
  for m := 2 to n do // Find optimal trees with m nodes.
    for i := 0 to n - m do
    {
      j := i + m;
      w[i, j] := w[i, j - 1] + p[j] + q[j];
      c[i, j] := ∞; // Solve 5.12 using Knuth's result.
      k := Find(c, r, i, j);
      // A value of k in the range [r[i, j - 1], r[i + 1, j]] that minimizes c[i, k - 1] + c[k, j];
      c[i, j] := w[i, j] + c[i, k - 1] + c[k, j];
      r[i, j] := k;
    }
  write (c[0, n], w[0, n], r[0, n]);
}

Algorithm Find(c, r, i, j)
{
  min := ∞;
  for m := r[i, j - 1] to r[i + 1, j] do
    if (c[i, m - 1] + c[m, j] < min) then
    {
      min := c[i, m - 1] + c[m, j];
      l_i := m;
    }
  return l_i;
}

Program:
#include <stdio.h>
#define MAX 10
#define INF 300000

void main() {
    char ele[MAX][MAX];
    int w[MAX][MAX], c[MAX][MAX], r[MAX][MAX];
    int p[MAX], q[MAX];
    int temp, min, min1;
    int i, j, k, b, n;

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

    // Input probabilities for elements p[i]
    for (i = 1; i <= n; i++) {
        printf("Enter the element P(%d): ", i);
        scanf("%d", &p[i]);
    }
    printf("\n");

    // Input probabilities for dummy keys q[i]
    for (i = 0; i <= n; i++) {
        printf("Enter the element q(%d): ", i);
        scanf("%d", &q[i]);
    }
    printf("\n");

    printf("W \t\t C \t\t R\n");

    // Initialization of w, c, and r matrices for single elements
    for (i = 0; i <= n; i++) {
        for (j = 0; j <= n; j++) {
            if (i == j) {
                w[i][i] = q[i];
                c[i][i] = 0;
                r[i][i] = 0;
                printf("w[%d][%d] : %d \t c[%d][%d]: %d \t r[%d][%d] : %d\n", i, j, w[i][j], i, j, c[i][j], i, j, r[i][j]);
            }
        }
    }
    printf("\n");

    // Fill w, c, and r matrices for ranges [i, j]
    for (b = 0; b < n; b++) {
        for (i = 0, j = b + 1; j <= n; i++, j++) {
            if (i != j && i < j) {
                // Calculate w[i][j]
                w[i][j] = w[i][j - 1] + p[j] + q[j];
                min = INF;

                // Find minimum cost and root for this subproblem
                for (k = i + 1; k <= j; k++) {
                    min1 = c[i][k - 1] + c[k][j] + w[i][j];
                    if (min > min1) {
                        min = min1;
                        temp = k;
                    }
                }

                // Store minimum cost and root for this range
                c[i][j] = min;
                r[i][j] = temp;
            }
            // Print w[i][j], c[i][j], and r[i][j]
            printf("w[%d][%d] : %d \t c[%d][%d]: %d \t r[%d][%d] : %d\n", i, j, w[i][j], i, j, c[i][j], i, j, r[i][j]);
        }
        printf("\n");
    }

    // Print minimum cost for the entire tree
    printf("Minimum cost: %d\n", c[0][n]);
}
Output:
/tmp/VsdNZE6fYV.o
Enter the number of elements: 4
Enter the element P(1): 3
Enter the element P(2): 3
Enter the element P(3): 1
Enter the element P(4): 1

Enter the element q(0): 2
Enter the element q(1): 3
Enter the element q(2): 1
Enter the element q(3): 1
Enter the element q(4): 1

W 		 C 		 R
w[0][0] : 2 	 c[0][0]: 0 	 r[0][0] : 0
w[1][1] : 3 	 c[1][1]: 0 	 r[1][1] : 0
w[2][2] : 1 	 c[2][2]: 0 	 r[2][2] : 0
w[3][3] : 1 	 c[3][3]: 0 	 r[3][3] : 0
w[4][4] : 1 	 c[4][4]: 0 	 r[4][4] : 0

w[0][1] : 8 	 c[0][1]: 8 	 r[0][1] : 1
w[1][2] : 7 	 c[1][2]: 7 	 r[1][2] : 2
w[2][3] : 3 	 c[2][3]: 3 	 r[2][3] : 3
w[3][4] : 3 	 c[3][4]: 3 	 r[3][4] : 4

w[0][2] : 12 	 c[0][2]: 19 	 r[0][2] : 1
w[1][3] : 9 	 c[1][3]: 12 	 r[1][3] : 2
w[2][4] : 5 	 c[2][4]: 8 	 r[2][4] : 3

w[0][3] : 14 	 c[0][3]: 25 	 r[0][3] : 2
w[1][4] : 11 	 c[1][4]: 19 	 r[1][4] : 2

w[0][4] : 16 	 c[0][4]: 32 	 r[0][4] : 2

Minimum cost: 32


=== Code Exited With Errors ===
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>External Style Example</title>
    <!-- Link to the external CSS file -->
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h1 class="heading">Welcome to External CSS Styling</h1>
        <p class="text">This is an example using external styling. All CSS rules are in a separate file.</p>
        <p class="text highlight">This paragraph uses both the `text` and `highlight` classes.</p>
    </div>
</body>
</html>
------
CSS (styles.css):
/* External CSS file: styles.css */

body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
    margin: 0;
    padding: 0;
}

.container {
    padding: 40px;
    background-color: #ffffff;
    border: 1px solid #ddd;
    max-width: 800px;
    margin: 20px auto;
}

.heading {
    color: #333;
    text-align: center;
    padding: 20px;
}

.text {
    color: #666;
    font-size: 18px;
    line-height: 1.6;
    margin: 20px;
}

.highlight {
    color: #0056b3;
    font-weight: bold;
}

Task-5
Implement Dijkstra's algorithm to compute the shortest path through a graph.
Algorithm:
Algorithm ShortestPaths(v, cost, dist, n)
// dist[j], 1 ≤ j ≤ n, is set to the length of the shortest
// path from vertex v to vertex j in a digraph G with n
// vertices. dist[v] is set to zero. G is represented by its
// cost adjacency matrix cost[1 : n, 1 : n].
{
  for i := 1 to n do
  { // Initialize S.
    S[i] := false; dist[i] := cost[v, i];
  }
  S[v] := true; dist[v] := 0.0; // Put v in S.
  for num := 2 to n − 1 do
  {
    // Determine n − 1 paths from v.
    Choose u from among those vertices not
    in S such that dist[u] is minimum;
    S[u] := true; // Put u in S.
    for (each w adjacent to u with S[w] = false) do
    // Update distances.
    if (dist[w] > dist[u] + cost[u, w]) then
      dist[w] := dist[u] + cost[u, w];
  }
}
Program:
#include <stdio.h> 
#include <limits.h>
#define M 8

int n;

void spath(int graph[n][n], int u) {
    int dist[M];
    int s[M] = {0};
    for (int i = 0; i < n; i++) {
        dist[i] = INT_MAX;
    }
    dist[u] = 0;
    for (int i = 0; i < n - 1; i++) {
        int v;
        int min = INT_MAX;
        for (int j = 0; j < n; j++) {
            if (dist[j] < min && s[j] == 0) {
                min = dist[j];
                v = j;
            }
        }
        s[v] = 1;
        for (int j = 0; j < n; j++) {
            if (graph[v][j] != 0 && s[j] == 0) {
                if (dist[j] > dist[v] + graph[v][j]) {
                    dist[j] = dist[v] + graph[v][j];
                }
            }
        }
    }
    for (int i = 0; i < n; i++) {
        printf("%d ", dist[i]);
    }
    printf("\n");
}

int main() {
    printf("Enter the number of vertices (up to %d): ", M);
    scanf("%d", &n);

    int graph[M][M];
    printf("Enter the adjacency matrix (use 0 for no direct path):\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            scanf("%d", &graph[i][j]);
        }
    }

    int startNode;
    printf("Enter the starting node (0 to %d): ", n - 1);
    scanf("%d", &startNode);

    spath(graph, startNode);
    return 0;
}
Output:
/tmp/q6mNdkXwgB.o
Enter the number of vertices (up to 8): 8
Enter the adjacency matrix (use 0 for no direct path):
0 0 0 0 0 0 0 0
300 0 0 0 0 0 0 0
1000 800 0 0 0 0 0 0
0 0 1200 0 0 0 0 0
0 0 0 1500 0 250 0 0
0 0 0 1000 0 0 900 1400
0 0 0 0 0 0 0 1000
1700 0 0 0 0 0 0 0
Enter the starting node (0 to 7): 4
3350 3250 2450 1250 0 250 1150 1650 


=== Code Execution Successful ===
Task-4
Implement Fractional Knapsack Algorithm
Algorithm:
Algorithm Sort(p, w, n){
  int r[n], index[n];
  int p[n], w[n];
  
  for i := 1 to n
    r[i] := p[i] / w[i];
  
  for i := n to n do{
    j := i;
    for k := i + 1 to n do
      if (r[k] <= r[j]) then 
	j := k;
    if(j!-i){
     index[i] := j;
     t := r[i];
     r[i] := r[j];
     r[j] := t;
    }
  }
  
  for i := 1 to n
  {
    p[i] := p[index[i]];
    w[i] := w[index[i]];
  }
}
Program:
#include <stdio.h>

void knapsack(int n, float weight[], float profit[], float capacity) {
    float tp = 0;
    int i, u;
    u = capacity;
    for (i = 0; i < n; i++) {
        if (weight[i] > u)
            break;
        else {
            tp = tp + profit[i];
            u = u - weight[i];
        }
    }
    if (i < n)
        tp = tp + (u / weight[i] * profit[i]);
    printf("\nMaximum profit is:- %f", tp);
}

int main() {
    float weight[20], profit[20], capacity;
    int num, i, j;
    float ratio[20], temp;

    printf("\nEnter the no. of objects:- ");
    scanf("%d", &num);

    printf("\nEnter the wts and profits of each object:-\n");
    for (i = 0; i < num; i++) {
        scanf("%f %f", &weight[i], &profit[i]);
    }

    printf("\nEnter the capacity of knapsack:- ");
    scanf("%f", &capacity);

    // Calculate profit/weight ratio
    for (i = 0; i < num; i++) {
        ratio[i] = profit[i] / weight[i];
    }

    // Sort items by profit/weight ratio in descending order
    for (i = 0; i < num; i++) {
        for (j = i + 1; j < num; j++) {
            if (ratio[i] < ratio[j]) {
                // Swap ratios
                temp = ratio[j];
                ratio[j] = ratio[i];
                ratio[i] = temp;

                // Swap weights and profits to keep arrays aligned
                temp = weight[j];
                weight[j] = weight[i];
                weight[i] = temp;

                temp = profit[j];
                profit[j] = profit[i];
                profit[i] = temp;
            }
        }
    }

    knapsack(num, weight, profit, capacity);
    return 0;
}
Output:
Enter the no. of objects:- 5
Enter the wts and profits of each object:-
4 12
1 2
2 2
1 1
4 10
Enter the capacity of knapsack:- 15
Maximum profit is:- 17.333334

=== Code Execution Successful ===
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Internal Style Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            padding: 0;
        }
        
        #main-content {
            padding: 40px;
            background-color: #ffffff;
            border: 1px solid #ddd;
            max-width: 800px;
            margin: 20px auto;
        }
        
        h1 {
            color: #333;
            text-align: center;
            padding: 20px;
        }
        
        p {
            color: #666;
            font-size: 18px;
            line-height: 1.6;
            margin: 20px;
        }
        
        p.highlight {
            color: #0056b3;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div id="main-content">
        <h1>Welcome to Internal CSS Styling</h1>
        <p>This is an example of internal styling. All CSS rules are within a style block in the head section.</p>
        <p class="highlight">This paragraph has specific styling defined in the internal CSS.</p>
    </div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inline Style Example</title>
</head>
<body style="font-family: Arial, sans-serif; background-color: #f0f0f0; margin: 0; padding: 0;">
    <div style="padding: 40px; background-color: #ffffff; border: 1px solid #ddd; max-width: 800px; margin: 20px auto;">
        <h1 style="color: #333; text-align: center; padding: 20px;">Welcome to Inline CSS Styling</h1>
        <p style="color: #666; font-size: 18px; line-height: 1.6; margin: 20px;">
            This is an example of inline styling. All CSS rules are directly within the HTML elements.
        </p>
        <p style="color: #0056b3; font-weight: bold; margin: 20px;">
            This paragraph uses inline styling for specific text color and font weight.
        </p>
    </div>
</body>
</html>
star

Sun Nov 03 2024 17:44:24 GMT+0000 (Coordinated Universal Time)

@varuntej #python

star

Sun Nov 03 2024 17:30:06 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 17:12:12 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 16:59:56 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 16:33:59 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 16:32:11 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 16:29:47 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 16:16:49 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 16:14:42 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 16:12:09 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 16:03:11 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 15:51:24 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 15:25:33 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 15:24:38 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 15:14:08 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 15:09:35 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 15:08:03 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 15:05:37 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 14:32:45 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 14:20:01 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 14:13:08 GMT+0000 (Coordinated Universal Time)

@sem

star

Sun Nov 03 2024 14:12:41 GMT+0000 (Coordinated Universal Time)

@sem

star

Sun Nov 03 2024 14:11:41 GMT+0000 (Coordinated Universal Time)

@sem

star

Sun Nov 03 2024 14:11:02 GMT+0000 (Coordinated Universal Time)

@sem

star

Sun Nov 03 2024 14:10:18 GMT+0000 (Coordinated Universal Time)

@sem

star

Sun Nov 03 2024 14:09:30 GMT+0000 (Coordinated Universal Time)

@sem

star

Sun Nov 03 2024 13:56:40 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 13:55:40 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 13:54:31 GMT+0000 (Coordinated Universal Time)

@login123

star

Sun Nov 03 2024 13:52:10 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 13:45:01 GMT+0000 (Coordinated Universal Time)

@varuntej #python

star

Sun Nov 03 2024 13:34:53 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 13:30:43 GMT+0000 (Coordinated Universal Time)

@signup_returns #html

star

Sun Nov 03 2024 13:27:38 GMT+0000 (Coordinated Universal Time)

@varuntej #python

star

Sun Nov 03 2024 13:14:38 GMT+0000 (Coordinated Universal Time)

@varuntej #python

star

Sun Nov 03 2024 12:49:12 GMT+0000 (Coordinated Universal Time)

@varuntej #c

star

Sun Nov 03 2024 12:49:09 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 12:48:01 GMT+0000 (Coordinated Universal Time)

@varuntej #c

star

Sun Nov 03 2024 12:45:43 GMT+0000 (Coordinated Universal Time)

@varuntej #c

star

Sun Nov 03 2024 12:45:37 GMT+0000 (Coordinated Universal Time)

@signup1

star

Sun Nov 03 2024 12:43:54 GMT+0000 (Coordinated Universal Time)

@signup1

Save snippets that work with our extensions

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