Snippets Collections
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
  }
}
import java.util.Arrays;

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]);
  }
}



  }
}
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));

}
}
import java.util.Arrays;

class Main{
  public static void main (String[] args) {

    int [][] arr1 = {{1, 2, 3}, {4, 5}};

System.out.println (arr1[1][0]);

}
}
import java.util.Arrays;

class Main{
  public static void main (String[] args) {

    int [][] arr1 = {{1, 2, 3}, {4, 5}};

System.out.println (arr1[0][1]);

}
}
      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));

  }
}
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));

  }
}
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 (arr1 == arr2);

  }
}
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));
  }
}
    //

    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
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>