Thursday, January 18, 2024

Sort an array of 0s, 1s and 2s | Dutch National Flag problem

Sort an array of 0s, 1s and 2s |

Dutch National Flag problem


👀👀👀👀👀


/*

* This program defines a sortArray() method that sorts

* an array of 0s, 1s, and 2s using

* the Dutch National Flag algorithm.

*/


public class Sort012 {


public static void swap(int[] arr,int i,int j) {

int temp;

temp=arr[i];

arr[i]=arr[j];

arr[j]=temp;

}

public static void sortArray(int[] arr) {

int low =0;

int mid =0;

int high =arr.length-1;

while(mid<=high) {

switch (arr[mid]) {

case 0:

swap(arr,low,mid);

low++;

mid++;

break;

case 1:

mid++;

break;

case 2:

swap(arr,mid,high);

high--;

break;

default:

break;

}

}

}


public static void main(String... aa) {

int arr[]= {2,0,1,0,2,1,2,0,1,0,2,1};

sortArray(arr);

for(int i:arr) {

System.out.print(i+" ");

}

}

}


Output:

0 0 0 0 1 1 1 1 2 2 2 2



Wednesday, January 17, 2024

Merge two sorted linked lists


Merge two sorted linked lists


public class MergeLinkedLists {

static class ListNode {

int val;

ListNode next;

public ListNode() {}


public ListNode(int val) {

this.val = val;

}


public ListNode(int val, ListNode next) {

this.val = val;

this.next = next;

}

}

public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {

ListNode mergedList = new ListNode();

ListNode current = mergedList;


while (list1 != null && list2 != null) {

if (list1.val <= list2.val) {

current.next = list1;

list1 = list1.next;

} else {

current.next = list2;

list2 = list2.next;

}

current = current.next;

}


if (list1 != null) {

current.next = list1;

} else {

current.next = list2;

}


return mergedList.next;

}


public static void main(String[] args) {

// Example usage:

ListNode list1 = new ListNode(1, new ListNode(2, new ListNode(4)));

ListNode list2 = new ListNode(1, new ListNode(3, new ListNode(4)));


ListNode mergedList = mergeTwoLists(list1, list2);

while (mergedList != null) {

System.out.print(mergedList.val + " ");

mergedList = mergedList.next;

}

}

}


Time Complexity: O(M + N), Where M and N are the size of the list1 and list2 respectively.
Auxiliary Space: O(M+N), Function call stack space


Output:


1 1 2 3 4 4


Geeks link:

    Merge To Linked List


Monday, January 15, 2024

Python script to automate login and extract cookie

 pip install requests

*****************create file*****************

import requests

url_login = "https://example.com/login" # Replace with the actual login URL url_after_login = "https://example.com/next" # Replace with the actual URL after login # Replace with your actual username and password payload = { "username": "your_username", "password": "your_password" } # Create a session to persist cookies session = requests.Session() # Perform the login response_login = session.post(url_login, data=payload) # Check if login was successful (replace '200' with the appropriate success status code) if response_login.status_code == 200: print("Login successful") # Perform the action after login (e.g., skip OTP) response_after_login = session.get(url_after_login) # Get the value of the desired cookie (replace 'cookie_name' with the actual cookie name) cookie_value = session.cookies.get("cookie_name") if cookie_value: print(f"The value of the cookie is: {cookie_value}") else: print("The desired cookie was not found.") else: print("Login failed.")

**********************************************

save login_script.py
python login_script.py

Thursday, January 4, 2024

Graph QL Simple working example

Here's a simple working tutorial on creating a GraphQL server using Node.js and Express, with a basic query and mutation. We'll be using the Apollo Server Express library to create the GraphQL server.

  1. Install Node.js: If you don't have Node.js installed, download and install it from the official website: https://nodejs.org/
  1. Create a new project folder: Create a new folder for your project and navigate to it in your terminal or command prompt.
  1. Initialize the project: Run the following command to initialize a new Node.js project:


npm init -y

  1. Install required packages: Install Express, Apollo Server Express, and GraphQL using the following command:

npm install express apollo-server-express graphql

  1. Create the GraphQL schema: Create a file named schema.graphql in your project folder and add the following schema definition:

type Query { hello: String } type Mutation { setMessage(message: String!): String }

Here we define a simple query hello that returns a string and a mutation setMessage that takes a string as input and returns a string.

  1. Create the server: Create a file named index.js in your project folder and add the following code:

const express = require("express"); const { ApolloServer, gql } = require("apollo-server-express"); const fs = require("fs"); // Read the schema from the schema.graphql file const typeDefs = gql(fs.readFileSync("schema.graphql", "utf8")); // Set up the resolvers const resolvers = { Query: { hello: () => "Hello, world!", }, Mutation: { setMessage: (_, { message }) => message, }, }; // Create the Apollo Server const server = new ApolloServer({ typeDefs, resolvers }); // Create the Express app const app = express(); // Apply the Apollo middleware to the Express app server.applyMiddleware({ app }); // Start the server const PORT = process.env.PORT || 4000; app.listen(PORT, () => console.log(`GraphQL server running at http://localhost:${PORT}${server.graphqlPath}`) );

In this code, we create a simple Express app and an Apollo Server with the schema and resolvers. The hello query returns a static string, and the setMessage mutation returns the input message.

  1. Start the server: Run the following command in your terminal or command prompt:

node index.js

Your GraphQL server should now be running at http://localhost:4000/graphql.

  1. Test your GraphQL server: Open a web browser and navigate to http://localhost:4000/graphql. You should see the GraphQL Playground interface. Run the following query and mutation in the playground:

query { hello } mutation { setMessage(message: "This is a test message!") }

You should see the appropriate responses for the query and mutation.

That's it! You now have a simple working GraphQL server using Node.js, Express, and Apollo Server Express. You can expand the schema and resolvers to handle more complex data and operations as needed.

Saturday, November 4, 2023

Sorting on the basis of multiple fields

 function sortObjects(arr) {

arr.sort(function(a, b) { if (a.adviserid < b.adviserid) { return -1; } else if (a.adviserid > b.adviserid) { return 1; } else { if (a.cutomer_id < b.cutomer_id) { return -1; } else if (a.cutomer_id > b.cutomer_id) { return 1; } else { if (a.account_id < b.account_id) { return -1; } else if (a.account_id > b.account_id) { return 1; } else { if (a.product_type === b.product_type) { if (a.account_id > b.account_id) { return -1; } else if (a.account_id < b.account_id) { return 1; } } return 0; } } } }); // Group the array by adviserid var groupedArr = []; var currentAdviserId = null; for (var i = 0; i < arr.length; i++) { var obj = arr[i]; if (obj.adviserid !== currentAdviserId) { currentAdviserId = obj.adviserid; groupedArr.push([]); } groupedArr[groupedArr.length - 1].push(obj); } return groupedArr; }

Here's how you would use this function:

// Example array of objects var arr = [ { adviserid: 1, cutomer_id: "abc", account_id: 10, product_type: "A" }, { adviserid: 1, cutomer_id: "abc", account_id: 20, product_type: "A" }, { adviserid: 1, cutomer_id: "def", account_id: 30, product_type: "B" }, { adviserid: 2, cutomer_id: "ghi", account_id: 40, product_type: "A" } ]; // Call the function to sort the array var sortedArr = sortObjects(arr); // Print the sorted array console.log(sortedArr);

In this example, the arr array contains four objects with adviserid, cutomer_id, account_id, and product_type properties. The sortObjects function sorts the array based on the three fields you specified (in ascending order), and then groups the sorted array by adviserid. The sorted and grouped array is then printed to the console.

In the sorting logic, the function first sorts by adviserid, then by cutomer_id, and then by account_id. If two objects have the same product_type, they are sorted by account_id in descending order. If two objects have the same adviserid, they are grouped together in the output array.




Sure, here's an example JavaScript function that sorts an array of objects based on the three fields you specified:

function sortObjects(arr) { arr.sort(function(a, b) { if (a.adviserId < b.adviserId) { return -1; } else if (a.adviserId > b.adviserId) { return 1; } else { if (a.priority < b.priority) { return -1; } else if (a.priority > b.priority) { return 1; } else { if (a.accountId < b.accountId) { return 1; } else if (a.accountId > b.accountId) { return -1; } else { return 0; } } } }); return arr; } // Example array of objects var arr = [ { adviserId: 2, priority: 1, accountId: 10 }, { adviserId: 1, priority: 2, accountId: 20 }, { adviserId: 1, priority: 2, accountId: 30 }, { adviserId: 2, priority: 1, accountId: 40 } ]; // Print the input array console.log("Input: ", arr); // Call the function to sort the array var sortedArr = sortObjects(arr); // Print the sorted array console.log("Output: ", sortedArr);

In this example, the arr array contains four objects with adviserId, priority, and accountId properties. The sortObjects function sorts the array based on the three fields you specified, with priority being sorted in ascending order. If two objects have the same priority, they are sorted by accountId in descending order. The input and output arrays are then printed to the console.

The output of this function will be:

Input: [ { adviserId: 2, priority: 1, accountId: 10 }, { adviserId: 1, priority: 2, accountId: 20 }, { adviserId: 1, priority: 2, accountId: 30 }, { adviserId: 2, priority: 1, accountId: 40 } ] Output: [ { adviserId: 1, priority: 2, accountId: 30 }, { adviserId: 1, priority: 2, accountId: 20 }, { adviserId: 2, priority: 1, accountId: 40 }, { adviserId: 2, priority: 1, accountId: 10 } ]

Wednesday, August 2, 2023

Decorator Design Pattern

Decorator Design Pattern in Java


The Decorator design pattern is a structural pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. It is used when we want to add new functionality to an object without modifying its structure.


The pattern involves creating a decorator class, which wraps the original object and provides additional functionality by dynamically adding new behavior to it. The decorator class has the same interface as the original object, allowing it to be used interchangeably with the original object.


The Decorator pattern consists of four main components:


  1. Component: This is the interface that defines the methods that will be implemented by the concrete components and decorators.
  1. Concrete Component: This is the class that provides the basic implementation of the component interface.
  1. Decorator: This is the abstract class that implements the component interface and contains a reference to the component object. The decorator class has a constructor that takes a component object as an argument, and it can add new behavior to the component by overriding its methods.
  1. Concrete Decorator: This is the class that extends the decorator class and adds new behavior to the component.

The Decorator pattern is useful when we want to add new functionality to an object at runtime, without modifying its structure. It allows us to mix and match different behaviors dynamically, providing greater flexibility and modularity to the code.



Example:


//Component interface

interface Pizza {

 public String getDescription();

 public double getCost();

}




//Concrete component

class BasicPizza implements Pizza {

 public String getDescription() {

     return "Pizza with tomato sauce and cheese";

 }

 public double getCost() {

     return 10.00;

 }

}




//Decorator

abstract class ToppingDecorator implements Pizza {

 protected Pizza decoratedPizza;

 public ToppingDecorator(Pizza pizza) {

     decoratedPizza = pizza;

 }

 public String getDescription() {

     return decoratedPizza.getDescription();

 }

 public double getCost() {

     return decoratedPizza.getCost();

 }

}




//Concrete decorator

class Pepperoni extends ToppingDecorator {

 public Pepperoni(Pizza pizza) {

     super(pizza);

 }

 public String getDescription() {

     return decoratedPizza.getDescription() + ", pepperoni";

 }

 public double getCost() {

     return decoratedPizza.getCost() + 2.50;

 }

}




//Client code

public class DecoratorPizzaShop {

 public static void main(String[] args) {

     Pizza basicPizza = new BasicPizza();

     System.out.println("Basic pizza: " + basicPizza.getDescription() + " - Cost: $" + basicPizza.getCost());


     Pizza pepperoniPizza = new Pepperoni(basicPizza);

     System.out.println("Pepperoni pizza: " + pepperoniPizza.getDescription() + " - Cost: $" + pepperoniPizza.getCost());

 }

}


//Output:


Basic pizza: Pizza with tomato sauce and cheese - Cost: $10.0

Pepperoni pizza: Pizza with tomato sauce and cheese, pepperoni - Cost: $12.5


In this example, we have a Pizza interface that defines the methods for getting the description and 
cost of a pizza. 


The BasicPizza class is a concrete implementation of the Pizza interface.


The ToppingDecorator abstract class is a decorator that implements the Pizza interface and contains 
an instance of the Pizza interface. 


The Pepperoni class is a concrete decorator that extends the ToppingDecorator class 
and adds a pepperoni topping to the pizza.


In the PizzaShop class, we create a basic pizza and a pepperoni pizza using the decorator pattern. 
We first create a BasicPizza object, and then we create a Pepperoni object that takes the BasicPizza object as a parameter in its constructor. 


This creates a pizza with tomato sauce, cheese, and pepperoni. We then print out the descriptions 
and costs of both pizzas.




Sunday, July 9, 2023

Java (JVM) Memory Model - Switches

 

VM SwitchVM Switch Description
-XmsFor setting the initial heap size when JVM starts
-XmxFor setting the maximum heap size.
-XmnFor setting the size of the Young Generation, rest of the space goes for Old Generation.
-XX:PermGenFor setting the initial size of the Permanent Generation memory
-XX:MaxPermGenFor setting the maximum size of Perm Gen
-XX:SurvivorRatioFor providing ratio of Eden space and Survivor Space, for example if Young Generation size is 10m and VM switch is -XX:SurvivorRatio=2 then 5m will be reserved for Eden Space and 2.5m each for both the Survivor spaces. The default value is 8.
-XX:NewRatioFor providing ratio of old/new generation sizes. The default value is 2.

Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > ...

Followers

Search This Blog

Popular Posts