Snippets Collections
src/main/java
    +- com
        +- example
            +- Application.java
            +- ApplicationConstants.java
                +- configuration
                |   +- ApplicationConfiguration.java
                +- controller
                |   +- ApplicationController.java
                +- dao
                |   +- impl
                |   |   +- ApplicationDaoImpl.java
                |   +- ApplicationDao.java
                +- dto
                |   +- ApplicationDto.java
                +- service
                |   +- impl
                |   |   +- ApplicationServiceImpl.java
                |   +- ApplicationService.java
                +- util
                |   +- ApplicationUtils.java
                +- validation
                |   +- impl
                |   |   +- ApplicationValidationImpl.java
                |   +- ApplicationValidation.java
@Override
    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof WrongVoucher))
            return false;
        WrongVoucher other = (WrongVoucher)o;
        boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null)
                || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode));
        boolean storeEquals = (this.store == null && other.store == null)
                || (this.store != null && this.store.equals(other.store));
        return this.amount == other.amount && currencyCodeEquals && storeEquals;
    }
package com.company;
import java.util.Scanner;

public class CWH_05_TakingInpu {
    public static void main(String[] args) {
        System.out.println("Taking Input From the User");
        Scanner sc = new Scanner(System.in);
//        System.out.println("Enter number 1");
//        int a = sc.nextInt();
//        float a = sc.nextFloat();
//        System.out.println("Enter number 2");
//        int b = sc.nextInt();
//        float b = sc.nextFloat();

//        int sum = a +b;
//        float sum = a +b;
//        System.out.println("The sum of these numbers is");
//        System.out.println(sum);
//        boolean b1 = sc.hasNextInt();
//        System.out.println(b1);
//        String str = sc.next();
        String str = sc.nextLine();
        System.out.println(str);

    }
}
Scanner S = new Scanner(System.in);  //(Read from the keyboard)
int a = S.nextInt();  //(Method to read from the keyboard)
import java.util.Scanner;  // Importing  the Scanner class
Scanner sc = new Scanner(System.in);  //Creating an object named "sc" of the Scanner class.
  public static void setData(Object object){
    for (Field field : object.getClass().getDeclaredFields()) {
      field.setAccessible(true);
      try {
        String value = String.valueOf(field.get(object));
        if ("null".equals(value)){
          field.set(object, "test");
        }
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  }
  public static void setData(Object object){
    for (Field field : object.getClass().getDeclaredFields()) {
      field.setAccessible(true);
      try {
        String value = String.valueOf(field.get(object));
        if ("null".equals(value)){
          field.set(object, "test");
        }
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  }
public class Word {
    private char[] tab;
    private int pole = 0;

    public Word() {
        tab = new char[100];
        for (int i = 0; i < tab.length; ++i) {
            tab[i] = 0;
        }
    }

    public void addChar(char add) {
        tab[pole] = add;
        pole++;
    }

    public void show() {
        for (int i = 0; i < tab.length; ++i) {
            if (tab[i] == 0) {
                break;
            } else {
                System.out.print(tab[i] + " ");
            }
        }
    }

    public int length(){
        int k=0;
        for(int i=0; i <= tab.length; i++){
            if(tab[i] == 0)
                break;
            else{
                k++;
            }
        }
        return k;
    }
}
public class PrefixProblem {
    static class Node {
        Node[] children = new Node[26];
        boolean endOfWord = false;
        int freq;

        Node() {
            for (int i = 0; i < 26; i++) children[i] = null;
            freq=1;
        }
    }

    public static Node root = new Node();

    public static void insert(String key){
        Node curr=root;
        for(int i=0;i<key.length();i++){
            int idx=key.charAt(i)-'a';
            if(curr.children[idx]==null){
                curr.children[idx]=new Node();
            }
            else curr.children[idx].freq++;
            curr=curr.children[idx];
        }
        curr.endOfWord=true;
    }

    public static void findPrefix(Node root, String ans){
        if(root==null) return;
        if(root.freq == 1) {
            System.out.print(ans + " ");
            return;
        }
        for(int i=0;i<26;i++){
            if(root.children[i]!=null){
                findPrefix(root.children[i], ans+(char)(i+'a'));
            }
        }
    }


    public static void main(String[] args){
        String[] words={"zebra","dog","duck","dove"};
        for (String word : words) insert(word);
        root.freq=-1;
        findPrefix(root,"");
    }
}
public class Tries {
    static class Node {
        Node[] children = new Node[26];
        boolean endOfWord = false;

        Node() {
            for (int i = 0; i < 26; i++) children[i] = null;
        }
    }

    public static Node root = new Node();

    public static void insert(String word) {
        Node curr = root;
        for (int level = 0; level < word.length(); level++) {
            int idx = word.charAt(level) - 'a';
            if (curr.children[idx] == null) {
                curr.children[idx] = new Node();
            }
            curr = curr.children[idx];
        }
        curr.endOfWord = true;
    }

    public static boolean search(String key) {
        Node curr = root;
        for (int i = 0; i < key.length(); i++) {
            int idx = key.charAt(i) - 'a';
            if (curr.children[idx] == null) return false;
            curr = curr.children[idx];
        }
        return curr.endOfWord;
    }

    public static boolean stringBreak(String key) {
        if(key.length()==0) return true;
        for (int i = 1; i <= key.length(); i++) {
            String word1=key.substring(0,i);
            String word2=key.substring(i);
            if(search(word1) && stringBreak(word2)){
                return true;
            }
        }
        return false;
    }


    public static int countSubstrings(String word){
        for(int i=0;i<word.length();i++){
            insert(word.substring(i));
        }
        return countNodes(root);
    }
    public static int countNodes(Node root){
        if(root==null) return 0;
        int count=0;
        for(int i=0;i<26;i++){
            if(root.children[i]!=null){
                count+=countNodes(root.children[i]);
            }
        }
        return count+1;
    }

    public static String longestWord(String[] words){
        String str="";
        for (String word : words) insert(word);

        return str;
    }
    public static boolean isPresent(String word){
        for()
    }



    public static void main(String[] args) {
        String[] words = {"the", "there", "a", "any", "their", "i", "sam", "samsung","like"};
//        for (String word : words) {
//            insert(word);
//        }

    }
}
interface Language {
  public void getType();
  public void getVersion();
}
 BufferedReader in
   = new BufferedReader(new FileReader("foo.in"));
 
Scanner sc = new Scanner(ystem.in);    
sc.useLocale(Locale.ENGLISH);
List<Integer> numbers = new ArrayList<Integer>(
    Arrays.asList(5,3,1,2,9,5,0,7)
);

List<Integer> head = numbers.subList(0, 4);
List<Integer> tail = numbers.subList(4, 8);
System.out.println(head); // prints "[5, 3, 1, 2]"
System.out.println(tail); // prints "[9, 5, 0, 7]"

Collections.sort(head);
System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7]"

tail.add(-1);
System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7, -1]"
import java.util.ArrayList;

public class BST extends Trees{
    static ArrayList<Integer> arr=new ArrayList<>();
    public static node insert(int val, node root){
        if(root==null){
            root=new node(val);
            return root;
        }
        if(val<root.data)
            root.left=insert(val,root.left);
        else
            root.right = insert(val,root.right);
        return root;
    }

    public static void inorder(node root){
        if(root==null) return;
        inorder(root.left);
        System.out.print(root.data +" ");
        inorder(root.right);
    }

    public static boolean find(node root, int val){
        if(root==null) return false;
        if(root.data==val) return true;
        if(val> root.data) return find(root.right,val);
        else return find(root.left,val);
    }

    public static node delete(node root, int val){
        if (root.data < val) root.right=delete(root.right,val);
        else if(root.data > val) root.left=delete(root.left,val);
        else {
            if(root.left==null && root.right==null){
                return null;
            }
            if(root.left==null) return root.right;
            else if(root.right==null) return root.left;
            else{
                node inorderSuccessor=findInorderSuccessor(root.right);
                root.data=inorderSuccessor.data;
                root.right=delete(root.right,inorderSuccessor.data);
            }
        }
        return  root;
    }
    public static node findInorderSuccessor(node root){
        while(root.left!=null){
            root=root.left;
        }
        return root;
    }

    public static void printInRange(node root, int k1, int k2){
        if(root==null) return ;
        if(root.data>=k1 && root.data<=k2){
            printInRange(root.left,k1,k2);
            System.out.print(root.data+" ");
            printInRange(root.right,k1,k2);
        }
        else if(root.data<k1) printInRange(root.right,k1,k2);
        else printInRange(root.left,k1,k2);
    }

    public static void printRoot2Leaf(node root, ArrayList<Integer> path){
        if(root==null) return;
        path.add(root.data);
        if(root.left==null && root.right==null)
            System.out.println(path);
        printRoot2Leaf(root.left,path);
        printRoot2Leaf(root.right,path);
        path.remove(path.size()-1);
    }

    public static boolean isValidBST(node root){
        INORDER(root);
        for(int i=0;i<arr.size()-1;i++){
            if(arr.get(i)> arr.get(i+1)) return false;
        }
        return true;
    }
    public static void INORDER(node root){
        if(root==null) return;
        INORDER(root.left);
        arr.add(root.data);
        INORDER(root.right);
    }

    public static node createBST(int[] arr,int st, int end){  //always taking mid-value of array and making it root
        if(st>end) return null;
        int mid=(st+end)/2;
        node root=new node(arr[mid]);
        root.left=createBST(arr,st,mid-1);
        root.right=createBST(arr,mid+1,end);
        return root;
    }

    public class info {
        boolean isBST;
        int size;
        int min;
        int max;

        public info(boolean isBST, int size, int min, int max){
            this.isBST=isBST;
            this.size=size;
            this.min=min;
            this.max=max;
        }
    }
    public static int maxBST=0;
    public info largestBST(node root){
        if(root==null) return new info(true,0,Integer.MAX_VALUE,Integer.MIN_VALUE);
        info leftInfo=largestBST(root.left);
        info rightInfo=largestBST(root.right);
        int size=leftInfo.size+rightInfo.size+1;
        int min=Math.min(root.data,Math.min(leftInfo.min, rightInfo.min));
        int max=Math.max(root.data,Math.max(leftInfo.max, rightInfo.max));
        if(root.data<= leftInfo.max||root.data>= rightInfo.min) {
            return new info(false,size,min,max);
        }
        if(leftInfo.isBST && rightInfo.isBST){
            maxBST=Math.max(maxBST,size);
            return new info(true,size,min,max);
        }
        return new info(false,size,min,max);
    }

    public static void main(String[] args) {
//        int[] arr = {8,5,3,1,4,6,10,11,14};
        int[] arr={3,5,6,8,10,11,12};
        node root=createBST(arr,0, arr.length-1);
        inorder(root);
    }
}
String propertiesJSON = obj.get("properties").toString();
                            Type listType = new TypeToken<ArrayList<Property>>() {
                            }.getType();
                            List<Property> propertyList = GsonProvider.getGson().fromJson(propertiesJSON, listType);
                            JsonObject properties = new JsonObject();
                            for (Property property : propertyList) {
                                properties.addProperty(property.key, property.value);
                            }
apiKey = System.getenv("SENDGRID_API_KEY");
#热部署生效
spring.devtools.restart.enabled: true
#设置重启的目录
#spring.devtools.restart.additional-paths: src/main/java
#classpath目录下的WEB-INF文件夹内容修改不重启
spring.devtools.restart.exclude: WEB-INF/**
import java.util.*;
import java.util.LinkedList;

public class Trees {
    public static class node{
        int data;
        node left,right;

        public node(int data){
            this.data=data;
            this.left=null;
            this.right=null;
        }
    }
    public static int height(node root){
        if(root==null) return 0;
        int lh=height(root.left);
        int rh=height(root.right);
        return Math.max(lh,rh)+1;
    }

    public static int count(node root){
        if(root==null) return 0;
        return count(root.right) + count(root.left) +1;
    }

    public static int sum(node root){
        if(root == null) return 0;
        return sum(root.left)+sum(root.right) + root.data;
    }

    public static int diameter(node root){
        if(root==null) return 0;
        int lh=height(root.left);
        int rh=height(root.right);
        int ld=diameter(root.left);
        int rd=diameter(root.right);
        int selfD=lh+rh+1;
        return Math.max(selfD,Math.max(ld,rd));
    }

    static class info{
        int diam;
        int ht;

        info(int diam,int ht){
            this.diam=diam;
            this.ht=ht;
        }
    }
    public static info Diameter(node root){
        if(root ==null) return new info(0,0);
        info leftInfo=Diameter(root.left);
        info rightInfo=Diameter(root.right);
        int ht=Math.max(leftInfo.ht, rightInfo.ht)+1;
        int diam=Math.max(Math.max(leftInfo.diam,rightInfo.diam), leftInfo.ht+rightInfo.ht+1);
        return new info(diam,ht);
    }

    public static boolean isSubtree(node root, node subRoot){
        if(root==null) return false;
        if(root.data==subRoot.data){
            if(isIdentical(root,subRoot))
                return true;
        }
        return isSubtree(root.left,subRoot)||isSubtree(root.right,subRoot);
    }

    public static boolean isIdentical(node root, node subRoot){
        if(root==null && subRoot==null) return true;
        else if (root==null||subRoot==null || root.data!=subRoot.data) return false;
        if(!isIdentical(root.left,subRoot.left)) return false;
        if(!isIdentical(root.right,subRoot.right)) return false;
        return true;
    }

    static class information{
        node node;
        int hd;
        public information(node node,int hd){
            this.node=node;
            this.hd=hd;
        }
    }
    public static void topView(node root){
        Queue<information> q=new LinkedList<>();
        HashMap<Integer,node> map = new HashMap<>();

        int min=0,max=0;
        q.add(new information(root,0));
        q.add(null);
        while(!q.isEmpty()){
            information curr=q.remove();
            if (curr == null) {
                if (q.isEmpty()) break;
                else q.add(null);
            }
            else{
                if(!map.containsKey(curr.hd)) map.put(curr.hd, curr.node);
                if(curr.node.left!=null) {
                    q.add(new information(curr.node.left, curr.hd - 1));
                    min = Math.min(min, curr.hd - 1);
                }
                if(curr.node.right!=null) {
                    q.add(new information(curr.node.right, curr.hd + 1));
                    max = Math.max(curr.hd + 1, max);
                }
            }
        }
        for(int i=min;i<=max;i++){
            System.out.print(map.get(i).data + " ");
        }
    }

    public static ArrayList<ArrayList<Integer>> levelOrder(node root){
    Queue<node> q=new LinkedList<>();
    ArrayList<Integer> arr=new ArrayList<>();
    ArrayList<ArrayList<Integer>> ans=new ArrayList<>();
    q.add(root);
    q.add(null);
    while(!q.isEmpty()){
        while(q.peek()!=null) {
            if (q.peek().left != null) q.add(q.peek().left);
            if (q.peek().right != null) q.add(q.peek().right);
            arr.add(q.peek().data);
            q.remove();
        }
            q.add(null);
            q.remove();
            ans.add(arr);
            arr=new ArrayList<>();
            if(q.size()==1 && q.peek()==null) break;
    }
    Collections.reverse(ans);
    return  ans;
    }

    public static void kLevel(node root, int level, int k){
        if(level==k){
            System.out.print(root.data + " ");
            return;
        }
        else{
            kLevel(root.left,level+1,k);
            kLevel(root.right,level+1,k);
        }
    }

    public static int lowestCommonAncestor(node root, int n1, int n2){
        // Store the paths of both nodes in arraylist and iterate
        ArrayList<node> path1=new ArrayList<>();
        ArrayList<node> path2=new ArrayList<>();
        getPath(root,n1,path1);
        getPath(root,n2,path2);
        int i=0;
        for(;i< path1.size()&&i< path2.size();i++){
            if(path1.get(i) != path2.get(i)) break;
        }
        return path1.get(i-1).data;
    }
    public static boolean getPath(node root, int n, ArrayList<node> path){
        if(root==null) return false;
        path.add(root);
        if(root.data==n) return true;
        boolean foundLeft=getPath(root.left,n,path);
        boolean foundRight=getPath(root.right,n,path);
        if(foundLeft||foundRight) return true;
        path.remove(path.size()-1);
        return false;
    }

    public static node lca(node root, int n1, int n2){
        //both the nodes belong to the same subtree of lca root.
        if( root==null || root.data==n1 || root.data==n2) return root;
        node leftLca=lca(root.left,n1,n2);
        node rightLca=lca(root.right,n1,n2);
        if(leftLca==null) return rightLca;
        if(rightLca==null) return leftLca;
        return root;
    }



    public static int minDistance(node root, int n1, int n2){
        node lca= lca(root,n1,n2);//calculate the separate distances from both the nodes to the lca.
        return distance(lca,n1) + distance(lca,n2);
    }
    public static int distance(node root, int n){
        //calculating the distance from root(lca) to the given node n.
        if(root==null) return -1;
        if(root.data==n) return 0;
        int leftDistance=distance(root.left,n);
        int rightDistance=distance(root.right,n);
        if(leftDistance==-1) return rightDistance+1;
        else return leftDistance+1;
    }

    public static int kthAncestor(node root, int n, int k){
        if(root==null) return -1;
        if(root.data==n) return 0;
        int leftDist=kthAncestor(root.left,n,k);
        int rightDist=kthAncestor(root.right,n,k);
        if(leftDist==-1 && rightDist==-1) return -1;
        int max=Math.max(leftDist,rightDist);
        if(max+1==k) System.out.println(root.data);
        return max+1;
    }


    public static int  sumTree(node root){
        if(root==null) return 0;
        int leftChild=sumTree(root.left);
        int rightChild=sumTree(root.right);
        int data=root.data;
        int newLeft=root.left==null?0:root.left.data;
        int newRight=root.right==null?0:root.right.data;
        root.data=leftChild + rightChild + newLeft+newRight;
        return data;
    }

    public static void preOrder(node root){
        if(root==null) return;
        System.out.print(root.data + " ");
        preOrder(root.left);
        preOrder(root.right);

    }

    public node removeLeafNodes(node root, int target) {
        if(root==null) return null;
        root.left=removeLeafNodes(root.left,target);
        root.right=removeLeafNodes(root.right,target);
        if(root.left==null && root.right==null){
            if(root.data==target) return null;
        }
        return root;
    }

    public node invertTree(node root) {
        if(root==null) return null;
        else if (root.left==null && root.right==null) return root;
        node m=invertTree(root.left);
        node n=invertTree(root.right);
        root.left=n;
        root.right=m;
        return root;
    }
    public static void main(String[] args){
        node root =new node(1);
        root.left=new node(2);
        root.right=new node(3);
        root.left.left=new node(4);
        root.left.right=new node(5);
        root.right.left=new node(6);
        root.right.right=new node(7);
        sumTree(root);
        preOrder(root);
    }
}
//One Thread method that a supervisor thread may use to monitor another thread is .isAlive(). This method returns true if the thread is still running, and false if it has terminated. A supervisor might continuously poll this value (check it at a fixed interval) until it changes, and then notify the user that the thread has changed state.

import java.time.Instant;
import java.time.Duration;
 
public class Factorial {
 public int compute(int n) {
   // the existing method to compute factorials
 }
 
 // utility method to create a supervisor thread
 public static Thread createSupervisor(Thread t) {
   Thread supervisor = new Thread(() -> {
     Instant startTime = Instant.now();
     // supervisor is polling for t's status
     while (t.isAlive()) {
       System.out.println(Thread.currentThread().getName() + " - Computation still running...");
       Thread.sleep(1000);
     }
   });
 
   // setting a custom name for the supervisor thread
   supervisor.setName("supervisor");
   return supervisor;
 
 }
 
 public static void main(String[] args) {
   Factorial f = new Factorial();
 
   Thread t1 = new Thread(() -> {
     System.out.println("25 factorial is...");
     System.out.println(f.compute(25));
   });
 
 
   Thread supervisor = createSupervisor(t1);
 
   t1.start();
   supervisor.start();
 
   System.out.println("Supervisor " + supervisor.getName() + " watching worker " + t1.getName());
 }
}
mport java.util.Random;

// Checkpoint 1
// public class CrystalBall implements Runnable {
  
public class CrystalBall{

  /* Instance Variables */
  // Removed in checkpoint 3
  /* Constructors */
  // Removed in checkpoint 3
  /* Instance Methods */
  // Removed in checkpoint 3

  public void ask(Question question) {
    System.out.println("Good question! You asked: " + question.getQuestion());
    this.think(question);
    System.out.println("Answer: " + this.answer());
  }

  private void think(Question question) {
    System.out.println("Hmm... Thinking");
    try {
      Thread.sleep(this.getSleepTimeInMs(question.getDifficulty()));
    } catch (Exception e) {
      System.out.println(e);
    }
    System.out.println("Done!");
  }

  private String answer() {
    String[] answers = {
        "Signs point to yes!",
        "Certainly!",
        "No opinion",
        "Answer is a little cloudy. Try again.",
        "Surely.",
        "No.",
        "Signs point to no.",
        "It could very well be!"
    };
    return answers[new Random().nextInt(answers.length)];
  }

  private int getSleepTimeInMs(Question.Difficulty difficulty) {
    switch (difficulty) {
      case EASY:
        return 1000;
      case MEDIUM:
        return 2000;
      case HARD:
        return 3000;
      default:
        return 500;
    }
  }
}

mport java.util.Random;

// Checkpoint 1
// public class CrystalBall implements Runnable {
  
public class CrystalBall{

  /* Instance Variables */
  // Removed in checkpoint 3

  /* Constructors */
  // Removed in checkpoint 3

  /* Instance Methods */
  // Removed in checkpoint 3

  public void ask(Question question) {
    System.out.println("Good question! You asked: " + question.getQuestion());
    this.think(question);
    System.out.println("Answer: " + this.answer());
  }

  private void think(Question question) {
    System.out.println("Hmm... Thinking");
    try {
      Thread.sleep(this.getSleepTimeInMs(question.getDifficulty()));
    } catch (Exception e) {
      System.out.println(e);
    }
    System.out.println("Done!");
  }

  private String answer() {
    String[] answers = {
        "Signs point to yes!",
        "Certainly!",
        "No opinion",
        "Answer is a little cloudy. Try again.",
        "Surely.",
        "No.",
        "Signs point to no.",
        "It could very well be!"
    };
    return answers[new Random().nextInt(answers.length)];
  }

  private int getSleepTimeInMs(Question.Difficulty difficulty) {
    switch (difficulty) {
      case EASY:
        return 1000;
      case MEDIUM:
        return 2000;
      case HARD:
        return 3000;
      default:
        return 500;
    }
  }
}
public class Factorial implements Runnable {
 private int n;
 
 public Factorial(int n) {
   this.n = n;
 }
 
 public int compute(int n) {
   // ... the code to compute factorials
 }
 
 public void run() {
   System.out.print("Factorial of " + String.valueOf(this.n) + ":")
   System.out.println(this.compute(this.n));
 }
 
 public static void main(String[] args) {
   Factorial f = new Factorial(25);
   Factorial g = new Factorial(10);
   Thread t1 = new Thread(f);
   Thread t2 = new Thread(f);
   t1.start();
   t2.start();
 }
}

//Another way of using the Runnable interface, which is even more succinct, is to use lambda expressions
public class Factorial {
 public int compute(int n) {
   // ... the code to compute factorials
 }
 
 public static void main(String[] args) {
   Factorial f = new Factorial();
 
   // the lambda function replacing the run method
   new Thread(() -> {
     System.out.println(f.compute(25));
   }).start();
 
   // the lambda function replacing the run method
   new Thread(() -> {
     System.out.println(f.compute(10));
   }).start();
 }
}
/*Extended the Thread Class
Created and Overrode a .run() method from Thread
Instantiated HugeProblemSolver and called .start() which signifies to start a new thread and search in the class for the .run() method to execute.*/
//CrystalBall
import java.util.Random;

public class CrystalBall extends Thread{
  private Question question;

  public CrystalBall(Question question){
    this.question = question;
    }

  @Override
  public void run() {
    ask(this.question);
  }


  private int getSleepTimeInMs(Question.Difficulty difficulty) {
    switch (difficulty) {
      case EASY:
        return 1000;
      case MEDIUM:
        return 2000;
      case HARD:
        return 3000;
      default:
        return 500;
    }
  }

  private String answer() {
    String[] answers = {
        "Signs point to yes!",
        "Certainly!",
        "No opinion",
        "Answer is a little cloudy. Try again.",
        "Surely.",
        "No.",
        "Signs point to no.",
        "It could very well be!"
    };
    return answers[new Random().nextInt(answers.length)];
  }

  private void think(Question question) {
    System.out.println("Hmm... Thinking");
    try {
      Thread.sleep(this.getSleepTimeInMs(question.getDifficulty()));
    } catch (Exception e) {
      System.out.println(e);
    }
    System.out.println("Done!");
  }

  public void ask(Question question) {
    System.out.println("Good question! You asked: " + question.getQuestion());
    this.think(question);
    System.out.println("Answer: " + this.answer());
  }
}

//FortuneTeller
import java.util.Arrays;
import java.util.List;

public class FortuneTeller {

  public static void main(String[] args) {

    List<Question> questions = Arrays.asList(
        new Question(Question.Difficulty.EASY, "Am I a good coder?"),
        new Question(Question.Difficulty.MEDIUM, "Will I be able to finish this course?"),
        new Question(Question.Difficulty.EASY, "Will it rain tomorrow?"),
        new Question(Question.Difficulty.EASY, "Will it snow today?"),
        new Question(Question.Difficulty.HARD, "Are you really all-knowing?"),
        new Question(Question.Difficulty.HARD, "Do I have any hidden talents?"),
        new Question(Question.Difficulty.HARD, "Will I live to be greater than 100 years old?"),
        new Question(Question.Difficulty.MEDIUM, "Will I be rich one day?"),
        new Question(Question.Difficulty.MEDIUM, "Should I clean my room?")
    );

    questions.stream().forEach(q -> {
      CrystalBall c = new CrystalBall(q);
      c.start();
    });
  }
}
//Shadowing allows for the overlapping scopes of members with the same name and type to exist in both a nested class and the enclosing class simultaneously. Depending on which object we use to call the same variable in a main method will result in different outputs.

class Book {
  String type="Nonfiction";
	// Nested inner class
	class Biography {
    String type="Biography";

    public void print(){
      System.out.println(Book.this.type);
      System.out.println(type);
    }

	}
}

public class Books {
	public static void main(String[] args) {
		Book book = new Book();
		Book.Biography bio = book.new Biography();
		bio.print();
	}
}
//Nonfiction
//Biography
class Lib { 
  String objType;
  String objName;
  static String libLocation = "Midfield St.";

  public Lib(String type, String name) {
    this.objType = type;
    this.objName = name;
  }

  private String getObjName() {
    return this.objName;
  }

  // inner class
  static class Book {
    String description;

    void printLibraryLocation(){
      System.out.println("Library location: "+libLocation);
    }
  }
}

public class Main {
  public static void main(String[] args) {
    Lib.Book book =  new Lib.Book();
    book.printLibraryLocation();

  }
}
class Lib {
  String objType;
  String objName;

  // Assign values using constructor
  public Lib(String type, String name) {
    this.objType = type;
    this.objName = name;
  }

  // private method
  private String getObjName() {
    return this.objName;
  }

  // Inner class
  class Book {
    String description;

    void setDescription() {
      if(Lib.this.objType.equals("book")) {
        if(Lib.this.getObjName().equals("nonfiction")) {
          this.description = "Factual stories/accounts based on true events";
        } else {
          this.description = "Literature that is imaginary.";
        }
      } else {
        this.description = "Not a book!";
        }
    }
    String getDescription() {
      return this.description;
    }
  }
}

public class Main {
  public static void main(String[] args) {
    Lib fiction = new Lib("book", "fiction");

    Lib.Book book1 = fiction.new Book();
    book1.setDescription();
    System.out.println("Fiction Book Description = " + book1.getDescription());
 
    Lib nonFiction = new Lib("book", "nonfiction");
    Lib.Book book2 = nonFiction.new Book();
    book2.setDescription();
    System.out.println("Non-fiction Book Description = " + book2.getDescription());
  }
}
class Outer {
  String outer;
  // Assign values using constructor
  public Outer(String name) {
    this.outer = name;
  }
 
  // private method
  private String getName() {
    return this.outer;
  }
}
 
  // Non-static nested class
  class Inner {
    String inner;
    String outer;
    
    public String getOuter() {
  // Instantiate outer class to use its method
  outer = Outer.this.getName();
}
package com.viettel.cyber.chatbot.utils;

import com.mongodb.DBObject;
import com.viettel.cyber.chatbot.conf.Configuration;
import com.viettel.cyber.chatbot.models.*;
import com.viettel.cyber.chatbot.models.mbi.ReportKD;
import com.viettel.cyber.chatbot.models.newapi.DbProperties;
import com.viettel.cyber.chatbot.models.newapi.auth.AuthInputNewApi;
import com.viettel.cyber.chatbot.models.newapi.statisticalData.StatisticalInputNewApi;
import com.viettel.cyber.chatbot.models.newapi.statisticalData.StatisticalOutputNewApi;
import com.viettel.cyber.chatbot.models.ttns.DbSearchObject;
import com.viettel.cyber.chatbot.models.ttns.Property;
import com.viettel.cyber.chatbot.thread.StatisticalThread;
import javafx.util.Pair;
import org.apache.commons.lang.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by haitm on 24/09/2019.
 */
public class MBIRawUtil {
    public static Logger LOG = LoggerFactory.getLogger(MBIRawUtil.class);

    public static StatisticalOutput getStatisticalData(String token, AuthInput authInput, String urlStatisticalData, MainInput mainInput) {
        try {
            StatisticalOutput statisticalOutput = new StatisticalOutput();
            statisticalOutput.setError(Configuration.getInstance().getConfig("error.nodata"));
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("User-token", token);

            if (mainInput.getFlag()) {
                DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
                Calendar c = Calendar.getInstance();
                int countLimit = 1;
                String date = mainInput.getToDate1();
                Date currentDate = dateFormat.parse(date);
                // convert date to calendar
                c.setTime(currentDate);

                // neu khong co ket qua ngay hien tai thi lui ngay lai vao call api
                ArrayList<Thread> listThread = new ArrayList<>();
                ArrayList<StatisticalThread> listStatisticcalThread = new ArrayList<>();
                ArrayList<MainInput> listMainInput = new ArrayList<>();

                while (countLimit < 3) {
                    MainInput tmpMainInput = (MainInput) SerializationUtils.clone(mainInput);
                    tmpMainInput.setFromDate1(dateFormat.format(c.getTime()));
                    tmpMainInput.setToDate1(dateFormat.format(c.getTime()));
                    StatisticalThread myThread = new StatisticalThread(token, tmpMainInput);
                    Thread th = new Thread(myThread);
                    th.start();
                    countLimit += 1;
                    listThread.add(th);
                    listStatisticcalThread.add(myThread);
                    listMainInput.add(tmpMainInput);
                    c.add(Calendar.DATE, -1);
                }

                for (Thread thread: listThread) {
                    thread.join();
                }
                int countFor = 0;
                for (StatisticalThread statisticalThread: listStatisticcalThread) {
                    StatisticalOutput tmpStatisticalOutput = statisticalThread.getStatisticalOutput();
                    if (tmpStatisticalOutput.getError() == null) {
                        if (tmpStatisticalOutput.getResponse().getSpeech() == null) {
                            statisticalOutput = tmpStatisticalOutput;
                            mainInput.setFromDate1(listMainInput.get(countFor).getFromDate1());
                            mainInput.setToDate1(listMainInput.get(countFor).getToDate1());
                            break;
                        }
                    }
                    countFor += 1;
                }
            } else {
                String output = RESTUtil.post(urlStatisticalData, GsonUtil.toJson(mainInput), headers);
                statisticalOutput = GsonUtil.parse(output, StatisticalOutput.class);
            }

            LOG.info("Result: " + GsonUtil.toJson(statisticalOutput));

            return statisticalOutput;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static ResponseOutput getPlanData(String token, AuthInput authInput, String urlPlanData, MainInput mainInput) {

        String useCache = Configuration.getInstance().getConfig("api.cache");
        ResponseOutput outputInRedis;
        if(useCache.equals("true")) {
            outputInRedis = RedisUtil.getResponseOutput(GsonUtil.toJson(mainInput), "plan");
        }else {
            outputInRedis = null;
        }
//        ResponseOutput outputInRedis = RedisUtil.getResponseOutput(GsonUtil.toJson(mainInput), "plan");

        if(outputInRedis == null){
            if (token == null) {
                System.out.println("khoi tao token");
                token = TokenAPIUtil.getToken(authInput);
            }
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("User-token", token);
            try {
                String output = RESTUtil.post(urlPlanData, GsonUtil.toJson(mainInput), headers);

                ResponseOutput planOutput = GsonUtil.parse(output, ResponseOutput.class);

                LOG.info("Result plan: " + GsonUtil.toJson(planOutput));

                RedisUtil.setResponseOutput(GsonUtil.toJson(mainInput), "plan", planOutput);
                return planOutput;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }else {
            return outputInRedis;
        }
    }

    public static ResponseOutput getGrowthData(String token, AuthInput authInput, String urlGrowthData, MainInput mainInput) {
        String useCache = Configuration.getInstance().getConfig("api.cache");
        ResponseOutput outputInRedis;
        if(useCache.equals("true")) {
            outputInRedis = RedisUtil.getResponseOutput(GsonUtil.toJson(mainInput), "growth");
        }else {
            outputInRedis = null;
        }
//        ResponseOutput outputInRedis = RedisUtil.getResponseOutput(GsonUtil.toJson(mainInput), "growth");

        if(outputInRedis == null) {

            if (token == null) {
                System.out.println("khoi tao token");
                token = TokenAPIUtil.getToken(authInput);
            }

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("User-token", token);
            try {
                String output = RESTUtil.post(urlGrowthData, GsonUtil.toJson(mainInput), headers);

                ResponseOutput growthOutput = GsonUtil.parse(output, ResponseOutput.class);

                LOG.info("input growth: " + GsonUtil.toJson(mainInput));
                LOG.info("Result growth: " + GsonUtil.toJson(growthOutput));

                RedisUtil.setResponseOutput(GsonUtil.toJson(mainInput), "growth", growthOutput);

                return growthOutput;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }else {
            return outputInRedis;
        }
    }

    public static ReportKD getDataReportKD(String token, AuthInput authInput, String urlReport, MainInput mainInput) {
        if (token == null) {
            System.out.println("khoi tao token");
            token = TokenAPIUtil.getToken(authInput);
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("User-token", token);
        try {
            String output = RESTUtil.post(urlReport, GsonUtil.toJson(mainInput), headers);

            ReportKD reportKD = GsonUtil.parse(output, ReportKD.class);

            LOG.info("Result Report: " + GsonUtil.toJson(reportKD));
            return reportKD;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static StatisticalOutputNewApi getStatisticDataNewApi(String token, AuthInputNewApi authInputNewApi, String urlStatisticalData, StatisticalInputNewApi inputNewApi) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", token);
        try {
            String output = RESTUtil.post(urlStatisticalData, GsonUtil.toJson(inputNewApi), headers);

          StatisticalOutputNewApi outputNewApi = GsonUtil.parse(output,StatisticalOutputNewApi.class);
//            LOG.info("Result statistical New API: " + GsonUtil.toJson(outputNewApi));
          System.out.println(outputNewApi.toString());
            return outputNewApi;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

//    search for parent
    public static List<Pair<String,String>> getParentServiceId(String id){
      String collectionName = Configuration.getInstance().getConfig("mongo.entities.collection");
        List<DBObject> parentService = MongoUtils.find(collectionName,id);
        if(parentService.size() >0){
          String parrentServiceID ="";
          parrentServiceID = (String) parentService.get(0).get("parent");

//          query for parentServeId
          if(parrentServiceID != null) {
            parentService = MongoUtils.find(collectionName, parrentServiceID);

            List<Pair<String,String>> myNameAndId = new ArrayList<>();
            myNameAndId.add(new Pair<>("name",(String) parentService.get(0).get("word")));
            String parentServiceId = getProperties("serviceId", parentService);
            myNameAndId.add(new Pair<>("serviceId",parentServiceId));
            return myNameAndId;
          }
        }
        return null;
    }

  public static List<Pair<String,String>> getParentUnitId(String unit,String areaCode){
    String collectionName = Configuration.getInstance().getConfig("mongo.entities.collection");
    String botID = Configuration.getInstance().getConfig("mongo.entities.bot_id");

//    Pair<String,Object> pair = new Pair<>();
    List<Pair<String, Property>> pairs = new ArrayList<>();
    pairs.add(new Pair<>("word",new Property(unit, Property.TYPE.EQUAL)));
    pairs.add(new Pair<>("bot_id",new Property(botID, Property.TYPE.EQUAL)));
//    Pair<String,Object> pair = new Pair<>("word",unit);


    List<DBObject> parentUnit = MongoUtils.find(collectionName,pairs);
    parentUnit = parentUnit.stream().filter(item ->(item.get("properties") != null)).collect(Collectors.toList());
    parentUnit = parentUnit.stream().filter(MBIRawUtil::filterUnitWithProperties).collect(Collectors.toList());
    if(parentUnit.size() >0){
//          String jsonObject = new JsonObject();
      String parentUnitID ="";
      Object propertyEntities = parentUnit.get(0).get("properties");
      String properties = "{\"properties\": " + propertyEntities.toString() + "}";
      DbProperties unitSyncDataToDb = GsonUtil.parse(properties, DbProperties.class);

      List<PropertyEntity> temp = unitSyncDataToDb.getProperties();
      for (PropertyEntity item:
           temp) {
        if (item.getKey().equals("areaCode")){
          if (item.getValue().equals(areaCode)){
            if (parentUnit.get(0).get("parent") != null) {
              parentUnitID = (String) parentUnit.get(0).get("parent");
            }
          }
          break;
        }
      }

      if(parentUnitID != null && !parentUnitID.equals("")){
        parentUnit = MongoUtils.find(collectionName, parentUnitID);
        List<Pair<String,String>> myNameAndId = new ArrayList<>();
        myNameAndId.add(new Pair<>("name",(String) parentUnit.get(0).get("word")));
        String parentAreaCode = getProperties("areaCode", parentUnit);
        myNameAndId.add(new Pair<>("areaCode",parentAreaCode));
        return myNameAndId;
      }
    }
    return null;
  }

  public static boolean filterUnitWithProperties(DBObject object){
    Object propertyEntities = object.get("properties");
    String properties = "{\"properties\": " + propertyEntities.toString() + "}";
    DbProperties unitSyncDataToDb = GsonUtil.parse(properties, DbProperties.class);
    return (unitSyncDataToDb.getProperties().size() > 0)? true : false;
  }
  public static String getProperties(String key, List<DBObject> objs){

      List<String> myNameAndId = new ArrayList<>();
    Object propertyEntities = objs.get(0).get("properties");
    String properties = "{\"properties\": " + propertyEntities.toString() + "}";
    DbProperties unitSyncDataToDb = GsonUtil.parse(properties, DbProperties.class);

    List<PropertyEntity> temp = unitSyncDataToDb.getProperties();
    for (PropertyEntity item:
      temp) {
      if (item.getKey().equals(key)){
          String value = item.getValue();
          return value;
      }
    }
    return null;
  }
  public static List<String> getPath(List<DBObject> lists, String n2Name,String n1AreaCode,String n1Path){
    List<DBObject> result;
    List<String> path = new ArrayList<>();
    result = lists.stream().filter(item -> item.get("word").toString().equalsIgnoreCase(n2Name)).collect(Collectors.toList());
    LOG.info("first search n2-paths: " + result.size());
    if (result.size() > 0){

      if (n1AreaCode == null){
        String json = GsonUtil.toJson(result.get(0));
        DbSearchObject dbSearchObject = GsonUtil.parse(json, DbSearchObject.class);
        List<PropertyEntity> areasList= dbSearchObject.getAreasList();
        areasList.forEach(item -> path.add(item.getValue()));
        return path;
      }else {
        String json = GsonUtil.toJson(result.get(0));
        DbSearchObject dbSearchObject = GsonUtil.parse(json, DbSearchObject.class);
        List<PropertyEntity> areasList= dbSearchObject.getAreasList();
//        filter for parent unit
        areasList = areasList.stream().filter(propertyEntity -> propertyEntity.getKey().equals(n1AreaCode)).collect(Collectors.toList());
        areasList = areasList.stream().filter(propertyEntity -> propertyEntity.getValue().contains(n1Path)).collect(Collectors.toList());

        if (areasList == null || areasList.size() == 0){
          return null;
        }else {
          path.add(areasList.get(0).getValue());
          return path;
        }
      }
    }else {
      return null;
    }
  }

}
// Given `intList` with the following elements: 5, 4, 1, 3, 7, 8
List<Integer> evenList = new ArrayList<>();
for(Integer i: intList) {
  if(i % 2 == 0) {
    evenList.add(i*2);
  }
}
// evenList will have elements 8, 16
/*A Stream is a sequence of elements created from a Collection source. A Stream can be used as input to a pipeline, which defines a set of aggregate operations (methods that apply transformations to a Stream of data). The output of an aggregate operation serves as the input of the next operation (these are known as intermediate operations) until we reach a terminal operation, which is the final operation in a pipeline that produces some non Stream output.*/
List<Integer> evenList = intList.stream()
  .filter((number) -> {return number % 2 == 0;})
  .map( evenNum -> evenNum*2)
  .collect(Collectors.toList());

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import java.util.Random;
public class Main {
  public static void main(String[] args) {
    List<Integer> myInts = new ArrayList<>();
    Random random = new Random();

    for(int i =0; i < 20; i++) {
      myInts.add(random.nextInt(5));
    }

    Map<Integer, Integer> intCount = countNumbers(myInts);
    for(Map.Entry<Integer, Integer> entry: intCount.entrySet()) {
      System.out.println("Integer: "+ entry.getKey()+" appears: "+ entry.getValue());
    }
  }

  public static Map<Integer, Integer> countNumbers(List<Integer> list) {
    Map<Integer, Integer> intCount = new TreeMap<>();
    for(Integer i: list){
      Integer currentCount = intCount.get(i);
      if(currentCount!=null){
        int newCount = currentCount+1;
        intCount.put(i, newCount);}
      else{intCount.put(i, 1);}
    }
    return intCount;
  }

}

/*
Output:
Integer: 0 appears: 3
Integer: 1 appears: 2
Integer: 2 appears: 8
Integer: 3 appears: 1
Integer: 4 appears: 6
//Map defines a generic interface for an object that holds key-value pairs as elements. The key is used to retrieve (like the index in an array or List) some value. A key must be unique and map to exactly one value.
//The HashMap defines no specific ordering for the keys and is the most optimized implementation for retrieving values.
//The LinkedHashMap keeps the keys in insertion order and is slightly less optimal than the HashMap.
//The TreeMap keeps keys in their natural order (or some custom order defined using a Comparator). This implementation has a significant performance decrease compared to HashMap and LinkedHashMap but is great when needing to keep keys sorted.
//A Map has the following methods for accessing its elements:
//put(): Sets the value that key maps to. Note that this method replaces the value key mapped to if the key was already present in the Map.
//get(): Gets, but does not remove, the value the provided key argument points to if it exists. This method returns null if the key is not in the Map.

Map<String, String> myMap = new HashMap<>();
 
myMap.put("Hello", "World") // { "Hello" -> "World" }
myMap.put("Name", "John") //   { "Hello" -> "World" }, { "Name" -> "John" }
 
String result = myMap.get("Hello") // returns "World" 
String noResult = myMap.get("Jack") // return `null`

// Given a map, `myMap`, with the following key-value pairs { "Hello" -> "World" }, { "Name" -> "John"}
for (Map.Entry<String, String> pair: myMap.entrySet()){
  System.out.println("key: "+pair.getKey()+", value: "+pair.getValue());
}
// OUTPUT TERMINAL:
// key: Name, value: John
// key: Hello, value: World
//There are many methods provided in the Collections class and we’ll cover a subset of those below:
//binarySearch(): Performs binary search over a List to find the specified object and returns the index if found. This method is overloaded to also accept a Comparator in order to define a custom sorting algorithm.
//max(): Finds and returns the maximum element in the Collection. This method is overloaded to also accept a Comparator in order to define a custom sorting algorithm.
//min(): Finds and returns the minimum element in the Collection. This method is overloaded to also accept a Comparator in order to define a custom sorting algorithm.
//reverse(): Reverses the order of elements in the List passed in as an argument.
//sort(): Sorts the List passed in as an argument. This method is overloaded to also accept a Comparator in order to define a custom sorting algorithm.
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Collection;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
public class Main {
  public static void main(String[] args) {
    List<Integer> myList = new ArrayList<>();
    myList.add(3);
    myList.add(-1);
    myList.add(57);
    myList.add(29);

    Set<String> mySet = new HashSet<>();
    mySet.add("Hello");
    mySet.add("World");

    System.out.println("mySet max: \""+ Collections.max(mySet)+"\"");
    System.out.println();

    System.out.println("myList min: "+ Collections.min(myList));
    System.out.println();

    System.out.println("Index of 57 in myList is: "+Collections.binarySearch(myList, 57));
    System.out.println();


    System.out.println("myList prior to reverse: ");
    printCollection(myList);

    System.out.println();

    Collections.reverse(myList);
    System.out.println("myList reversed: ");
    printCollection(myList);

    System.out.println();

    System.out.println("myList prior to sort: ");
    printCollection(myList);

    System.out.println();

    Collections.sort(myList);
    System.out.println("myList after sort: ");
    printCollection(myList);


  }

  public static void printCollection(Collection<?> collection){
    Iterator<?> myItr = collection.iterator();

    while(myItr.hasNext()){
      System.out.println(myItr.next());
    }
  }
}
//the Collection interface provides a generic, general-purpose API when our program needs a collection of elements and doesn’t care about what type of collection it is.
//Implementing classes may implement collections methods and add restrictions to them, like a Set does to only contain unique elements. Also, implementing classes or extending interfaces do not need to implement all methods and instead will throw an UnsupportOperationException when a Collection method is not implemented.
//We’ve seen add() and remove() be used but some other methods Collection defines are:
//addAll() - receives a Collection argument and adds all the elements.
//isEmpty() - return true if the collection is empty, false otherwise.
//iterator() - returns an Iterator over the collection.
//size() - returns the number of elements in the collection.
//stream() - returns a Stream over the elements in the collection.
//toArray() - returns an array with all elements in the collection.

Collection<Integer> collection = new ArrayList<>();
collection.add(4);
collection.add(8);
 
boolean isEmpty = collection.isEmpty(); // false
int collectionSize = collection.size(); // 2
 
Integer[] collectionArray = collection.toArray(new Integer[0]);

private static <T> void printCollection(Collection<T> collection) {
    for(T item: collection){
      System.out.println(item);}
  }
//A Deque is a collection that allows us to manipulate elements from both the front and end of the collection.
//The Deque interface has two types of methods for manipulating the front and back of the collection.
//The following methods throw an exception when:
//addFirst(), addLast() - there is no space to add an element.
//removeFirst(), removeLast() - there is no element to remove.
//getFirst(), getLast() - there is no element to get.
//The following methods return a special value:
//offerFirst(), offerLast() - false when there is no space to add an element.
//pollFirst(), pollLast() - null when there is no element to remove.
//peekFirst(), peekLast() - null when there is no element to get.

Deque<String> stringDeque = new LinkedList<>();
stringDeque.addFirst("A"); // Front -> "A" <- end
stringDeque.offerFirst("B"); // Return `true` - front -> "B", "A" <- end
stringDeque.offerLast("Z"); // Returns `true` - front -> "B", "A", "Z" <- end
 
String a = stringDeque.removeFirst()  // Returns "B" - front -> "A", "Z"
String b = stringDeque.pollLast()  // Returns "Z" - front -> "A" <- back
String c = stringDeque.removeLast()  // Returns "A" - empty deque
 
String d = stringDeque.peekFirst()  // Returns null
String e = stringDeque.getLast() // Throws NoSuchElementException

// Assuming `stringDeque` has elements front -> "Mike", "Jack", "John" <- back
Iterator<String> descItr = stringDeque.descendingIterator();
 
while(descItr.hasNext()) {
  System.out.println(descItr.next());
}
// OUTPUT TERMINAL:  "John", "Jack", "Mike"
 public static boolean isPossible(int[] nums, int mid, int k){
        int subArr=1;
        int sum=0;
        for(int i=0;i<nums.length;i++){
            sum+=nums[i];
            if(sum>mid){
                subArr++;
                sum=nums[i];
            }
        }
        return subArr <=k;
    }
    public int splitArray(int[] nums, int k) {
        if(nums[0]==1 && nums[1]==1 && nums.length==2) return 2;
        int max=0;
        int sum=0;
        for(int val: nums){
            sum+=val;
            max= Math.max(val,max);
        }
        if(k==max) return max;
        int low=max;
        int high=sum;
        int ans=0;
        while(low<=high){
            int mid=low+(high-low)/2;
            if(isPossible(nums,mid,k)){
                ans=mid;
                high=mid-1;
            }
            else low=mid+1;
        }
        return ans;
    }
//collection that stores elements that can be accessed at some later point to process (like waiting in line at the bank teller). A Queue accesses elements in a (usually) First In First Out (FIFO) manner where elements are inserted at the tail (back) of the collection and removed from the head (front).
//A Queue has two types of access methods for inserting, removing, and getting but not removing the head of the Queue.
//The following methods throw an exception when:
//add() - there is no space for the element
//remove() - there are no elements to remove
//element() - there are no elements to get
//The following methods return a special value:
//offer() - false there is no space for the element
//poll() - null there are no elements to remove
//peek() - null there are no elements to get
//The methods that return a special value should be used when working with a statically sized Queue and the exception throwing methods when using a dynamic Queue.

Queue<String> stringQueue = new LinkedList<>();
stringQueue.add("Mike"); // true - state of queue -> "Mike"
stringQueue.offer("Jeff"); // true - state of queue -> "Mike", "Jeff" 
 
String a = stringQueue.remove() // Returns "Mike" - state of queue -> 1
String b = stringQueue.poll() // Returns "Jeff" - state of queue -> empty
String c = stringQueue.peek() // Returns null
String d = stringQueue.element() // Throws NoSuchElementException

// Assuming `stringQueue` has elements -> "Mike", "Jack", "John"
for (String name: stringQueue) {
  System.out.println(name);
}
// OUTPUT TERMINAL: "Mike", "Jack", "John"
//A Set is a collection of unique elements and all of its methods ensure this stays true. 
//The HashSet implementation has the best performance when retrieving or inserting elements but cannot guarantee any ordering among them.
//The TreeSet implementation does not perform as well on insertion and deletion of elements but does keep the elements stored in order based on their values (this can be customized).
//The LinkedHashSet implementation has a slightly slower performance on insertion and deletion of elements than a HashSet but keeps elements in insertion order.

Set<Integer> intSet = new HashSet<>();  // Empty set
intSet.add(6);  // true - 6  
intSet.add(0);  //  true - 0, 6 (no guaranteed ordering)
intSet.add(6);  //  false - 0, 6 (no change, no guaranteed ordering)
 
boolean isNineInSet = intSet.contains(9);  // false
boolean isZeroInSet = intSet.contains(0);  // true

// Assuming `intSet` has elements -> 1, 5, 9, 0, 23
for (Integer number: intSet) {
  System.out.println(number);
}
// OUTPUT TERMINAL: 5 0 23 9 1
//. A List is a collection where its elements are ordered in a sequence. Lists allow us to have duplicate elements and fine-grain control over where elements are inserted in the sequence. Lists are dynamically sized.
import java.util.List;
import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
    List<String> stringList = new ArrayList<>();
    stringList.add("Hello");
    stringList.add("World");
    stringList.add("!");
    for(String element: stringList){
      System.out.println(element);}
  }
}
public class Util {
  public static void printBag(Bag<?> bag ) {
    System.out.println(bag.toString()); 
  }
}
Bag<String> myBag1 = new Bag("Hello");
Bag<Integer> myBag2 = new Bag(23);
Util.printBag(myBag1);  // Hello
Util.printBag(myBag2);  // 23

public static <T> void printBag(Bag<T> bag ) {
  System.out.println(bag.toString()); 
}

public static <T> Bag<T> getBag(Bag<T> bag ) {
  return bag;
}

public static void printBag(Bag<? extends Number> bag ) {
  System.out.println(bag.toString()); 
}

//Wildcard Lower Bounds
//A lower bound wildcard restricts the wildcard to a class or interface and any of its parent types.
//There are some general guidelines provided by Java as to when to use what type of wildcard:

//An upper bound wildcard should be used when the variable is being used to serve some type of data to our code.
//A lower bound wildcard should be used when the variable is receiving data and holding it to be used later.
//When a variable that serves data is used and only uses Object methods, an unbounded wildcard is preferred.
//When a variable needs to serve data and store data for use later on, a wildcard should not be used (use a type parameter instead).
//An upper bound restricts the type parameter to a class or any of its sub-classes and is done this way: SomeClass<? extends SomeType>. A lower bound restricts the type parameter to a class or any of its parent classes and is done this way: SomeClass<? super SomeType>.
public class Util {
  public static void getBag(Bag<? super Integer> bag ) {
    return bag;
  }
}
public class Box <T extends Number> {
  private T data; 
}
 
Box<Integer> intBox = new Box<>(2);  // Valid type argument
Box<Double> doubleBox = new Box<>(2.5);  // Valid type argument
Box<String> stringBox = new Box<>("hello");  // Error

public static <T extends Number> boolean isZero(T data) {
  return data.equals(0);
}

//multiple bounds
public class Box <T extends Number & Comparable<T>> {
  private T data; 
}
public class Box<T, S> {
  private T item1;
  private S item2;
  // Constructors, getters, and setters
}
Box<String, Integer> wordAndIntegerBox = new Box<>("Hello", 5);

public class Util {
  public static <T, S> boolean areNumbers(T item1, S item2) {
    return item1 instanceof Number && item2 instanceof Number; 
  }
}
 
boolean areNums = Util.areNumbers("Hello", 34);  // false
public class Box <T> {
  private T data;
 
  public Box(T data) {
    this.data = data; 
  }
 
  public T getData() {
    return this.data;
  }  
}
 
Box box = new Box<>("My String");  // Raw type box
String s2 = (String) box.getData();  // No incompatible type error
String s1 = box.getData();  // Incompatible type error
import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Car implements Serializable {
  private String make;
  private int year;
  private static final long serialVersionUID = 1L;
  private Engine engine;

  public Car(String make, int year) {
    this.make = make;
    this.year = year;
    this.engine = new Engine(2.4, 6);
  }

 private void writeObject(ObjectOutputStream stream) throws IOException {
    stream.writeObject(this.make);
    stream.writeInt(this.year);
    stream.writeDouble(this.engine.getLiters());
    stream.writeInt(this.engine.getCylinders());   
  }
 
  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
    this.make = (String) stream.readObject();
    this.year = (int) stream.readInt();
    double liters = (double) stream.readDouble();
    int cylinders = (int) stream.readInt();
    this.engine = new Engine(liters, cylinders); 
  }    


  public String toString(){
    return String.format("Car make is: %s, Car year is: %d, %s", this.make, this.year, this.engine);
  }

  public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
    Car toyota = new Car("Toyota", 2021);
    Car honda = new Car("Honda", 2020);
    FileOutputStream fileOutputStream = new FileOutputStream("cars.txt");
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
    objectOutputStream.writeObject(toyota);
    objectOutputStream.writeObject(honda);

    FileInputStream fileInputStream = new FileInputStream("cars.txt");
    ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

    Car toyotaCopy = (Car) objectInputStream.readObject();
    Car hondaCopy = (Car) objectInputStream.readObject();

    boolean isSameObject = toyotaCopy == toyota;
    System.out.println("Toyota (Copy) - "+toyotaCopy);
    System.out.println("Toyota (Original) - "+toyota);
    System.out.println("Is same object: "+ isSameObject);
  }
}
public class Person implements Serializable {
  public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
 
    FileInputStream fileInputStream = new FileInputStream("persons.txt");
    ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
 
    Person michaelCopy = (Person) objectInputStream.readObject();
    Person peterCopy = (Person) objectInputStream.readObject();
  }
}
public class Person implements Serializable {
  private String name;
  private int age;
  private static final long serialVersionUID = 1L; 
 
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }  
 
  public static void main(String[] args) throws FileNotFoundException, IOException{
    Person michael = new Person("Michael", 26);
    Person peter = new Person("Peter", 37);
 
    FileOutputStream fileOutputStream = new FileOutputStream("persons.txt");
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
 
    objectOutputStream.writeObject(michael);
    objectOutputStream.writeObject(peter);    
  }
} 
import java.io.FileReader;
import java.io.IOException;

public class Introduction {
  public static void main(String[] args) {
    String path = "/a/bad/file/path/to/thisFile.txt";
    try {
      FileReader reader = new FileReader(path);  
      while (reader.ready()) {    
        System.out.print((char) reader.read());    
      }    
      reader.close();
    } catch (IOException e) {
      System.out.println("There has been an IO exception!");
      System.out.println(e);
    }
  }
}
import java.io.*;


public class Introduction {
  public static void main(String[] args) throws IOException {
    FileOutputStream output = new FileOutputStream("output.txt");
    String outputText = "bla,bla,bla";
    byte[] outputBytes = outputText.getBytes();
    output.write(outputBytes);
    output.close();
  }
}
import java.io.*;


public class Introduction {
  public static void main(String[] args) throws IOException {
    String path = "/home/ccuser/workspace/java-input-and-output-file-input-stream/input.txt";
    FileInputStream input1 = new FileInputStream(path);
    int i = 0;
// A loop to access each character
    while((i = input1.read()) != -1) {
      System.out.print((char)i);
    }
    input1.close();
  }
}
public static int chocola(int n, int m,int[] hArray, int [] vArray) {
        Arrays.sort(hArray);
        Arrays.sort(vArray);
        int h=0,v=0,hp=1,vp=1;
        int cost=0;
        while(h<hArray.length && v<vArray.length){
            if(vArray[vArray.length-v-1]<=hArray[hArray.length-h-1]){
                cost+=hArray[hArray.length-h-1]*vp;
                hp++;
                h++;
            }
            else{
                cost+=vArray[vArray.length-v-1]*hp;
                vp++;
                v++;
            }
        }
        while(h<hArray.length){
            cost+=hArray[hArray.length-h-1]*vp;
            hp++;
            h++;
        }
        while(v<vArray.length){
            cost+=vArray[vArray.length-v-1]*hp;
            vp++;
            v++;
        }
        return cost;
    }
    public static void main(String[] args){
        String s= new String("hi");
        System.out.println(s.);
        int n=4, m=6;
        int[] hArray={2,1,3,1,4};
        int[] vArray={4,1,2};
        System.out.println(chocola(n,m,hArray,vArray));
    }
}
 public static double maxValue(int[] weight, int[] value, int capacity){
        double[][] ratio=new double[weight.length][2];
        for(int i=0;i< weight.length;i++){
            ratio[i][0]=i;
            ratio[i][1]=value[i]/(double)weight[i];
        }
        Arrays.sort(ratio,Comparator.comparingDouble(o->o[1]));
        double val=0;
        for(int i= weight.length-1;i>=0;i--){
            int idx=(int)ratio[i][0];
            if(capacity>=weight[idx]){
                val+=value[idx];
                capacity-=weight[idx];
            }
            else{
                val+=capacity*ratio[i][1];
                capacity=0;
                break;
            }
        }
        return val;
    }
    public static void main(String[] args){
       int[] weight={10,20,30};
       int[] value={60,100,120};
       int capacity=50;
        System.out.println(maxValue(weight,value,capacity));
    }
public static void main(String[] args){
        int[] start={1,3,0,5,8,5};
        int[] end={2,4,6,7,9,9};
        int[][] activities=new int[start.length][3];
        ArrayList<Integer> ans=new ArrayList<>();
        for(int i=0;i< start.length;i++){
            activities[i][0]=i;
            activities[i][1]=start[i];
            activities[i][2]=end[i];
        }

        Arrays.sort(activities, Comparator.comparingDouble(o->o[2]));
        int maxAct=1;
        int lastEnd=activities[0][2];
        ans.add(activities[0][0]);
        for(int i=1;i<end.length;i++){
            if(lastEnd<=activities[i][1]){
                maxAct++;
                lastEnd=activities[i][2];
                ans.add(activities[i][0]);
            }
        }
        System.out.println(maxAct);
        System.out.println(ans);
    }
server.port=4001
spring.jackson.default-property-inclusion = NON_NULL
spring.jpa.defer-datasource-initialization= true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.hibernate.hbm2ddl.auto=create
spring.jpa.hibernate.use-new-id-generator-mappings=false
spring.datasource.initialization-mode=never
spring.datasource.url=jdbc:h2:file:~/boots.db
package com.codecademy.plants.repositories;
import java.util.List; 
import org.springframework.data.repository.CrudRepository;
import com.codecademy.plants.entities.Plant;

public interface PlantRepository extends CrudRepository<Plant, Integer> {
  List<Plant> findByHasFruitTrue();
  List<Plant> findByHasFruitFalse();
  List<Plant> findByQuantityLessThan(Integer quantity);
  List<Plant> findByHasFruitTrueAndQuantityLessThan(Integer quantity);
  List<Plant> findByHasFruitFalseAndQuantityLessThan(Integer quantity);
}

//Controller
@GetMapping("/plants/search")
  public List<Plant> searchPlants(
    @RequestParam(name="hasFruit", required = false) Boolean hasFruit,
    @RequestParam(name="maxQuantity", required = false) Integer quantity
  ) {
    if (hasFruit != null && quantity != null && hasFruit) {
      return this.plantRepository.findByHasFruitTrueAndQuantityLessThan(quantity);
    }
    if (hasFruit != null && quantity != null && !hasFruit) {
      return this.plantRepository.findByHasFruitFalseAndQuantityLessThan(quantity);
    }
    if (hasFruit != null && hasFruit) {
      return this.plantRepository.findByHasFruitTrue();
    }
    if (hasFruit != null && !hasFruit) {
      return this.plantRepository.findByHasFruitFalse();
    }
    if (quantity != null) {
      return this.plantRepository.findByQuantityLessThan(quantity);
    }
    return new ArrayList<>();
  }
//Repository
List<Person> findByEyeColorAndAgeLessThan(String eyeColor, Integer age);
//Controller
@GetMapping("/people/search")
public List<Person> searchPeople(
  @RequestParam(name = "eyeColor", required = false) String eyeColor,
  @RequestParam(name = "maxAge", required = false) Integer maxAge 
) {
  if (eyeColor != null && maxAge != null) {
    return this.personRepository.findByEyeColorAndAgeLessThan(eyeColor, maxAge);
  } else if (eyeColor != null) {
    return this.personRepository.findByEyeColor(eyeColor);
  } else if (maxAge != null) {
    return this.personRepository.findByAgeLessThan(maxAge);
  } else {
    return new ArrayList<>();
  }
}
package com.codecademy.people.repositories;
import java.util.List; 
import org.springframework.data.repository.CrudRepository;
import com.codecademy.people.entities.Person;

//Repository folder
public interface PersonRepository extends CrudRepository<Person, Integer> {
  // this declaration is all we need!
  List<Person> findByEyeColor(String eyeColor);
  List<Person> findByAgeLessThan(Integer age); 
}

//Controller folder
	@GetMapping("/people/search")
	public List<Person> searchPeople(@RequestParam(name = "eyeColor", required = false) String eyeColor) {
  if (eyeColor != null) {
    return this.personRepository.findByEyeColor(eyeColor)
  } else {
    return new ArrayList<>();
  }
}

//Advanced Controller folder
@GetMapping("/people/search")
public List<Person> searchPeople(
  @RequestParam(name = "eyeColor", required = false) String eyeColor,
  @RequestParam(name = "maxAge", required = false) Integer maxAge 
) {
  if (eyeColor != null) {
    return this.personRepository.findByEyeColor(eyeColor)
  } else if (maxAge != null) {
    return this.personRepository.findByAgeLessThan(maxAge);
  } else {
    return new ArrayList<>();
  }
}

package com.codecademy.plants.repositories;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

import com.codecademy.plants.entities.Plant;

public interface PlantRepository extends CrudRepository<Plant, Integer> {
}
package com.codecademy.plants.entities;

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;

@Entity
@Table(name = "PLANTS")
public class Plant {

  @Id
  @GeneratedValue
  private Integer id;

  @Column(name = "NAME")
  private String name;

  @Column(name = "QUANTITY")
  private Integer quantity;

  @Column(name = "WATERING_FREQUENCY")
  private Integer wateringFrequency;

  @Column(name = "HAS_FRUIT")
  private Boolean hasFruit;

  public Integer getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public Integer getQuantity() {
    return this.quantity;
  }

  public Integer getWateringFrequency() {
    return this.wateringFrequency;
  }

  public Boolean getHasFruit() {
    return this.hasFruit;
  }

  public void setId(Integer id) {
    this.id = id;
  }

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

  public void setQuantity(Integer quantity) {
    this.quantity = quantity;
  }

  public void setWateringFrequency(Integer wateringFrequency) {
    this.wateringFrequency = wateringFrequency;
  }

  public void setHasFruit(Boolean hasFruit) {
    this.hasFruit = hasFruit;
  }

}
package com.codecademy.plants.controllers;

import java.lang.Iterable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import com.codecademy.plants.entities.Plant;
import com.codecademy.plants.repositories.PlantRepository;

@RestController
public class PlantController {

  private final PlantRepository plantRepository;

  public PlantController(final PlantRepository plantRepository) {
    this.plantRepository = plantRepository;
  }

  @GetMapping("/plants")
  public Iterable<Plant> getAllPlants() {
    return this.plantRepository.findAll();
  }

  @GetMapping("/plants/{id}")
  public Optional<Plant> getPlantById(@PathVariable("id") Integer id) {
    return this.plantRepository.findById(id);
  }

  @PostMapping("/plants")
  public Plant createNewPlant(@RequestBody Plant plant) {
    Plant newPlant = this.plantRepository.save(plant);
    return newPlant;
  }

  @PutMapping("/plants/{id}")
  public Plant updatePlant(
    @PathVariable("id") Integer id,
    @RequestBody Plant p
  ) {
    Optional<Plant> plantToUpdateOptional = this.plantRepository.findById(id);
    if (!plantToUpdateOptional.isPresent()) {
      return null;
    }
    Plant plantToUpdate = plantToUpdateOptional.get();
    if (p.getHasFruit() != null) {
      plantToUpdate.setHasFruit(p.getHasFruit());
    }
    if (p.getQuantity() != null) {
      plantToUpdate.setQuantity(p.getQuantity());
    }
    if (p.getName() != null) {
      plantToUpdate.setName(p.getName());
    }
    if (p.getWateringFrequency() != null) {
      plantToUpdate.setWateringFrequency(p.getWateringFrequency());
    }
    Plant updatedPlant = this.plantRepository.save(plantToUpdate);
    return updatedPlant;
  }

  @DeleteMapping("/plants/{id}")
  public Plant deletePlant(@PathVariable("id") Integer id) {
    Optional<Plant> plantToDeleteOptional = this.plantRepository.findById(id);
    if (!plantToDeleteOptional.isPresent()) {
      return null;
    }
    Plant plantToDelete = plantToDeleteOptional.get();
    this.plantRepository.delete(plantToDelete);
    return plantToDelete;
  }
}
package com.cyberspace.tla.migrate.utils;

import com.cyberspace.tla.migrate.config.ConfigLoad;
import com.cyberspace.tla.migrate.models.chitieu.token.ServiceAuthInput;
import com.cyberspace.tla.migrate.models.chitieu.token.SyncData;
import com.cyberspace.tla.migrate.models.token_sync_corp.SyncAuthInput;
import com.cyberspace.tla.migrate.models.token_sync_corp.SyncAuthOutput;
import javafx.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class SyncGetToken {
    public static Logger LOG = LoggerFactory.getLogger(SyncGetToken.class);

    private static String urlToken = ConfigLoad.getConfigLoad().getConfig("token_url");
  private static String serviceList_token = ConfigLoad.getConfigLoad().getConfig("serviceList_token");
  private static String serviceList_username = ConfigLoad.getConfigLoad().getConfig("serviceList_username");
  private static String serviceList_password = ConfigLoad.getConfigLoad().getConfig("serviceList_password");

    public static String getToken(SyncAuthInput authInput) {
        try {
            List<Pair<String, String>> form = new ArrayList<>();
            form.add(new Pair<>("username", authInput.getUsername()));
            form.add(new Pair<>("password", authInput.getPassword()));
            form.add(new Pair<>("client_id", authInput.getClientId()));
            form.add(new Pair<>("client_secret", authInput.getClientSecret()));
            form.add(new Pair<>("grant_type", authInput.getGrantType()));

            String output = RESTUtil.post(urlToken, form, null);
            if(!output.contains("access_token")){
              LOG.error("Failed to get token from: " + urlToken);
              return null;
            }
            SyncAuthOutput authOutput = GsonUtil.parse(output, SyncAuthOutput.class);

            String token = authOutput.getAccessToken();
            LOG.info("Got token: " + token);
            return token;

        } catch (Exception e) {
          LOG.error("Failed to get token from: " + urlToken+ "\n" + e.getMessage());
          return null;
        }
    }

  public static String getTokenServiceList() {
    try {

      ServiceAuthInput serviceListInput = new ServiceAuthInput(serviceList_username,serviceList_password);
      String output = RESTUtil.postNoLog(serviceList_token, GsonUtil.toJson(serviceListInput), null);
      if(!output.contains("token")){
        LOG.error("Failed to get token from: " + urlToken);
        return null;
      }
      SyncData authOutput = GsonUtil.parse(output, SyncData.class);

      String token = authOutput.getData().getToken();
      LOG.info("Got token: " + token);
      return token;

    } catch (Exception e) {
      LOG.error("Failed to get token from: " + serviceList_token+ "\n" + e.getMessage());
      return null;
    }
  }

    public static void main(String[] args) {

//        SyncAuthInput authTTNSInput = new SyncAuthInput("troLyAo"
//                , "WR*#oMhnQy3"
//                , "8pxgbrfvn8t3rv0w4xriwglt4e0xbztg"
//                , "35xrkohoevzkhtw6hm6zenq4wpnriiml"
//                , "password");
//
//        String test = getToken(authTTNSInput);
      String test = getTokenServiceList();

        System.out.println(test);

    }
}
package com.cyberspace.tla.migrate.utils;

import com.cyberspace.tla.migrate.config.ConfigLoad;
import com.google.gson.JsonObject;
import javafx.util.Pair;
import okhttp3.*;
import okhttp3.OkHttpClient.Builder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class RESTUtil {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static final MediaType FORM = MediaType.parse("application/x-www-form-urlencoded");
    public static Logger LOG = LoggerFactory.getLogger(RESTUtil.class);
    static OkHttpClient client = null;

    static OkHttpClient getClient(){
        if(client == null){
            client = new OkHttpClient();
            client = trustAllSslClient(client);
        }
        return client;
    }

    /*
    * This is very bad practice and should NOT be used in production.
    */
    private static final TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[]{};
                }
            }
    };
    private static final SSLContext trustAllSslContext;
    static {
        try {
            trustAllSslContext = SSLContext.getInstance("SSL");
            trustAllSslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException(e);
        }
    }
    private static final SSLSocketFactory trustAllSslSocketFactory = trustAllSslContext.getSocketFactory();

    public static OkHttpClient trustAllSslClient(OkHttpClient client) {
//        LOG.warn("Using the trustAllSslClient is highly discouraged and should not be used in Production!");
        int timeoutInSec = Integer.parseInt(ConfigLoad.getConfigLoad().getConfig("service.timeout.sec"));
//        int timeoutInSec = 5;
        Builder builder = client.newBuilder()
                .writeTimeout(timeoutInSec, TimeUnit.SECONDS)
                .readTimeout(timeoutInSec, TimeUnit.SECONDS);
        builder.sslSocketFactory(trustAllSslSocketFactory, (X509TrustManager)trustAllCerts[0]);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return builder.build();
    }

    public static String post(String url, String json, Map<String, String> headers) throws IOException {
        if (headers == null) {
            headers = new HashMap<>();
        }
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .headers(Headers.of(headers))
                .build();
        try {
            LOG.info("send json " + json + " to url " + url);
            Response response = getClient().newCall(request).execute();
            String ans = response.body().string();
            return ans;
        } catch (SocketTimeoutException e){
            LOG.error("TIME OUT, " + e.getMessage());
            JsonObject timeOutObj = new JsonObject();
            String timeOutError = ConfigLoad.getConfigLoad().getConfig("error.timeout");
            timeOutObj.addProperty("error", timeOutError);
            return GsonUtil.toJson(timeOutObj);
        } catch (IOException e) {
            LOG.error(e.getMessage());
            JsonObject timeOutObj = new JsonObject();
            String noDataError = ConfigLoad.getConfigLoad().getConfig("error.nodata");
            timeOutObj.addProperty("error", noDataError);
            return GsonUtil.toJson(timeOutObj);
        }
    }

    public static String postNoLog(String url, String json, Map<String, String> headers) throws IOException {
        if (headers == null) {
            headers = new HashMap<>();
        }
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .headers(Headers.of(headers))
                .build();
        try {
            Response response = getClient().newCall(request).execute();
            String ans = response.body().string();
            return ans;
        } catch (SocketTimeoutException e){
            LOG.error("TIME OUT, " + e.getMessage());
            JsonObject timeOutObj = new JsonObject();
            String timeOutError = ConfigLoad.getConfigLoad().getConfig("error.timeout");
            timeOutObj.addProperty("error", timeOutError);
          System.out.println("timeout");
            return GsonUtil.toJson(timeOutObj);
        } catch (IOException e) {
            LOG.error(e.getMessage());
            JsonObject timeOutObj = new JsonObject();
            String noDataError = ConfigLoad.getConfigLoad().getConfig("error.nodata");
            timeOutObj.addProperty("error", noDataError);
          System.out.println("no data");
            return GsonUtil.toJson(timeOutObj);
        }
    }

    public static String post(String url, List<Pair<String, String>> form, Map<String, String> headers) throws IOException {
        if (headers == null) {
            headers = new HashMap<>();
        }
        String stringForm = "";
        for (Pair<String, String> param: form) {
            stringForm += "&"+ param.getKey() +"="+ param.getValue();
        }

        stringForm = stringForm.substring(1);
        RequestBody body = RequestBody.create(FORM, stringForm);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .headers(Headers.of(headers))
                .build();
        try {
            LOG.info("send formdata " + stringForm + " to url " + url);
            Response response = getClient().newCall(request).execute();
            String ans = response.body().string();
            return ans;
        } catch (SocketTimeoutException e){
            LOG.error("TIME OUT, " + e.getMessage());
            JsonObject timeOutObj = new JsonObject();
            String timeOutError = ConfigLoad.getConfigLoad().getConfig("error.timeout");
            timeOutObj.addProperty("error", timeOutError);
            return GsonUtil.toJson(timeOutObj);
        } catch (IOException e) {
            LOG.error(e.getMessage());
            JsonObject timeOutObj = new JsonObject();
            String noDataError = ConfigLoad.getConfigLoad().getConfig("error.nodata");
            timeOutObj.addProperty("error", noDataError);
            return GsonUtil.toJson(timeOutObj);
        }
    }

    public static String get(String url, Map<String, String> headers) throws IOException {
        String result = "{}";
        try{
            if (headers == null) {
                headers = new HashMap<>();
            }
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .headers(Headers.of(headers))
                    .build();
            LOG.info("Get url " + url);
            LOG.info("Header: " + headers);
            Response response = getClient().newCall(request).execute();
            result =  response.body().string();
//            LOG.info("Response: " + result);
        }catch (SocketTimeoutException e){
            LOG.error("Time out when get url " + url);
            JsonObject timeOutObj = new JsonObject();
            timeOutObj.addProperty("isTimeOut", "true");
            return GsonUtil.toJson(timeOutObj);
        }catch (Exception e){
            LOG.error(e.getMessage());
        }
        return result;
    }

    public static String get(String url, Map<String, String> headers, Map<String, String> params){
      String result = "{}";
      try{
        if (headers == null) {
          headers = new HashMap<>();
        }
//        create Http url with adding params
        HttpUrl.Builder httpUrl = HttpUrl.parse(url).newBuilder();
        if(params != null){
          for(Map.Entry<String, String> param : params.entrySet()) {
            httpUrl.addQueryParameter(param.getKey(),param.getValue());
          }
        }
        Request request = new Request.Builder()
          .url(httpUrl.build())
          .get()
          .headers(Headers.of(headers))
          .build();
        LOG.info("Get url " + url);
        LOG.info("Header: " + headers);
        LOG.info("Params" + params);
        Response response = getClient().newCall(request).execute();
        result =  response.body().string();
//            LOG.info("Response: " + result);
      }catch (SocketTimeoutException e){
        LOG.error("Time out when get url " + url);
        JsonObject timeOutObj = new JsonObject();
        timeOutObj.addProperty("isTimeOut", "true");
        return GsonUtil.toJson(timeOutObj);
      }catch (Exception e){
        LOG.error(e.getMessage());
      }
      return result;
    }

}
package com.cyberspace.tla.migrate.utils;

import com.cyberspace.tla.migrate.models.Property;
import com.cyberspace.tla.migrate.models.Status;
import com.cyberspace.tla.migrate.providers.MongoProvider;
import com.mongodb.*;
import com.mongodb.util.JSON;
import javafx.util.Pair;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class MongoUtils {

    public static Logger LOG = LoggerFactory.getLogger(MongoUtils.class);

    public static List<Map<String, Object>> getCollection(String collectionName){
        DBCollection collection = MongoProvider.getDatabase().getCollection(collectionName);
        LOG.info("load " + collectionName + " collection succesful from robomongo");
        DBCursor cursor = collection.find();
        List<Map<String, Object>> list = new ArrayList<>();

        while(cursor.hasNext()) {
            list.add((Map<String, Object>)cursor.next());
        }
        return list;
    }

//    public static List<Map<String, Object>> retrieveCollection(String collectionName, String botId){
    public static List<DBObject> retrieveCollection(String collectionName, String botId){
        DBCollection collection = MongoProvider.getDatabase().getCollection(collectionName);
        BasicDBObject query = new BasicDBObject();
        query.put("bot_id", botId);
        DBCursor cursor = collection.find(query);
        List<DBObject> list = cursor.toArray();
        LOG.info("query successfully.");
        return list;
    }
// find by id
    public static List<DBObject> find(String collectionName, String id){
        DBCollection collection = MongoProvider.getDatabase().getCollection(collectionName);
        BasicDBObject query = new BasicDBObject();
        query.put("_id", new ObjectId(id));
        DBCursor cursor = collection.find(query);
        List<DBObject> list = cursor.toArray();
      LOG.info("query successfully.");

      return list;
    }
  public static List<DBObject> findByKey(String collectionName, Pair<String, Object> pair){
    DBCollection collection = MongoProvider.getDatabase().getCollection(collectionName);
    BasicDBObject query = new BasicDBObject();
    query.put(pair.getKey(), new BasicDBObject("$eq",pair.getValue()));
    DBCursor cursor = collection.find(query);
    List<DBObject> list = cursor.toArray();
//    LOG.info("query successfully.");

    return list;
  }

//    find by key,value
    public static List<DBObject> find(String collectionName, List<Pair<String, Property>> pairs){
        DBCollection collection = MongoProvider.getDatabase().getCollection(collectionName);
        BasicDBObject whereQuery = new BasicDBObject();

        for(Pair<String, Property> pair : pairs){
            switch (pair.getValue().getType()) {
                case SEARCH:
                    BasicDBList and = new BasicDBList();
                    String value = pair.getValue().getValue();
                    String[] splitValue = value.split(" ");
                    for (String iValue: splitValue) {
                        BasicDBObject andClause = new BasicDBObject().append("fullName", Pattern.compile(".*"+iValue+".*", Pattern.CASE_INSENSITIVE));
                        and.add(andClause);
                    }
                    whereQuery.put("$and", and);

                    break;
                case EQUAL:
                    whereQuery.put(pair.getKey(), Pattern.compile("^"+pair.getValue().getValue()+"$", Pattern.CASE_INSENSITIVE));
                    break;
                case CONTAINS:
                    whereQuery.put(pair.getKey(), Pattern.compile(".*"+pair.getValue().getValue()+".*", Pattern.CASE_INSENSITIVE));
                    break;
                case HEAD:
                    whereQuery.put(pair.getKey(), Pattern.compile("^"+pair.getValue().getValue(), Pattern.CASE_INSENSITIVE));
                    break;
                case END:
                    whereQuery.put(pair.getKey(), Pattern.compile(pair.getValue().getValue()+"$", Pattern.CASE_INSENSITIVE));
                    break;
                case LESS:
                  whereQuery.put(pair.getKey(), new BasicDBObject("$lt",pair.getValue().getValue()));
                  break;
              case LESS_EQUAL:{
                    whereQuery.put(pair.getKey(), new BasicDBObject("$lte",pair.getValue().getValue()));
                  break;
                }
              case GREATER:
                    whereQuery.put(pair.getKey(),new BasicDBObject("$gt",pair.getValue().getValue()));
                  break;
              case GREATER_EQUAL:
                    whereQuery.put(pair.getKey(), new BasicDBObject("gte", pair.getValue().getValue()));
                  break;
                case NULL:
                    whereQuery.put(pair.getKey(), null);
                    break;
            }
        }
        DBCursor cursor = collection.find(whereQuery);
        List<DBObject> list = cursor.toArray();
//        LOG.info("query successfully.");
        return list;
    }
    public static String insert(String collectionName, Object data){
        DBCollection collection = MongoProvider.getDatabase().getCollection(collectionName);
        try {
            DBObject dbObject = (DBObject) JSON.parse(GsonUtil.toJson(data));
//            dbObject.put("type_obj_id",new ObjectId("5d5a0e6ebf9aadacba4c19a5"));
          dbObject.put("created_at", new Date());
          dbObject.put("update_at", new Date());
//          dbObject.put("type_obj_id",new ObjectId(id));

          collection.insert(dbObject);
          String id = dbObject.get( "_id" ).toString();
//          LOG.info("insert successfully.");
          return id;
        }catch (Exception e){
            e.printStackTrace();
          LOG.error("query failed: " + e);
          return "";
        }

    }
  public static String insert(String collectionName, Object data,String typeId){
    DBCollection collection = MongoProvider.getDatabase().getCollection(collectionName);
    try {
      DBObject dbObject = (DBObject) JSON.parse(GsonUtil.toJson(data));
      dbObject.put("type_obj_id",new ObjectId(typeId));
      dbObject.put("created_at", new Date());
      collection.insert(dbObject);
      String id = dbObject.get( "_id" ).toString();
//          LOG.info("insert successfully.");
      return id;
    }catch (Exception e){
      e.printStackTrace();
      LOG.error("query failed: " + e);
      return "";
    }

  }

    public static boolean deleteField(String collectionName, String id, String key){
        DBCollection collection = MongoProvider.getDatabase().getCollection(collectionName);
        try{
            BasicDBObject set = new BasicDBObject();
            set.append("$unset", new BasicDBObject(key, ""));
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("_id", new ObjectId(id));
            collection.update(searchQuery, set);
          LOG.info("delete successfully.");
          return true;
        }catch (Exception e){
            e.printStackTrace();
            LOG.error("delete failed: " + e);
            return false;
        }
    }

    public static boolean deleteDocument(String collectionName, String id){
        DBCollection collection = MongoProvider.getDatabase().getCollection(collectionName);
        try{
            BasicDBObject query = new BasicDBObject();
            query.put("_id", new ObjectId(id));
            collection.remove(query);
          LOG.info("delete successfully.");
          return true;
        }catch (Exception e){
            e.printStackTrace();
          LOG.error("delete failed: " + e);
          return false;
        }
    }

    public static boolean deleteDocument(String collectionName, String key, String value){
        DBCollection collection = MongoProvider.getDatabase().getCollection(collectionName);
        try{
            BasicDBObject query = new BasicDBObject();
            query.put(key, value);
            collection.remove(query);
          LOG.info("delete successfully.");
          return true;
        }catch (Exception e){
            e.printStackTrace();
          LOG.error("delete failed: " + e);
          return false;
        }
    }
  public static boolean deleteDocument(String collectionName, List<Pair<String, String>> pairs){
    DBCollection collection = MongoProvider.getDatabase().getCollection(collectionName);
    try{
      BasicDBObject query = new BasicDBObject();
      for (Pair<String, String> pair : pairs) {
        query.put(pair.getKey(), pair.getValue());
        }
      collection.remove(query);
      LOG.info("delete successfully.");
      return true;
    }catch (Exception e){
      e.printStackTrace();
      LOG.error("delete failed: " + e);
      return false;
    }
  }

    public static boolean update(String collectionName, String id, String key, Object value){
        DBCollection collection = MongoProvider.getDatabase().getCollection(collectionName);
        try{
            BasicDBObject set = new BasicDBObject();
            if(value.getClass().equals(String.class) || value.getClass().equals(Integer.class) || value.getClass().equals(Date.class)){
                set.append("$set", new BasicDBObject(key, value));
            }else {
                DBObject dbObject = (DBObject) JSON.parse(GsonUtil.toJson(value));
                set.append("$set", new BasicDBObject(key, dbObject));
            }
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("_id", new ObjectId(id));
            collection.update(searchQuery, set);
            LOG.info("update done.");
            return true;
        }catch (Exception e){
            e.printStackTrace();
          LOG.error("update failed: " + e);
          return false;
        }
    }

    public static boolean update(String collectionName, List<Pair<String, Object>> pairs, String key, Object value){
        DBCollection collection = MongoProvider.getDatabase().getCollection(collectionName);
        try{
            BasicDBObject set = new BasicDBObject();
            if(value.getClass().equals(String.class) || value.getClass().equals(Integer.class) || value.getClass().equals(Date.class)){
                set.append("$set", new BasicDBObject(key, value));
            }else {
                DBObject dbObject = (DBObject) JSON.parse(GsonUtil.toJson(value));
                set.append("$set", new BasicDBObject(key, dbObject));
            }
            BasicDBObject searchQuery = new BasicDBObject();
            for(Pair<String, Object> pair : pairs){
                if(pair.getKey() == "_id"){
                    searchQuery.put("_id", new ObjectId(pair.getValue().toString()));
                }
                searchQuery.put(pair.getKey(), pair.getValue());
            }
            collection.update(searchQuery, set);
          LOG.info("update done.");
          return true;
        }catch (Exception e){
            e.printStackTrace();
          LOG.error("update failed: " + e);
          return false;
        }
    }
  public static boolean updateMultiField(String collectionName, List<Pair<String, Object>> pairs, List<Pair<String, Object>> couple){
    DBCollection collection = MongoProvider.getDatabase().getCollection(collectionName);
    try{
      BasicDBObject set = new BasicDBObject();
      for (Pair<String,Object> element:
           couple) {
        if(element.getValue().getClass().equals(String.class) || element.getValue().getClass().equals(Integer.class) || element.getValue().getClass().equals(Date.class)){
          set.append(element.getKey(),element.getValue());
        }else {
          DBObject dbObject = (DBObject) JSON.parse(GsonUtil.toJson(element.getValue()));
          set.append("$set", new BasicDBObject().append(element.getKey(), dbObject));
        }
      }
      BasicDBObject setQuery = new BasicDBObject();
      setQuery.append("$set", set);
      BasicDBObject searchQuery = new BasicDBObject();
      for(Pair<String, Object> pair : pairs){
        if(pair.getKey().equals("_id")){
          searchQuery.put("_id", new ObjectId(pair.getValue().toString()));
        }
        searchQuery.put(pair.getKey(), pair.getValue());
      }
      collection.update(searchQuery, setQuery);
//      System.out.println("");
//          System.out.println("sth");
          LOG.info("update done.");
      return true;
    }catch (Exception e){
      e.printStackTrace();
      LOG.error("update failed: " + e);
      return false;
    }
  }

    public static void main(String[] args) {
      System.out.println("test");
//      List<Map<String, Object>> test = MongoUtils.getCollection("vt_org");
//      System.out.println(test.size());
//      Status status = new Status(10,"haga","chien");
//      MongoUtils.insert("vt_org",status);
//      test = MongoUtils.getCollection("vt_org");
//      System.out.println(test.size());
      List<Pair<String,Object>> search = new ArrayList<>();
      List<Pair<String,Object>> data = new ArrayList<>();
      search.add(new Pair<>("employeeCode","439415"));

      Date date = new Date();
      String que = "Thai Duong, Hai Duong";
      data.add(new Pair<>("dateOfBirth",date));
      data.add(new Pair<>("placeOfBirth",que));
      boolean isTrue = updateMultiField("zttns2_copy",search,data);
//      boolean isTrue = update("zttns2_copy",search,"dateOfBirth",date);
      System.out.println(isTrue);
    }

}
package com.viettel.cyber.chatbot.providers;

import com.google.gson.JsonObject;
import io.vertx.core.http.HttpServerResponse;

/**
 * Created by datluyen on 20/05/2017.
 */
public class ResponseProvider {

    private static String SUCCESS_MESSAGES = null;
    private static String INTERNAL_SERVER_ERROR_MESSAGES = null;
    private static String PARAMETER_ERROR_MESSAGES = null;

    static {

        JsonObject jsonSuccess = new JsonObject();
        jsonSuccess.addProperty("messages", "success");
        SUCCESS_MESSAGES = jsonSuccess.toString();


        JsonObject jsonInternalServerError = new JsonObject();
        jsonInternalServerError.addProperty("messages", "Internal server error");
        INTERNAL_SERVER_ERROR_MESSAGES = jsonInternalServerError.toString();


        JsonObject jsonParamterError = new JsonObject();
        jsonParamterError.addProperty("messages", "Parameter error");
        PARAMETER_ERROR_MESSAGES = jsonParamterError.toString();

    }


    private static void addDefaultHeader(HttpServerResponse response){
        response.putHeader("content-type", "application/json");
        response.putHeader("Access-Control-Allow-Origin", "*");
    }


    public static void makeBadRequestResponse(HttpServerResponse response){
        addDefaultHeader(response);
        response.setStatusCode(400);
        response.end(INTERNAL_SERVER_ERROR_MESSAGES);
    }

    public static void makeParameterErrorResponse(HttpServerResponse response){
        addDefaultHeader(response);
        response.setStatusCode(400);
        response.end(PARAMETER_ERROR_MESSAGES);
    }

    public static void makeErrorDBResponse(HttpServerResponse response){
        addDefaultHeader(response);
        response.setStatusCode(500);
        response.end(INTERNAL_SERVER_ERROR_MESSAGES);
    }

    public static void makeSuccessResponse(HttpServerResponse response, String value){
        addDefaultHeader(response);
        response.setStatusCode(200);
        response.end(value);
    }

}
package com.cyberspace.tla.migrate.utils;

import com.cyberspace.tla.migrate.config.ConfigLoad;
import com.cyberspace.tla.migrate.models.org_sync.Content;
import com.mongodb.DBObject;
import org.apache.commons.lang.SerializationException;
import org.apache.commons.lang.SerializationUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.exceptions.JedisClusterException;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by trungnt74 on 23/08/2017.
 */
public class RedisUtil {
    private static int EXPIRE_TIME = Integer.parseInt(ConfigLoad.getConfigLoad().getConfig("redis.time"));
    public static Logger LOG = LoggerFactory.getLogger(RedisUtil.class);

    static Set<HostAndPort> connectionPoints = new HashSet<>();
    static JedisCluster jedisCluster = createCluster();

    private static JedisCluster createCluster(){
        String hosts =  ConfigLoad.getConfigLoad().getConfig("redis.server.hosts");
        String[] hostsArray = hosts.split(",");
        for(String host : hostsArray){
            String[] hostAndPort = host.split(":");
            connectionPoints.add(new HostAndPort(hostAndPort[0], Integer.parseInt(hostAndPort[1])));
        }

        String password =  ConfigLoad.getConfigLoad().getConfig("redis.password");
        if (password != null && !password.equals("")) {
            try {
                return new JedisCluster(connectionPoints, 2000, 2000, 5, password, new GenericObjectPoolConfig());
            } catch (Exception e) {
                System.out.println(e);
            }
        }
        return new JedisCluster(connectionPoints);
    }

    public static void flushDB(){
        jedisCluster.flushDB();
    }

    public static void set(String key, String value){
        try{
            jedisCluster.set(key, value);
            jedisCluster.expire(key, EXPIRE_TIME);
        }catch (JedisClusterException e){
            LOG.error("Failed to save dialog " + key + " to redis: " + e.getMessage());
        }
    }


    public static String get(String key){
        try{
            return jedisCluster.get(key);
        }catch (JedisClusterException e){
            LOG.error("Failed to retrieve " + key + " from redis: " + e.getMessage());
        }
        return null;
    }
  public static void setViaCollection(String collection, List<DBObject> mongo) {
    String key = "mongo::" + collection;
    try {
      jedisCluster.set(SerializationUtils.serialize(key), SerializationUtils.serialize((Serializable) mongo));
      jedisCluster.expire(SerializationUtils.serialize(key), EXPIRE_TIME);
    }catch (JedisClusterException e){
      LOG.error("Failed to save dialog " + key + " to redis: " + e.getMessage());
    }
  }

  public static List<DBObject> getViaCollection(String collection) {
    long startTime = System.currentTimeMillis();
    String key = "mongo::" + collection;
    byte[] obj = null;
    try{
      obj = jedisCluster.get(SerializationUtils.serialize(key));
    }catch (JedisClusterException e){
      LOG.error("Failed to retrieve dialoge info with key " + key + ":" + e.getMessage());
    }
    if (obj != null) {
      try {
        List<DBObject> mongo = (List<DBObject>)SerializationUtils.deserialize(obj);
        long endTime = System.currentTimeMillis();
        LOG.info("get "+ collection +" in " + (endTime - startTime) + "ms");
        return mongo;
      } catch (SerializationException | ClassCastException e) {
        LOG.info("Can not cast to mongo object: " + obj.toString(), e);
      }
    }
    return null;
  }
  public static List<Content> getAllUnitViaCollection(String collection) {
    long startTime = System.currentTimeMillis();
    String key = "mongo::" + collection;
    byte[] obj = null;
    try{
      obj = jedisCluster.get(SerializationUtils.serialize(key));
    }catch (JedisClusterException e){
      LOG.error("Failed to retrieve dialoge info with key " + key + ":" + e.getMessage());
    }
    if (obj != null) {
      try {
        List<Content> mongo = (List<Content>)SerializationUtils.deserialize(obj);
        long endTime = System.currentTimeMillis();
        LOG.info("get "+ collection +" in " + (endTime - startTime) + "ms");
        return mongo;
      } catch (SerializationException | ClassCastException e) {
        LOG.info("Can not cast to mongo object: " + obj.toString(), e);
      }
    }
    return null;
  }
}
package com.cyberspace.tla.migrate.providers;

import com.google.gson.Gson;

/**
 * @Description: Create a gson provider to use for others.*/
public class GsonProvider {
  public static Gson gson =  new Gson();

  public static Gson getGson(){
    return gson;
  }
}
package com.cyberspace.tla.migrate.providers;

import com.cyberspace.tla.migrate.config.ConfigLoad;
import com.mongodb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

public class MongoProvider {

  private static String dbName;
  private static MongoClient mongo;
  public static Logger logger = LoggerFactory.getLogger(MongoProvider.class);

  private static MongoCredential credential;

  private static MongoClient createMongoClient(){
    int auth = Integer.parseInt(ConfigLoad.getConfigLoad().getConfig("mongo.auth"));
    if(auth ==1) {
      dbName = ConfigLoad.getConfigLoad().getConfig("mongo.authSource");
      String host = ConfigLoad.getConfigLoad().getConfig("mongo.host");
      String port = ConfigLoad.getConfigLoad().getConfig("mongo.port");
      String username = ConfigLoad.getConfigLoad().getConfig("mongo.username");
      String password = ConfigLoad.getConfigLoad().getConfig("mongo.password");

      credential = MongoCredential.createCredential(username, dbName, password.toCharArray());
      MongoClient mongoClient = new MongoClient(new ServerAddress(host, Integer.parseInt(port)), Arrays.asList(credential));
      logger.info("create mongo client successfull");
      return mongoClient;
    }else {
      dbName = ConfigLoad.getConfigLoad().getConfig("mongo.authSource");
      String host = ConfigLoad.getConfigLoad().getConfig("mongo.host");
      String port = ConfigLoad.getConfigLoad().getConfig("mongo.port");
      String username = ConfigLoad.getConfigLoad().getConfig("mongo.username");
      String password = ConfigLoad.getConfigLoad().getConfig("mongo.password");
      MongoClient mongoClient = new MongoClient(new ServerAddress(host, Integer.parseInt(port)));
      logger.info("create mongo client successfull");
      return mongoClient;
    }
  }
  public static DB getDatabase(){
    if(mongo == null)mongo = createMongoClient();
    return mongo.getDB(dbName);
  }


}
package com.cyberspace.tla.migrate.config;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashMap;
import java.util.Properties;

/**
 * @Description: is used to load config from config file*/
public class ConfigLoad {
//path to config file
//  private static String CONFIG_PATH = "config/config-dev.properties";
  private static String FILE_CONFIG_DEV = "config/config-dev.properties";
  private static String FILE_CONFIG_PROD = "config/config-prod.properties";
//  storage to config
  private HashMap<String, String> mapConfig = new HashMap<>();
  public static Logger logger = LoggerFactory.getLogger(ConfigLoad.class);

  private void loadConfig(String source){
    Properties mapProperties = new Properties();

    try{
      mapProperties.load(new InputStreamReader(new FileInputStream(source),"UTF-8"));
      for (String key :
        mapProperties.stringPropertyNames()) {
        String value = mapProperties.getProperty(key);
        mapConfig.put(key,value);
      }
    } catch (FileNotFoundException e) {
      logger.error("Failed to load config: " + e.getMessage());
      throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
      logger.error("Failed to load config: " + e.getMessage());
      throw new RuntimeException(e);
    } catch (IOException e) {
      logger.error("Failed to load config: " + e.getMessage());
      throw new RuntimeException(e);
    }
  }

  public String getConfig(String key){
    return mapConfig.get(key);
  }

  private static ConfigLoad configLoad = null;

  public static ConfigLoad getConfigLoad(){

    return configLoad;
  }

  public static ConfigLoad init(String mode) {
    if (configLoad == null){
      configLoad = new ConfigLoad();

      if (mode == null || mode.equalsIgnoreCase("dev")) {
        configLoad.loadConfig(FILE_CONFIG_DEV);
        System.out.println("dev");
      } else {
        configLoad.loadConfig(FILE_CONFIG_PROD);
        System.out.println("prod");
      }

    }
    return configLoad;
  }
}
package com.cyberspace.tla.migrate.config;

import org.apache.commons.cli.*;

public class CLI {
  private Options options;

  public CLI(){
    this.init(getDefaultOptions());
  }

  public CLI(Options options){
    this.options = options;
  }
  /**
   *  Init needed arguments
   */
  public void init(Options options){
    this.options = options;
  }

  /**
   * Parse args from command line
   * @param args List arguments input
   * @return return CommandLine object which contains all input params.
   */
  public CommandLine parse(String[] args) throws ParseException {
    options = new Options();

    Option c = new Option("m", "mode", true, "mode dev or prod");
    c.setRequired(false);
    options.addOption(c);

    CommandLineParser parser = new DefaultParser();
    return parser.parse(options, args);
  }

  /**
   * Print helping message
   * @param message
   */
  public void help(String message){
    HelpFormatter formatter = new HelpFormatter();
    System.out.println(message);
  }

  public Options getOptions() {
    return options;
  }

  public void setOptions(Options options) {
    this.options = options;
  }

  public static Options getDefaultOptions(){
    Options options = new Options();
    Option c = new Option("m", "mode", true, "mode dev or prod");
    c.setRequired(false);
    options.addOption(c);

    //TODO add more options

    return options;
  }
}
package com.codecademy.ccapplication;
import java.util.List;
import java.lang.Iterable;
import java.util.Date;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PathVariable;

@RestController
@RequestMapping("/superHeroes")
public class SuperHeroController {

  private final SuperHeroRepository superHeroRepository;
  private final SuperReportRepository superReportRepository;

  public SuperHeroController(SuperHeroRepository superHeroRepository, SuperReportRepository superReportRepository) {
    this.superHeroRepository = superHeroRepository;
    this.superReportRepository = superReportRepository;
  }

  @GetMapping()
	public Iterable<SuperHero> getSuperHeros() {
    Iterable<SuperHero> superHeroes = superHeroRepository.findAll();
    return superHeroes;
	}

  @PostMapping(path="/addNew")
  public String createNewSuperHero(@RequestParam String firstName, @RequestParam String lastName, @RequestParam String superPower) {
    SuperHero newSuperHero = new SuperHero(firstName, lastName, superPower);
    superHeroRepository.save(newSuperHero);
    return "New Super Hero successfully added!";
  }

  @PostMapping(path="/help")
  public String postHelp(@RequestParam String postalCode, @RequestParam String streetAddress) {
    SuperReport newSuperReport = new SuperReport(postalCode, streetAddress, "");
    superReportRepository.save(newSuperReport);
    return "Thanks! Super Heroes have been dispatched to your location!";
  }

  @GetMapping(path="/heroReport")
  public Iterable<SuperReport> getHeroReport() {
    Iterable<SuperReport> superReport = superReportRepository.findAll();
    return superReport;
  }

  @PostMapping(path="/{postalCode}")
  public Iterable<SuperReport> getHeroReportByPostal(@PathVariable String postalCode) {
    Iterable<SuperReport> superReport = superReportRepository.findByPostalCode(postalCode);
    return superReport;
  }
}
import java.util.Stack;

public class HistogramArea {
   /* public static int minVal(int[] arr, int i,int j){
        int min= Integer.MAX_VALUE;
        for(int k=i;k<=j;k++){
            min=Math.min(min,arr[k]);
        }
        return min;
    }
    public static int maxArea(@NotNull int[] arr){
        int max=Integer.MIN_VALUE, area=0;
        for(int i=0;i< arr.length;i++){
            for (int j = i; j < arr.length; j++) {
                int width=j-i+1;
                int length=minVal(arr,i,j);
                area=length*width;
                max=Math.max(area,max);
            }
        }
        return max;
    }*/
    public static void maxArea(int[] arr){
        int maxArea=0;
        int[] nsr =new int[arr.length];
        int[] nsl =new int[arr.length];
        Stack<Integer> s=new Stack<>();
        //next smaller right
        for (int i = arr.length-1; i >=0 ; i--) {
            while(!s.isEmpty()&&arr[s.peek()]>=arr[i]){
                s.pop();
            }
            if(s.isEmpty()) nsr[i]=arr.length;
            else nsr[i]=s.peek();
            s.push(i);
        }

        s=new Stack<>();
        //next smaller left
        for (int i = 0;i<arr.length;i++) {
            while(!s.isEmpty()&&arr[s.peek()]>=arr[i]){
                s.pop();
            }
            if(s.isEmpty()) nsl[i]=arr.length;
            else nsl[i]=s.peek();
            s.push(i);
        }

        for (int i = 0; i < arr.length; i++) {
            int h=arr[i];
            int w=nsr[i]-nsl[i]-1;
            int area=h*w;
            maxArea=Math.max(area,maxArea);
        }
        System.out.println(maxArea);
    }

    public static void main(String[] args){
        int[] arr={2,1,5,6,2,3};
        maxArea(arr);
    }
}
import java.util.Stack;

public class Parenthesis {
    public static boolean isValid(String str){
        Stack<Character> s=new Stack<>();
        int i=0;
        while(i<str.length()){
            if(str.charAt(i)=='('||str.charAt(i)=='{'||str.charAt(i)=='[') s.push(str.charAt(i));
            if(!s.isEmpty()){
                if((str.charAt(i)==')'&&s.peek()=='(')
                        ||(str.charAt(i)=='}'&&s.peek()=='{')
                        ||(str.charAt(i)==']'&&s.peek()=='[')){
                    s.pop();
                }
            }
            i++;
        }
        return s.isEmpty();
    }
    
    public static boolean duplicateParenthesis(String str){
        if(isValid(str)){
            Stack<Character> s=new Stack<>();
          for(int i=0;i<str.length();i++){
              if(str.charAt(i)==')'){
                  int count=0;
                  while(s.pop()!='(') count++;
                  if(count==0) return true;
              }
              else s.push(str.charAt(i));
          }
        }
        return false;
    }
    public static void main(String[] args){
        String str="((a+b)+((c+d)))";
        System.out.println(duplicateParenthesis(str));

    }
}
import java.util.Stack;
public class StockSpan {
    public static void stockSpan(int[] arr) {
        int[] span = new int[arr.length];
        Stack<Integer> s = new Stack<>();
        span[0] = 1;
        s.push(0);
        for(int i = 1; i < arr.length; i++) {
            while (!s.isEmpty() && arr[i] > arr[s.peek()]) s.pop();
            if (s.isEmpty()) span[i] = i + 1;
            else span[i] = i - s.peek();
            s.push(i);
            }
        for (int j : span) {
            System.out.println(j + " ");
        }
        return;
    }
    public static void main(String[] args){
        int[] arr={100,80,60,70,60,85,100};
        stockSpan(arr);
    }
}
import java.util.*;

public class Stacks {
   /* static class Stack{
        static ArrayList<Integer> list= new ArrayList<>();
        public boolean isEmpty(ArrayList<Integer> list){
            return list.size()==0;
        }
        public int pop(ArrayList<Integer> list){
            if(isEmpty(list)) return -1;
            int x= list.get(list.size()-1);
            list.remove(list.size()-1);
            return x;
        }
        public void push(ArrayList<Integer> list, int n){
            list.add(n);
            return;
        }
        public int peek(ArrayList<Integer> list){
            if(isEmpty(list)) return -1;
            return list.get(list.size()-1);
        }
    }*/
   public static Stack bottomPush(Stack s,int n){
        if(s.isEmpty()) {
            s.push(n);
            return s;
        }
        int x= (int) s.pop();
        bottomPush(s,n);
        s.push(x);
        return  s;
    }

    public static String stringReverse(String str){
        Stack<Character> s= new Stack<>();
        int i=0;
        StringBuilder sb=new StringBuilder("");
        while(i<str.length()){
            s.push(str.charAt(i));
            i++;
        }
        i=0;
        while(i<s.size()){
            sb.append(s.pop());
        }
        return sb.toString();
    }

    public static Stack reverseStack(Stack s){
        if(s.size()==0) return s;
        int x= (int) s.pop();
        reverseStack(s);
        bottomPush(s,x);
        return s;
    }
    public static void main(String[] args){
        Stack <Integer> s=new Stack<>();
        s.push(1);
        s.push(2);
        s.push(3);
        s.push(4);
        System.out.println(s);
        System.out.println(stringReverse("a"));
        System.out.println(reverseStack(s));
    }
}
public class KeypadSolution {
    public static void printKeypad(int input,String output) {
        if (input == 0) {
            System.out.println(output);
            return;
        }
        int rem = input % 10;
        char[] helperArray = helper(rem);
        printKeypad(input / 10, helperArray[0] + output);
        printKeypad(input / 10, helperArray[1] + output);
        printKeypad(input / 10, helperArray[2] + output);
        if (helperArray.length == 4) printKeypad(input / 10, helperArray[3] + output);
    }

    public static char[] helper(int n){
                 if (n == 2) return new char[]{'a', 'b', 'c'};
            else if (n == 3) return new char[]{'d', 'e', 'f'};
            else if (n == 4) return new char[]{'g', 'h', 'i'};
            else if (n == 5) return new char[]{'j', 'k', 'l'};
            else if (n == 6) return new char[]{'m', 'n', 'o'};
            else if (n == 7) return new char[]{'p', 'q', 'r', 's'};
            else if (n == 8) return new char[]{'t', 'u', 'v'};
            else if (n == 9) return new char[]{'w', 'x', 'y', 'z'};
            else             return new char[]{' '};
        }
    public static void main(String[] args){
        printKeypad(97,"");
        }
}
import java.util.*;
public class LinkedList {
    public static class Node{
        int data;
        Node next;
        public Node (int data) {
            this.data = data;
            this.next = null;
        }
    }
    public static Node head;
    public static Node tail;
    public static int size;

    public void addFirst(int data){
        Node newNode=new Node(data);
        size++;
        if(head==null){
            head=tail=newNode;
            return;
        }
        newNode.next=head;
        head=newNode;
    }

    public void addLast(int data){
        Node newNode= new Node(data);
        tail.next=newNode;
        newNode.next=null;
        tail=newNode;
    }

    public void add(int idx, int data){
        if(idx==0){
            addFirst(data);
        }
        else{
            Node newNode=new Node(data);
            size++;
            Node temp=head;
            int i=0;
            while(i<idx-1){
                temp=temp.next;
                i++;
            }
            newNode.next=temp.next;
            temp.next=newNode;
        }
    }

    public void printLL(LinkedList ll){
        Node temp=ll.head;
        while(temp!=null){
            System.out.print(temp.data + "->");
            temp=temp.next;
        }
        System.out.println("null");
    }

    public Node findMid(Node head){
        Node slow=head;
        Node fast=head;
        while(fast!=null &&  fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        return slow;
    }

    public boolean checkPalindrome(){
        if(head==null || head.next==null) return true;
        Node midNode=findMid(head);
        Node prev=null;
        Node curr=midNode;
        Node next;
        while(curr!=null){
            next=curr.next;
            curr.next=prev;
            prev=curr;
            curr=next;
        }
        Node right=prev;
        Node left=head;
        while(right!=null){
            if(left.data!=right.data) return false;
            left = left.next;
            right=right.next;
        }
        return true;

    }

    public static void main(String[] args){
        LinkedList ll = new LinkedList();
        ll.addFirst(1);
        ll.addLast(2);
        ll.addLast(3);
        ll.addLast(1);
        ll.add(3,2);
        //ll.printLL(ll);
        System.out.println(ll.checkPalindrome());

    }
}
Game game = new Game();

// Earn some gold
game.earnGold(200);

// Buy an upgrade
game.buyUpgrade("Upgrade");

// Buy an invention
game.buyInvention("Invention");

// Upgrade the character
game.upgradeCharacter("Character");
public class Game {
  // Instance variables to hold the player's gold and inventory
  private int gold;
  private List<String> inventory;

  // Constructor to initialize the game
  public Game() {
    gold = 0;
    inventory = new ArrayList<>();
  }

  // Method to earn gold
  public void earnGold(int amount) {
    gold += amount;
  }

  // Method to buy an upgrade
  public void buyUpgrade(String upgrade) {
    if (gold >= 100) {
      gold -= 100;
      inventory.add(upgrade);
    }
  }

  // Method to buy an invention
  public void buyInvention(String invention) {
    if (gold >= 1000) {
      gold -= 1000;
      inventory.add(invention);
    }
  }

  // Method to get the player's gold
  public int getGold() {
    return gold;
  }

  // Method to get the player's inventory
  public List<String> getInventory() {
    return inventory;
  }

  // Method to upgrade the character
  public void upgradeCharacter(String character) {
    if (inventory.contains("Upgrade")) {
      // Upgrade the character here
    }
  }

  // Main method to run the game
  public static void main(String[] args) {
    Game game = new Game();

    // Earn some gold
    game.earnGold(200);

    // Buy an upgrade
    game.buyUpgrade("Upgrade");

    // Buy an invention
    game.buyInvention("Invention");

    // Upgrade the character
    game.upgradeCharacter("Character");
  }
}
public class PJJJeden {

    public static void main(String[] args) {
        int number = 12354;
        int c = Count(number);

        int[] digits = new int[c];

        for (int i = c - 1; i >= 0; i--) {
            digits[i] = number % 10;
            number = number / 10;
        }
        for (int number : digits) {
            System.out.println(number);
        }
    }
    public static int Count(int number) {
        int count = 0;
        while (number != 0) {
            number = number / 10;
            count++;
        }
        return count;
    }
}
import java.util.Arrays;
import java.util.Scanner;
public  class Main {
    public static void permut(String s, String ans) {
        String news="";
         if(news.length()==s.length()) {
             System.out.println(ans);
             return;
         }
         for(int i=0;i<s.length();i++){
             char curr=s.charAt(i);
             news =s.substring(0,i) + s.substring(i+1);
             permut(news,ans+curr);
         }
}
public static void main(String[] args) {
        String s="abc";
        permut(s,"");
    }
}
public class Main2 {
    public static void subSets(String s, String sb,int i){
        if(i==s.length()) {
            System.out.println(sb);
            return;
        }
        subSets(s,sb+s.charAt(i),i+1);
        subSets(s,sb,i+1);
    }
    public static void main(String[] args){
        String s="aef";
        subSets(s,"",0);
    }
}
public class Main3
{
    public static void nQueens( char[][] board,int row){
        if(row== board.length) {
            printBoard(board);
            return;
        }
        for (int j = 0; j < board.length; j++) {
           if(isSafe(board,row,j)){
               board[row][j]='Q';
               nQueens(board,row+1);
               board[row][j]='X';
           }
        }
    }
    public static void printBoard(char[][] board){
        System.out.println("---------chess board---------");
        for (char[] chars : board) {
            for (int j = 0; j < board.length; j++) {
                System.out.print(chars[j] + " ");
            }
            System.out.println();
        }
    }
    public static boolean isSafe(char[][] board,int row,int col){
        for(int i=row-1;i>=0;i--){
            if(board[i][col]=='Q') return false;
        }
        for(int i=row-1,j=col+1;i>=0&&j< board.length;i--,j++){
            if(board[i][j]=='Q') return false;
        }
        for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--){
            if(board[i][j]=='Q') return false;
        }
        return true;
    }
    public static void main(String[] args){
        int n=8;
        char[][] board=new char[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                board[i][j]='X';
            }
        }
        nQueens(board,0);
    }
}
public class Main4 {
    public static boolean SudokuSolver(int[][] sudoku,int row, int col ){
       if(row==9) return true;

        int nextRow=row,nextCol=col+1;
       if(col+1==9){
           nextRow=row+1;
           nextCol=0;
       }
       if(sudoku[row][col]!=0) return  SudokuSolver(sudoku,nextRow,nextCol);
       for(int digit=1;digit<10;digit++){
           if(isSafe(sudoku,row,col,digit)){
               sudoku[row][col]=digit;
               if(SudokuSolver(sudoku,nextRow,nextCol)) return true;
               sudoku[row][col]=0;
           }
       }
       return false;
    }

    public static boolean isSafe(int [][] sudoku,int row, int col, int digit){
        for (int i = 0; i < 9; i++) {
            if(sudoku[i][col]==digit) return false;
        }
        for(int j=0;j<9;j++){
            if(sudoku[row][j]== digit) return false;
        }
        int sr=(row/3)*3, sc=(col/3)*3;
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                if(sudoku[sr+i][sc+j]==digit) return false;
            }
        }
        return true;
    }

    public static void main(String[] args){
        int sudoku[][]={
                { 3, 0, 6, 5, 0, 8, 4, 0, 0 },
                { 5, 2, 0, 0, 0, 0, 0, 0, 0 },
                { 0, 8, 7, 0, 0, 0, 0, 3, 1 },
                { 0, 0, 3, 0, 1, 0, 0, 8, 0 },
                { 9, 0, 0, 8, 6, 3, 0, 0, 5 },
                { 0, 5, 0, 0, 9, 0, 6, 0, 0 },
                { 1, 3, 0, 0, 0, 0, 2, 5, 0 },
                { 0, 0, 0, 0, 0, 0, 0, 7, 4 },
                { 0, 0, 5, 2, 0, 6, 3, 0, 0 }
        };

        if(SudokuSolver(sudoku,0,0)){
            System.out.println("Solution exists");
            for (int i = 0; i < 9; i++) {
                for (int j=0;j<9;j++){
                    System.out.print(sudoku[i][j]+" ");
                }
                System.out.println();
            }
        }
    }
}
import java.util.Arrays;
import java.util.Scanner;

public class PJJJeden {

    public static void main(String[] args) {
        Kwadrat();
    }
    static void Kwadrat(){
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        System.out.println();
        int b = sc.nextInt();
        int result = 1;
        for(int i = 0; i < b; i++){
            result = result * a;
        }
        System.out.println(result);
    }
}
// class Fruit
public class Fruit {
    public String name;
    public double weight;
    Fruit(String name){
        this.name = name;
        this.weight = Math.random()*0.3+0.5;
    }
    public void show(){
        System.out.println(name + "  " + weight);
    }
}

// class PJJJeden
public class PJJJeden {
    public static void main(String[] args) {
  
        //--------------------------//
        Fruit fruit = new Fruit("Cherry");
        fruit.show();
        //--------------------------//
    }
}
public class PJJJeden {
    public static void main(String[] args) {
        Person person = new Person();
        person.name = "Mania";
        person.surname = "Czeska";
        person.birthYear = 2002;
//oraz klasa: 
public class Person {
    public String name;
    public String surname;
    public int birthYear;
}
int nk = arr.length - 1 -n;
in (nk<n) return;
for (int i = n; i <= mk; i++)
    arr[n][i] = arr[nk][i] = arr [i][n] = arr[i][nk] = n+1;
fill (arr, n+1);
 {
		Scanner sc = new Scanner(System.in);

		System.out.println("Enter the number");

		int n = sc.nextInt();

		String num = String.valueOf(n);                              //Converting int to string type;
                      
		for(int i=0 ; i<num.length() ; i++)
 {
			switch(num.charAt(i))
   {                                                                    //checking the alphanumeric value for the digit
				case '0':
					System.out.print("zero ");
					break;
				case '1':
					System.out.print("one ");
					break;
				case '2':
					System.out.print("two ");
					break;
				case '3':
					System.out.print("three ");
					break;
				case '4':
					System.out.print("four ");
					break;
				case '5':
					System.out.print("five ");
					break;
				case '6':
					System.out.print("six ");
					break;
				case '7':
					System.out.print("seven ");
					break;
				case '8':
					System.out.print("eight ");
					break;
				case '9':
					System.out.print("nine ");
					break;
			}
		}
	}
}
import java.util.Scanner;

public class PJJJeden {

    public static void main(String[] args) {
        int[] tab = {1, 2, 3, 4, 5, 7, 8, 9, 10, 0};
        Scanner sc = new Scanner(System.in);
        System.out.print("Wartość: ");
        int wart = sc.nextInt();
        System.out.println("Wpisana wartość będzie sumą elementów tablicy: ");
        for(int i = 0; i < tab.length; i++){
            for(int j = 0; j <tab.length; j++){
                if ((tab[i] + tab[j] == wart)||(tab[j] + tab[i] == wart)){
                    System.out.println(tab[i] + " " + tab[j] );}
            }
        }
    }
}
import java.util.Arrays;
public class PJJJeden {

    public static void main(String[] args) {
        int[] tabA = {25, 14, 56, 15, 36, 36, 77, 18, 29, 49};
        int[] tabB = {25, 14, 56, 17, 38, 36, 97, 18, 69, 99};
        CheckVal(tabA, tabB);
            }

    public static boolean CheckVal(int tabA[], int tabB[]) {
        for (int i = 0; i < tabA.length; i++) {
            for (int j = 0; j < tabB.length; j++) {
                if (tabA[i] == tabB[j])
                    System.out.println(tabA[i]);
            }

        }
        return false;
    }
}
public class PJJJeden {

    public static void main(String[] args) {
        int[] tab = {25, 14, 56, 15, 36, 36, 77, 18, 29, 49};
        checkVal(tab);
    }
    public static boolean checkVal(int[] tab) {
        for (int i = 0; i < tab.length; i++) {
            if (tab[i] == tab[i + 1]) {
                System.out.println(tab[i]);
                return true;
            }
        }
        return false;
    }

}
  public static int  findIndex (int[] my_array, int t) {
        if (my_array == null) return -1;
        int len = my_array.length;
        int i = 0;
        while (i < len) {
            if (my_array[i] == t) return i;
            else i=i+1;
        }
        return -1;
    }
import java.sql.SQLOutput;
import java.util.Arrays;
import java.util.Scanner;
public class PJJJeden {
    public static boolean check(int[] tab, int x) {
        for (int i = 0; i <= tab.length; i++) {
            if (x == tab[i]) {
                return true;
            }
        }
        return false;
    }
    public static void main(String[] args) {
        int tab[] = {1, 2, 3, 4, 5};
        int a = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println(" Podaj wartosc: ");
        int x = sc.nextInt();
        System.out.println(check(tab, 4));
    }
}

import java.sql.SQLOutput;
import java.util.Arrays;
import java.util.Scanner;
public class PJJJeden {
    public static void main(String[] args) {
        int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        double sum = 0;
        double count = 0;
        for(int a : my_array){
            count++;
            sum += a;
        }
        System.out.println(sum);
        System.out.println(count);
        System.out.println(sum/count);
    }
}
public class Main {
    public static void main(String[] args) {
        // write your code here
        char c = 'A';
        System.out.println(c);

        boolean fact = true;
        fact = false;
        System.out.println(fact);

        byte data = 'd';
        System.out.println(data);
    }
}
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class LeftSide
{
public LeftSide()
{
JFrame frame = new JFrame("Button");
JPanel panel = new JPanel();
JButton button = new JButton("Submit");
button.setPreferredSize(new Dimension(200, 30));
button.setIcon(new ImageIcon(this.getClass().getResource("submit.gif")));
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}

public static void main(String[] args)
{
new LeftSide();
}
Connection = 
  Helps our java project connect to database
Statement = 
  Helps to write and execute SQL query
ResultSet = 
  A DataStructure where the data from query result stored
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    

  After succesfully created the connect
next step is STATEMENT

Statement statement = connection.createStatement();
We use createStatement() method to create
the statement from our connection.
-The result we get from this type of statement
can only move from top to bottom,
not other way around

Statement statement = connection.
createStatement(ResultSet TYPE_SCROLL_INSENSITIVE
,ResultSet CONCUR_READ_ONLY);

-The result we get from this type of
statement can freely move between rows

Once we have statement we can run
the query and get the result to
ResultSet format 
		import java.sql.ResultSet;
        
We use the method executeQuery()
to execute our queries

ResultSet result = statement.
              executeQuery("Select * from employees");
class firstClass {
    void method1(int a) {
        System.out.println("1");
    }
}

class secondClass extends firstClass{

    public static void main(String[] args) {
        secondClass sc= new secondClass();
        sc.method1(45);
    }
}
class encapsulation {
    private int number;
    
    public int getNumber() {
        return number;
    }
    
    public void setNumber(int number){
        this.number = number;
    }
}
// Dynamic poly, Method overriding(same name, different class, same arguments(type, sequence, number, IS-A relationship)
class firstClass {
    void method1(int a) {
        System.out.println("1");
    }
}


class secondClass extends firstClass{
    void method1(String a) {
        System.out.println("2");
    }

    public static void main(String[] args) {
        firstClass fc = new firstClass();
        fc.method1(1);
        secondClass sc= new secondClass();
        sc.method1(45);
    }
}
class CompileTimePoly {
    // Static polymorphism, Method overloading(same name, same class, diff parameters:- type, number, sequence)

    void method1(int a, int b) {
        System.out.println("1");
    }

    void method1(String a, int b){
        System.out.println("2");
    }

    public static void main(String[] args) {
        CompileTimePoly compileTimePoly = new CompileTimePoly();
        compileTimePoly.method1("hello",5);
    }
}
abstract class vehicle {
    abstract void start();
}

class Bike extends vehicle {
    public void start() {
        System.out.println("Starts with kick");
    }
}

class Car extends vehicle {
    public void start() {
        System.out.println("Starts with key");
    }
    public static void main(String[] args) {
        Bike bike = new Bike();
        bike.start();
        Car car = new Car();
        car.start();
    }
}
class Pair{
    int first;
    int second;
    Pair(int first,int second){
        this.first=first;
        this.second=second;
    }
    public boolean equals(Object o) {
        if (o instanceof Pair) {
            Pair p = (Pair)o;
            return p.first == first && p.second == second;
        }
        return false;
    }
    public int hashCode() {
        return new Integer(first).hashCode() * 31 + new Integer(second).hashCode();
    }
}
import java.util.*;
import java.io.*;

public class Main{
    static class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){
            br=new BufferedReader(new InputStreamReader(System.in));
        }
        String next(){
            while(st==null || !st.hasMoreTokens()){
                try {
                    st=new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt(){
            return Integer.parseInt(next());
        }
        long nextLong(){
            return Long.parseLong(next());
        }
        double nextDouble(){
            return Double.parseDouble(next());
        }
        String nextLine(){
            String str="";
            try {
                str=br.readLine().trim();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    public static void main(String[] args) {
    	FastReader sc = new FastReader();
		
    }
}
String m = Integer.toString(month);
String d = Integer.toString(day);
String y = Integer.toString(year);
String providedDate = d+"-"+m+"-"+y;
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyy");
try {
  Date date = format.parse(providedDate);
  // getting day from the date
  String actualDay = new SimpleDateFormat("EEEE").format(date);
  return actualDay.toUpperCase();
} catch(ParseException e) {
  System.out.print(e);
}
try {
     JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
     Log.d("Error", err.toString());
}
switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}
int time = 20;
if (time < 18) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}
// Outputs "Good evening."
if (condition) {
  // block of code to be executed if the condition is true
} else {
  // block of code to be executed if the condition is false
}
if (20 > 18) {
  System.out.println("20 is greater than 18");
}
if (condition) {
  // block of code to be executed if the condition is true
}
String testpro1 = "TestPro";


String testpro2 = "TestPro";



system.out.println(testpro1.equals(testpro2));
int a = 7;

and

int b = 7; 

system.out.println(a == b);
class Main {
  public static void main (String[] args) {

    int a = 5;
    int b = 2;

    double result = 5/2.0;

    int c = 4;

    System.out.println (c++);
  }
}
class Main {
  public static void main (String[] args) {

    int a = 5;
    int b = 2;

    double result = 5/2.0;

    int c = 4;

    System.out.println (c++);
  }
}
class Main {
  public static void main (String[] args) {

    int a = 5;
    int b = 2;

    double result = 5/2.0;

    System.out.println (result);
  }
}
class Main {
  public static void main (String[] args) {

    int a = 7;
    int b = 8;

    int result = a%b;

    System.out.println (result);
  }
}
class Main {
  public static void main (String[] args) {

    int a = 7;
    int b = 8;

    int result = a-b;

    System.out.println (result);
  }
}
class Main {
  public static void main (String[] args) {

    int a = 7;
    int b = 8;

    int result = a+b;

    System.out.println (result);
  }
}
String greeting = "My name is"; 

String name = "Azat"; 
String stingExample = "I am string";
System.out.println ("2+2 equals 4");
System.out.println (2+2);
List<WebElement> listOfElements = driver.findElements(By.xpath("//div"));
Actions a = new Actions(driver);

//Double click on element
WebElement element = driver.findElement(By.xpath(locator));

a.doubleClick(element).perform();
Actions action = new Actions(driver); 
element = driver.findElement(By.cssLocator(locator));
action.moveToElement(element).click();
Actions action = new Actions(driver);
action.moveToElement(element).click().perform();
{
  "employees":[

    { "firstName":"John", "lastName":"Doe" },

    { "firstName":"Anna", "lastName":"Smith" },

    { "firstName":"Peter", "lastName":"Jones" }]
}
<employees>
  <employee>
    <firstName>John</firstName>
    <lastName>Doe</lastName>
  </employee>
  <employee>
    <firstName>Anna</firstName>
    <lastName>Smith</lastName>
  </employee>
  <employee>
    <firstName>Peter</firstName>
    <lastName>Jones</lastName>
  </employee>
</employees>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}

#myImg {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
}

img {
    -webkit-filter: brightness(100%);
}

#myImg:hover {
    -webkit-filter: brightness(80%);
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    -ms-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (image) */
.modal-content {
  margin: 0 auto;
  display: block;
  width: 90%;
  max-width: 90%;
}

/* Caption of Modal Image */
#caption {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}

/* Add Animation */
.modal-content, #caption {  
  -webkit-animation-name: zoom;
  -webkit-animation-duration: 0.6s;
  animation-name: zoom;
  animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
  from {-webkit-transform:scale(0)} 
  to {-webkit-transform:scale(1)}
}

@keyframes zoom {
  from {transform:scale(0)} 
  to {transform:scale(1)}
}

/* The Close Button */
.close {
  position: absolute;
  top: 20px;
  right: 65px;
  color: #ff5555;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
  .modal-content {
    width: 90%;
  }
}
.center {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
  margin: auto;
}
    
</style>
</head>
<body>

<center><img class="myImages" id="myImg" 

src="https://lwfiles.mycourse.app/testpro-public/c453e4c73efebdbd55d7c48e24d4aca4.jpeg"

style="width:100%;max-width:700px">

<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <img class="modal-content" id="img01">
  <div id="caption"></div>
</div>

<script>
// create references to the modal...
var modal = document.getElementById('myModal');

// to all images -- note I'm using a class!
var images = document.getElementsByClassName('myImages');

// the image in the modal
var modalImg = document.getElementById("img01");

// and the caption in the modal
var captionText = document.getElementById("caption");

// Go through all of the images with our custom class
for (var i = 0; i < images.length; i++) {
  var img = images[i];
 
 // and attach our click listener for this image.
  img.onclick = function(evt) {
    console.log(evt);
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
  }
}

var span = document.getElementsByClassName("close")[0];

span.onclick = function() {
  modal.style.display = "none";
}

</script>

</body>
</html>
 String result = CharStreams.toString(new InputStreamReader(
       inputStream, Charsets.UTF_8));
 String result = CharStreams.toString(new InputStreamReader(
       inputStream, Charsets.UTF_8));
@FunctionalInterface
interface Function6<One, Two, Three, Four, Five, Six> {
    public Six apply(One one, Two two, Three three, Four four, Five five);
}

public static void main(String[] args) throws Exception {
    Function6<String, Integer, Double, Void, List<Float>, Character> func = (a, b, c, d, e) -> 'z';
}
FacesContext facesContext = FacesContext.getCurrentInstance();
FacesMessage facesMessage = new FacesMessage("This is a message");
facesContext.addMessage(null, facesMessage);
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <!-- The apiVersion may need to be increased for the current release -->
    <apiVersion>53.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>APP NAME HERE</masterLabel>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
Feature: Smoke

Scenario: User Login
Given I open the url "/"
When I set "dancefront6@gmail.com" to the inputfield "//input[@type='email']"
And I set "te$t$tudent" to the inputfield "//input[@type='password']"
And I click on the button "//button"
And I pause for 1000ms
Then I expect that element "//i[@class='fa fa-sign-out']" is displayed
# The Logout icon is displayed

Scenario: User Searches for a Song
When I set "Ketsa" to the inputfield "//input[@name='q']"
And I pause for 2000ms
Then I expect that container "//section[@class='songs']//span[@class='details']" contains the text "Ketsa"
# There is a bug in the framework - only 'container' type works here

Scenario: User Plays a Song
Given I open the url "#!/songs"
# Easier way to start the playback is from All Songs page
And I doubleclick on the button "//section[@id='songsWrapper']//td[@class='title']"
# Double click is handy here
And I pause for 2000ms
Then I expect that element "//button[@data-testid='toggle-visualizer-btn']" is displayed
# Equalizer is a solid way of checking the playback without listening the music

Scenario: User Creates a Playlist
When I click on the element "//i[@class='fa fa-plus-circle create']"
And I pause for 1000ms
And I click on the element "//li[@data-testid='playlist-context-menu-create-simple']"
And I pause for 1000ms
And I set "aa" to the inputfield "//input[@name='name']"
And I press "Enter"
# This is how you can press an any key on a keyboard
And I pause for 2000ms
Then I expect that element "//a[text()='aa']" is displayed
# Better use a text in this case since you only know that

Scenario: User Adds a Song to a Playlist
Given I open the url "#!/songs"
# Easier way to add a song to the playback is from All Songs page
When I click on the element "//tr[@class='song-item']"
# It is always a first not playing song in this case
And I pause for 1000ms
And I click on the element "//button[@class='btn-add-to']"
And I pause for 2000ms
And I click on the element "//section[@id='songsWrapper']//li[contains(text(), 'aa')]"
# Partial text here since names have extra spaces in the list for some reason
And I pause for 1000ms
And I click on the element "//a[text()='aa']"
And I pause for 1000ms
Then I expect that container "//section[@id='playlistWrapper']//td[@class='title']" contains the text "Ketsa - That_s a Beat"

Scenario: User Removes a Song from a Playlist
Given I click on the element "//a[text()='aa']"
And I pause for 1000ms
When I click on the element "//section[@id='playlistWrapper']//td[@class='title']"
And I pause for 1000ms
And I press "Delete"
# This is a secret way of deleting songs since there are no such buttons anywhere
And I pause for 1000ms
Then I expect that container "//section[@id='playlistWrapper']//div[@class='text']" contains the text "The playlist is currently empty."

Scenario: User Renames the Playlist
When I doubleclick on the element "//a[text()='aa']"
# The easiest way of getting to the rename functionality
And I pause for 1000ms
And I set "bb" to the inputfield "//input[@name='name']"
# To change the name from 'aa' to 'bb'
And I press "Enter"
And I pause for 1000ms
Then I expect that element "//a[text()='bb']" is displayed

Scenario: User Deletes the Playlist
When I click on the element "//button[@class='del btn-delete-playlist']"
And I pause for 6000ms
# It takes a while for those green messages to go away, so the Logout button is clickable
Then I expect that element "//a[text()='bb']" is not displayed
# You can also check for invisibility by adding 'not'

Scenario: User Logout
When I click on the button "//i[@class='fa fa-sign-out']"
And I pause for 2000ms
Then I expect that element "//input[@type='password']" is displayed
# You can check that user is logged out when password field is shown
Scenario: User Renames a Playlist
Given I right click on the element "// section[@id='playlists']/ul[1]/li[3]"
And I click the the option " //li[contains(@data-testid, 'playlist-context-menu-edit')]"
And I clear the inputfield
And I set "a" to the inputfield "// input[@data-testid='inline-playlist-name-input']"
And I press "enter"
Then I expect that the element " //div[@class='success show']" is displayed

Scenario: User Deletes a Playlist
Given I click on the element "// section[@id='playlists']/ul[1]/li[3]"
And I pause for 1000ms
And I click on the button " //button[@class='del btn-delete-playlist']"
Then I expect that the element " //div[@class='success show']" is displayed
Scenario: User Creates a Playlist
Given I click on the element "//i[@class='fa fa-plus-circle create']"
And I pause for 1000ms
And I click on the element "//li[@data-testid='playlist-context-menu-create-simple']"
And I pause for 1000ms
And I set "a" to the inputfield "//input[@name='name']"
And I press "enter"

Scenario: User Adds a Song to a Playlist
Given I open the url "#!/songs"
When I click on the element "//tr[@class='song-item']"
And I pause for 1000ms
And I click on the element "//button[@class='btn-add-to']"
And I pause for 2000ms
And I click on the element "//section[@id='songsWrapper']//li[contains(text(), 'aa')]"
And I pause for 1000ms
And I click on the element "//a[text()='aa']"
And I pause for 1000ms
Then I expect that container "//section[@id='playlistWrapper']//td[@class='title']" contains the text "Ketsa - That_s a Beat"

Scenario: User Removes a Song from a Playlist
Given I click on the element "//a[text()='aa']"
And I pause for 1000ms
When I click on the element "//section[@id='playlistWrapper']//td[@class='title']"
And I pause for 1000ms
And I press "Delete"
And I pause for 1000ms
Then I expect that container "//section[@id='playlistWrapper']//div[@class='text']" contains the text "The playlist is currently empty."
Scenario: User Plays a Song
Given I open the url "#!/home"
And I click on the button "//span[@class='cover']"
And I pause for 2000ms
Then I expect that element "//button[@data-testid='toggle-visualizer-btn']" is displayed
 
Scenario: User Logs Out
When I click on the button "//i[@class='fa fa-sign-out']"
And I pause for 1000ms
Then I expect that element "//input[@type='password']" is displayed
Wait wait = new FluentWait(WebDriver reference);
.withTimeout(timeout, SECONDS);
.pollingEvery(timeout, SECONDS);
.ignoring(Exception.class);
title_is;
title_contains;
presence_of_element_located;
visibility_of_element_located;
visibility_of;
presence_of_all_elements_located;
text_to_be_present_in_element;
text_to_be_present_in_element_value;
frame_to_be_available_and_switch_to_it;
invisibility_of_element_located;
element_to_be_clickable;
staleness_of;
element_to_be_selected;
element_located_to_be_selected;
element_selection_state_to_be;
element_located_selection_state_to_be;
alert_is_present;
WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath( "locator")));
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(60));
@BeforeMethod
@Parameters({"BaseURL"})
public void launchBrowser(String BaseURL) {
  driver = new ChromeDriver();
  driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
  url = BaseURL;
  driver.get(url);
}
<suite name="TestNG">
  <parameter name="BaseURL" value="http://testpro.io/"/>
    <test name="Example Test" preserve-order="false">
      <classes>
         <class name="LoginTests">
         </class>
      </classes>
    </test>
</suite>
public class DP
{
  @DataProvider (name = "data-provider")
  public Object[][] dpMethod(){
    return new Object[][] {{"First-Value"}, {"Second-Value"}};
  }

  @Test (dataProvider = "data-provider")
  public void myTest (String val) {
    System.out.println("Passed Parameter Is : " + val);
  }
}
Feature: Smoke

Scenario: User Login
Given I open the url "/"
When I set "myersjason@me.com" to the inputfield "// input [@type='email']"
And I set "te$t$tudent" to the inputfield "// input [@placeholder='Password']"
And I click on the button "button"
And I pause for 1000ms
Then I expect the url to contain "#!/home"

Scenario: Search
When I add "All" to the inputfield "//input[@type='search']"
And I pause for 1000ms
Then I expect that container "//span[@class='details']" contains the text "Mid-Air Machine - If It_s All I Do"
// While loop to repeatedly call 'something' based on its previous output
int i = 0;
while (i < 10) {
  if (something) {
    i++;
  } else {
    i += 2;
  }
}
int i = 0; // Initializing an integer with a value of 0
while (i < 10) { // While loop to repeat code until i is greater than or equal to 10
  if (something) { // Check if the 'something' method returns true
    i++; // Increase value of i by 1
  } else { // Otherwise if the 'something method' does not return true
    i += 2; // Increase value of i by 2
  }
} // End of while loop
File f;
try {
  f = new File("file.txt");
  // More stuff
} catch (FileNotFoundException e1) {
  System.out.println("That file doesn't exist!");
  f = new File("backupFile.txt");
} catch (SomeOtherException e2) {
  // Handle other exception
}
File f;
try {
  f = new File("file.txt")
  // More stuff
} catch (Exception e) {
  e.printStackTrace();
}
public class Stuff {
  int i = 1;

  public void nonStaticMethod() {
    // do something
  }
}
public class StaticStuff {
  static int i = 1;

  public static void staticMethod() {
    // do something
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Practice Suite">
  <test name="Test Basics 1">
      <parameter name="emailid" value="tester456@gmail.com"/>
      <parameter name="password" value="test@123"/>
      <classes>
      <class name="practiceTests.testParameters"/>
      </classes>
  </test> <!-- Test --> 
   
  <test name="Test Basics 2">    
    <parameter name="emailid" value="tester789@gmail.com"/>
    <classes>
       <class name="practiceTests.testOptional"/>
    </classes>
     
  </test> <!-- Test -->
</suite> <!-- Suite -->
<classes>
<class name="LogInTests">
<method name="logInTestsValidCredentials"/>
</class>
<class name="UserProfileTests">
<method name="updateUsersName"/>
</class>
<class name="HomeTests">
<method name="addSongToFavorites"/>
</class>
</classes>
<classes>
<class name="LogInTests"/>
<class name="UserProfileTests"/>
<class name="HomeTests"/>
</classes>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="TestNG">

    <test name="Example Test" preserve-order="false">
        <classes>
            <class name="LoginTests"/>
            <class name="BaseTest"/>
            <class name="RegistrationTests"/>
        </classes>
    </test>
</suite>
@Test
public static void RegistrationSuccessTest () {

  WebDriver driver = new ChromeDriver();
  driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

  String url = "https://bbb.testpro.io/";
  driver.get(url);
  Assert.assertEquals(driver.getCurrentUrl(), url);
  driver.quit();
}
StringBuilder result = new StringBuilder();
for (char character : message.toCharArray()) {
    if (character != ' ') {
        int originalAlphabetPosition = character - 'a';
        int newAlphabetPosition = (originalAlphabetPosition + offset) % 26;
        char newCharacter = (char) ('a' + newAlphabetPosition);
        result.append(newCharacter);
    } else {
        result.append(character);
    }
}
return result;
Copy
After the Ethereum Merge Event, Ethereum has become more admired in the crypto industry. Meantime, the price of ethereum has skyrocketed. Do you wanna create an ethereum standard token? https://bit.ly/3TlCuwx 

Being the trusted Ethereum Token Development Company that rendering excellent Token Development Services on multiple ethereum standards such as ERC20, ERC1155, ERC223, ERC721, ERC777, ERC827, ERC 998, and ERC1400 to enhance your tokenomics business and platform.

For Instant Connect, 
Whatsapp +91 9384587998 || Telegram @maticzofficial

// Initialize a Scanner
static Scanner s = new Scanner(System.in);

public static void main(String[] args) {
  System.out.println("Enter a number");
  printForUser("foo");

  System.out.println("Enter another number");
  printForUser("foo2");
  
  System.out.println("Enter yet another number");
  printForUser("foo3");
}
public static void printForUser(String printedText) {
  // Store a number from user input
  int n = s.nextInt();
  
  // Print the text for the amount stored
  for (int i = 0; i < n; i++) {
    System.out.println(printedText);
  }
}
// Initialize a Scanner
static Scanner s = new Scanner(System.in);

public static void main(String[] args) {
  System.out.println("Enter a number");
  printForUser("foo");

  System.out.println("Enter another number");
  printForUser("foo2");
}
public static void printForUser(String printedText) {
  // Store a number from user input
  int n = s.nextInt();
  
  // Print the text for the amount stored
  for (int i = 0; i < n; i++) {
    System.out.println(printedText);
  }
}
// Initialize a Scanner
static Scanner s = new Scanner(System.in);

public static void main(String[] args) {
  // Store a number from user input
  System.out.println("Enter a number")
  int firstNum = s.nextInt();
  // Print "foo" for the amount stored
  for (int i = 0; i < firstNum; i++) {
    System.out.println("foo");
  }

  // Store another number from user input
  System.out.println("Enter another number")
  int secondNum = s.nextInt();
  // Print "foo2" for the amount stored
  for (int i = 0; i < secondNum; i++) {
    System.out.println("foo2");
  }

  // Store yet another number from user input
  System.out.println("Enter yet another number")
  int thirdNum = s.nextInt();
  // Print "foo3" for the amount stored
  for (int i = 0; i < thirdNum; i++) {
    System.out.println("foo3");
  }
}
// Initialize a JLabel for the title
String titleText = "Title";
JLabel titleLabel = new JLabel();
titleLabel.setText(titleText);
// Initialize a JLabel for the title
JLabel titleLabel = new JLabel("Title");
package snippets.collecectionApis;

import java.util.HashMap;

public class Maps {

  public static void main(String[] args) {

    // {key:value, key2:value2 ...}

    // France: Paris
    // Italy: Rome
    // Norway: Oslo
    // US: Washington DC

    HashMap<String, String> countryCapitals = new HashMap<>();
    countryCapitals.put("France","Paris");
    countryCapitals.put("Italy", "Rome");
    countryCapitals.put("Norway", "Oslo");
    countryCapitals.put("US", "Washington DC");
    countryCapitals.remove("Italy");

    HashMap<Integer, String> capitals = new HashMap<>();
    capitals.put(1,"Paris");
    capitals.put(2, "Rome");
    capitals.put(3, "Oslo");
    capitals.put(4, "Washington DC");

    System.out.println(capitals.get(3));
  }
}
package snippets.collecectionApis;

import java.util.HashMap;

public class Maps {

  public static void main(String[] args) {

    // {key:value, key2:value2 ...}

    // France: Paris
    // Italy: Rome
    // Norway: Oslo
    // US: Washington DC

    HashMap<String, String> countryCapitals = new HashMap<>();
    countryCapitals.put("France","Paris");
    countryCapitals.put("Italy", "Rome");
    countryCapitals.put("Norway", "Oslo");
    countryCapitals.put("US", "Washington DC");
    countryCapitals.remove("Italy");

    System.out.println( countryCapitals.values());
  }
}
package snippets.collecectionApis;

import java.util.HashMap;

public class Maps {

  public static void main(String[] args) {

    // {key:value, key2:value2 ...}

    // France: Paris
    // Italy: Rome
    // Norway: Oslo
    // US: Washington DC

    HashMap<String, String> countryCapitals = new HashMap<>();
    countryCapitals.put("France","Paris");
    countryCapitals.put("Italy", "Rome");
    countryCapitals.put("Norway", "Oslo");
    countryCapitals.put("US", "Washington DC");

    System.out.println( countryCapitals.get("Italy"));
  }
}
import java.util.*;

public class SetsDemo {

  public static void main(String[] args) {

    Set<String> uniqueKoelPages = new TreeSet<>();

    uniqueKoelPages.add("LoginPage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("ProfilePage");
    uniqueKoelPages.add("AProfilePage");

    System.out.println(uniqueKoelPages);

    Set<Integer> set1 = new HashSet<>();
    set1.add(1);
    set1.add(3);
    set1.add(2);
    set1.add(4);
    set1.add(8);
    set1.add(9);
    set1.add(0);

    Set<Integer> set2 = new HashSet<>();
    set2.add(1);
    set2.add(3);
    set2.add(7);
    set2.add(5);
    set2.add(4);
    set2.add(0);
    set2.add(7);
    set2.add(5);

    // Union
    Set<Integer> set3 = new HashSet<>(set1);
    set3.addAll(set2);
    System.out.println(set3);

    // intersection
    Set<Integer> setIntersection = new HashSet<>(set1);
    setIntersection.retainAll(set2);
    System.out.println(setIntersection);

    // Differences
    Set<Integer> setDifference = new HashSet<>(set1);
    setDifference.removeAll(set2);
    System.out.println(setDifference);

  }
}
import java.util.*;

public class SetsDemo {

  public static void main(String[] args) {

    Set<String> uniqueKoelPages = new TreeSet<>();

    uniqueKoelPages.add("LoginPage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("ProfilePage");
    uniqueKoelPages.add("AProfilePage");

    System.out.println(uniqueKoelPages);

    Set<Integer> set1 = new HashSet<>();
    set1.add(1);
    set1.add(3);
    set1.add(2);
    set1.add(4);
    set1.add(8);
    set1.add(9);
    set1.add(0);

    Set<Integer> set2 = new HashSet<>();
    set2.add(1);
    set2.add(3);
    set2.add(7);
    set2.add(5);
    set2.add(4);
    set2.add(0);
    set2.add(7);
    set2.add(5);

    // Union
    Set<Integer> set3 = new HashSet<>(set1);
    set3.addAll(set2);
    System.out.println(set3);

    // intersection
    Set<Integer> setIntersection = new HashSet<>(set1);
    setIntersection.retainAll(set2);
    System.out.println(setIntersection);
  }
}
import java.util.*;

public class SetsDemo {

  public static void main(String[] args) {

    Set<String> uniqueKoelPages = new TreeSet<>();

    uniqueKoelPages.add("LoginPage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("ProfilePage");
    uniqueKoelPages.add("AProfilePage");

    System.out.println(uniqueKoelPages);

    Set<Integer> set1 = new HashSet<>();
    set1.add(1);
    set1.add(3);
    set1.add(2);
    set1.add(4);
    set1.add(8);
    set1.add(9);
    set1.add(0);

    Set<Integer> set2 = new HashSet<>();
    set2.add(1);
    set2.add(3);
    set2.add(7);
    set2.add(5);
    set2.add(4);
    set2.add(0);
    set2.add(7);
    set2.add(5);

    // Union
    Set<Integer> set3 = new HashSet<>(set1);
    set3.addAll(set2);
    System.out.println(set3);
  }
}
import java.util.*;

public class SetsDemo {

  public static void main(String[] args) {

    Set<String> uniqueKoelPages = new TreeSet<>();

    uniqueKoelPages.add("LoginPage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("ProfilePage");
    uniqueKoelPages.add("AProfilePage");

    System.out.println(uniqueKoelPages);
  }
}
import java.util.*;

public class SetsDemo {

  public static void main(String[] args) {

    Set<String> uniqueKoelPages = new TreeSet<>();

    uniqueKoelPages.add("LoginPage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("HomePage");
    uniqueKoelPages.add("ProfilePage");
    uniqueKoelPages.add("AProfilePage");

    System.out.println(uniqueKoelPages);
  }
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListsDemo {

  public static void main(String[] args) {


    List<String> koelPages = new ArrayList<>();

    koelPages.add("LoginPage");
    koelPages.set(0, "RegistrationPage");
    koelPages.add("HomePage");
    koelPages.add("ProfilePage");
    koelPages.add("APage");
    koelPages.add("ZPage");
    Collections.sort(koelPages);
    Collections.reverse(koelPages);

    for(String i: koelPages) {
      System.out.println(koelPages);
    }
  }
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListsDemo {

  public static void main(String[] args) {


    List<String> koelPages = new ArrayList<>();

    koelPages.add("LoginPage");
    koelPages.set(0, "RegistrationPage");
    koelPages.add("HomePage");
    koelPages.add("ProfilePage");
    koelPages.add("APage");
    koelPages.add("ZPage");
    Collections.sort(koelPages);
    Collections.reverse(koelPages);

    System.out.println(koelPages);
  }
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListsDemo {

  public static void main(String[] args) {


    List<String> koelPages = new ArrayList<>();

    koelPages.add("LoginPage");
    koelPages.set(0, "RegistrationPage");
    koelPages.add("HomePage");
    koelPages.add("ProfilePage");
    koelPages.add("APage");
    koelPages.add("ZPage");
    Collections.sort(koelPages);
    koelPages.remove(0);

    System.out.println(koelPages);
  }
}
import java.util.ArrayList;
import java.util.List;

public class ListsDemo {

  public static void main(String[] args) {


    List<String> koelPages = new ArrayList<>();

    koelPages.add("LoginPage");
    koelPages.set(0, "RegistrationPage");
    koelPages.add("HomePage");
    koelPages.remove( index 0);

    System.out.println(koelPages);

  }
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListsDemo {

  public static void main(String[] args) {

    String[] arrayExample = {"BMW", "Mercedes", "Tesla"};

    List<String> koelPages = new ArrayList<>();

    koelPages.add("LoginPage");
    koelPages.set(0, "RegistrationPage");
    koelPages.add("HomePage");

    System.out.println(koelPages);

  }
}
package snippets.interfaces;

public class InterfacesDemo {


  public static void main(String[] args) {
    ChromeBrowser chrome = new ChromeBrowser();
    chrome.openDefaultHomePage();
  }
}

// WebBrowser
// Chrome Browser
// IE11 browser

interface WebBrowser {
  public String getBrowserName();
  public void openDefaultHomePage();

}

interface BrowserNavigation {
  public void navigateToPage();
  public void goBack();

}

class ChromeBrowser implements WebBrowser, BrowserNavigation {

  String browserName = "chrome";

public String getBrowserName() {
  return browserName;
}

public void openDefaultHomePage() {
  System.out.println("google.com");
}

public void navigateToPage() {

}
public void goBack() {

}

}
package snippets.abstractionClass;

class AbstractionDemo {
  public static void main(String[] args) {
    ChromeBrowser chrome = new ChromeBrowser();
    chrome.openDefaultHomePage();

  }
}

abstract class WebBrowser {
  // regular method
  // abstract methods

  public void openPage(String pageUrl) {
    System.out.println(pageUrl + " is opened");
  }

  abstract public String getBrowserName();
  abstract public void openDefaultHomePage();

}

class ChromeBrowser extends WebBrowser {

  String browserName = "chrome";

public String getBrowserName() {
  return browserName;
}

public void openDefaultHomePage() {
  System.out.println("google.com");
}

}

class IE11Browser extends WebBrowser {

  String browserName = "IE11";

public String getBrowserName() {
  return browserName;
}

public void openDefaultHomePage() {
  System.out.println("microsoft.com");
}
}
public class Car {

  public void drive( int miles) {
    System.out.println("car drove " + miles + " miles");
    odometer = odometer + miles;
  }

  public String returnCarModel() {
    return "car model is unknown";

  }
}
public class Wrangler extends Car {

  boolean carDoors = true; 

public void takeOffDoors() {
  carDoors = false;
  System.out.println("Doors are taken off");

}

public void putBackDoors() {
  carDoors = true;
  System.out.println("Doors are back");

}

public String returnCarModel() {
  return "car model is Wrangler";

}
}
public class ModelX extends Car {

  boolean autopilot = false;

public void drive switchAutopilotOn() {
  autoPilot = true;
  System.out.println("Autopilot is switched on");
}

public void drive switchAutopilotOff() {
  autoPilot = false;
  System.out.println("Autopilot is switched off");
}

public String returnCarModel() {
  return "car model is Modelx";
}
}
public class Main {

  public static void main(String[] args) {

    Wrangler myWraglerCar = new Wrangler();
    myWranglerCar.drive( miles: 100);
    System.out.println(myWranglerCar.odometer);
    myWranglerCar.takeOffDoors();
    System.out.println(myWranglerCar.returnCarModel());

    ModelX myModelXCar = new ModelX();
    myModelXCar.drive( miles: 90);
    System.out.println(myModelXCar.odometer);
    myModelXCar.switchAutopilotOn();
    System.out.println(myModelXCar.returnCarModel());


    Car myCar = new Car();
    myCar.drive( miles: 50);
    System.out.println(myCar.returnCarModel());

  }
}
public class Car {

   public void drive( int miles) {
             System.out.println("car drove " + miles + " miles");
             odometer = odometer + miles;
   }
}
public class Wrangler {

  int odometer = 0;
boolean carDoors = true; 

public void drive( int miles) {
  System.out.println("car drove " + miles + " miles");
  odometer = odometer + miles;

}

public void takeOffDoors() {
  carDoors = false;
  System.out.println("Doors are taken off");

}

public void putBackDoors() {
  carDoors = true;
  System.out.println("Doors are back");

}
}
public class ModelX {
      int odometer = 0;
      boolean autopilot = false;

      public void drive( int miles) {
             System.out.println("car drove " + miles + " miles");
             odometer = odometer + miles;
}

      public void drive switchAutopilotOn() {
             autoPilot = true;
             System.out.println("Autopilot is switched on");
}

  public void drive switchAutopilotOff() {
             autoPilot = false;
             System.out.println("Autopilot is switched off");
  }
}
public class Main {

  public static void main(String[] args) {

    Wrangler myWraglerCar = new Wrangler();
    myWranglerCar.drive( miles: 100);
    System.out.println(myWranglerCar.odometer);
    myWranglerCar.takeOffDoors();

    ModelX myModelXCar = new ModelX();
    myModelXCar.drive( miles: 90);
    System.out.println(myModelXCar.odometer);
    myModelXCar.switchAutopilotOn();

    Car myCare = new Car();
    myCar.drive( miles: 50);

  }
}
public class Main {

  public static void main (String[] args) {

    Cars azatCar = new Cars();
    azatCar.brand = "Mazda" ;
    azatCar.year = 2005 ;
    azatCar.color = "blue" ;

    Cars someOtherCar = new Cars () ;
    someOtherCar.color = "black" ;
    someOtherCar.year = 2020 ;
    someOtherCar.brand = "BMW" ;

    System.out.println(azatCar.brand);

  }
}
public void accelerate() {
     System.out.println("car is accelerating");
  }

public void headlightsOn() {
      System.out.println("car's headlights is on");
  }

public void headlightsOff() {
      System.out.println("car's headlights is off");
  }

public int return0dometer(int odometerValue) {
      return 10000; 
  }
public class Main {

  public static void main (String[] args) {

    Cars azatCar = new Cars(carBrand:"Mazda", carColor:"blue", carYear :2005);
    azatCar.brand = "Mazda" ;
    azatCar.year = 2005 ;
    azatCar.color = "blue" ;

    Cars someOtherCar = new Cars (carBrand:"BMW", carcolor: "black") ;
    someOtherCar.color = "black" ;
    someOtherCar.year = 2020 ;
    someOtherCar.brand = "BMW" ;

    System.out.println(someOtherCar.brand);
    azatCar.accelerate() ;
    azatCar.headlightsOn() ;
    azatCar.headlightsOff() ;
    System.out.println ("odometer is equal to" + azatCar.returnOdometer(100000) + "miles");

  }
}
public class Cars {
  3 usages
  String brand ;

  3 usages
  String color ;

  3 usages
  int year ;

  2 usages 2 related problems
  public Cars (String carBrand, String carColor, int carYear) {
    brand = carBrand;
    color = carColor; 
    year

  }

  public void accelerate() {
    System.out.println("car is accelerating");
  }

  public void headlightsOn() {
    System.out.println("car's headlights is on");
  }

  public void headlightsOff() {
    System.out.println("car's headlights is off");
  }
}
class Geek {
  public static String geekName = "";

  public static void geek(String name) {
    geekName = name;
  }
}
class Geek{    
  public static String geekName = "";
public static void geek(String name){
  geekName = name;
}
}
class GFG {
  public static void main (String[] args) {

    // Accessing the static method geek() and 
    // field by class name itself.
    Geek.geek("vaibhav"); 
    System.out.println(Geek.geekName);

    // Accessing the static method geek() by using Object's reference.
    Geek obj = new Geek();
    obj.geek("mohit");
    System.out.println(obj.geekName);
  }
}
class Geek {
  public static String geekName = "";

  public static void geek(String name) {
    geekName = name;
  }
}
import java.util.*;

class sample {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int x = 1;

    do {
      try {
        System.out.println("Enter first num: ");
        int n1 = input.nextInt();
        System.out.println("Enter first num: ");
        int n2 = input.nextInt();
        int sum = n1 / n2;
        System.out.println(sum);
        x = 2;

      } catch (Exception e) {
        System.out.println("You cant do that");
      }
    } while (x == 1);
  }
}
class Main {
  public static void main(String[] args) {

    // Write a simple application using nested loops to print out a Multiplication Table 1-12x
    
    // Example:
    // 1 2 3 4 5 6 7 8 9 10 11 12 
    // 2 4 6 8 10 12 14 16 18 20 22 24 
    // 3 6 9 12 15 18 21 24 27 30 33 36 
    // 4 8 12 16 20 24 28 32 36 40 44 48 
    // 5 10 15 20 25 30 35 40 45 50 55 60 
    // 6 12 18 24 30 36 42 48 54 60 66 72 
    // 7 14 21 28 35 42 49 56 63 70 77 84 
    // 8 16 24 32 40 48 56 64 72 80 88 96 
    // 9 18 27 36 45 54 63 72 81 90 99 108 
    // 10 20 30 40 50 60 70 80 90 100 110 120 
    // 11 22 33 44 55 66 77 88 99 110 121 132 
    // 12 24 36 48 60 72 84 96 108 120 132 144 

    // Hints:
    // - Start with the first loop
    // - To print numbers in one line use System.out.print(variable) method
    // - To break the line and start a new one - use System.out.println() without any parameters
    System.out.println("Assignment #1");

    // Check the output and submit your homework by clicking 'Submit' button at top right
  }
}
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
class Pair{
    public int first;  
    public int second; 
    public Pair(int first, int second){
        this.first = first;
        this.second = second;
    }
}
package com.sunmi.printerhelper.utils;

import android.content.Context;
import android.os.RemoteException;
import android.util.Log;

import com.sunmi.peripheral.printer.ExceptionConst;
import com.sunmi.peripheral.printer.InnerPrinterCallback;
import com.sunmi.peripheral.printer.InnerPrinterException;
import com.sunmi.peripheral.printer.InnerPrinterManager;
import com.sunmi.peripheral.printer.SunmiPrinterService;
import com.sunmi.peripheral.printer.WoyouConsts;

/**
 * @author M. Ali Biag
 * @since create at Wednesday, August 10, 2022
 */
public class SunmiPrinter {
    public static String TAG = "SunmiPrinter";

    public enum ALIGNMENT {LEFT, CENTER, RIGHT}

    private static final SunmiPrinter printer = new SunmiPrinter();

    private SunmiPrinter() {
    }

    public static SunmiPrinter instance() {
        return printer;
    }

    /**
     * SunmiPrinterService  is an interface
     * It contain all the Printer API (Functionalities)
     * <p>
     * InnerPrinterCallback gives us the implementation of
     * SunmiPrinterService interface
     */
    private SunmiPrinterService sunmiPrinterService;
    private final InnerPrinterCallback innerPrinterCallback = new InnerPrinterCallback() {
        @Override
        protected void onConnected(SunmiPrinterService service) {
            sunmiPrinterService = service;
        }

        @Override
        protected void onDisconnected() {
            sunmiPrinterService = null;
        }
    };

    /**
     * Check {@link ExceptionConst}
     */
    private void handleRemoteException(RemoteException e) {
        Log.e(TAG, "ERROR FROM SUNMI PRINTER CUSTOM IMPLEMENTATION: " + e.getMessage());
    }


    /**
     * Establish link with Sunmi Printer.
     * NOTE:
     * If you do not call this method then
     * SunmiPrinterService will be null
     * and you will not be able to access any
     * functionality of printer
     */
    public void connectWithSunmiPrinter(Context context) {
        try {
            boolean ret = InnerPrinterManager.getInstance().bindService(context,
                    innerPrinterCallback);
            if (!ret) {
                // Connection not established
            }
        } catch (InnerPrinterException e) {
            e.printStackTrace();
        }
    }

    /**
     * Disconnect from Sunmi printer from device
     * and release resources
     */
    public void disconnectFromSunmiPrinter(Context context) {
        try {
            if (sunmiPrinterService != null) {
                InnerPrinterManager.getInstance().unBindService(context, innerPrinterCallback);
                sunmiPrinterService = null;
            }
        } catch (InnerPrinterException e) {
            e.printStackTrace();
        }
    }

    /**
     * All style settings will be restored to default
     */
    public void setPrinterToDefaultStyle() {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }
        try {
            sunmiPrinterService.printerInit(null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * send esc cmd
     */
    public void sendRawData(byte[] data) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter();
            return;
        }
        try {
            sunmiPrinterService.sendRAWData(data, null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * Set printer alignment
     */
    public void setAlignment(ALIGNMENT align) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }
        try {
            sunmiPrinterService.setAlignment(align.ordinal(), null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    public void setFontSize(float fontSize) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }
        try {
            sunmiPrinterService.setFontSize(fontSize, null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * @param text text you want to print
     */
    public void printText(String text) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            sunmiPrinterService.printText(text, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param boldText After printing given text bold feature will be off.
     */
    public void printTextBold(String boldText) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            sunmiPrinterService.sendRAWData(ESCUtil.boldOn(), null);
            sunmiPrinterService.printText(boldText, null);
            sunmiPrinterService.sendRAWData(ESCUtil.boldOff(), null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void printTextInCenter(String centerText) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            sunmiPrinterService.setAlignment(ALIGNMENT.CENTER.ordinal(), null);
            sunmiPrinterService.printText(centerText, null);
            sunmiPrinterService.setAlignment(ALIGNMENT.LEFT.ordinal(), null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param leftText  will be Left Align
     * @param rightText will be Right Align
     */
    public void printTextLeftRight(String leftText, String rightText) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        String[] txts = new String[]{leftText, rightText};
        int[] width = new int[]{1, 1};
        int[] align = new int[]{0, 2};

        try {
            sunmiPrinterService.printColumnsString(txts, width, align, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void printTextFontSize(String text, float fontSize) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            sunmiPrinterService.printTextWithFont(text, null, fontSize, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void printOneLine() {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            sunmiPrinterService.lineWrap(1, null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * paper feed three lines
     * Not disabled when line spacing is set to 0
     */
    public void print3Line() {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            sunmiPrinterService.lineWrap(3, null);
        } catch (RemoteException e) {
            handleRemoteException(e);
        }
    }

    /**
     * Print dashes on one complete line
     * Handle both 58mm and 80mm paper
     */
    public void dashesPlusNextLine() {
        try {
            int paper = sunmiPrinterService.getPrinterPaper();
            if (paper == 1) {
                // 32 Dashes = 58mm
                sunmiPrinterService.printText("--------------------------------\n", null);
            } else {
                // 48 Dashes = 80mm
                sunmiPrinterService.printText("------------------------------------------------\n",
                        null);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public String getPaperSize() {
        String result = "Unknown";
        try {
            int paper = sunmiPrinterService.getPrinterPaper();
            if (paper == 1) {
                result = "58mm";
            } else {
                result = "80mm";
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * print Qr Code
     */
    public void printQr(String data, int modulesize, int errorlevel) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            sunmiPrinterService.printQRCode(data, modulesize, errorlevel, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    /**
     * print text
     * setPrinterStyle:Api require V4.2.22 or later, So use esc cmd instead when not supported
     * More settings reference documentation {@link WoyouConsts}
     * printTextWithFont:
     * Custom fonts require V4.14.0 or later!
     * You can put the custom font in the 'assets' directory and Specify the font name parameters
     * in the Api.
     */
    public void printText(String content, float size, boolean isBold, boolean isUnderLine,
                          String typeface) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return;
        }

        try {
            try {
                sunmiPrinterService.setPrinterStyle(WoyouConsts.ENABLE_BOLD, isBold ?
                        WoyouConsts.ENABLE : WoyouConsts.DISABLE);
            } catch (RemoteException e) {
                if (isBold) {
                    sunmiPrinterService.sendRAWData(ESCUtil.boldOn(), null);
                } else {
                    sunmiPrinterService.sendRAWData(ESCUtil.boldOff(), null);
                }
            }
            try {
                sunmiPrinterService.setPrinterStyle(WoyouConsts.ENABLE_UNDERLINE, isUnderLine ?
                        WoyouConsts.ENABLE : WoyouConsts.DISABLE);
            } catch (RemoteException e) {
                if (isUnderLine) {
                    sunmiPrinterService.sendRAWData(ESCUtil.underlineWithOneDotWidthOn(), null);
                } else {
                    sunmiPrinterService.sendRAWData(ESCUtil.underlineOff(), null);
                }
            }
            sunmiPrinterService.printTextWithFont(content, typeface, size, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }


    public boolean doesPrinterExist(Context context) {
        if (sunmiPrinterService == null) {
            // disconnectFromSunmiPrinter()
            return false;
        }
        boolean result = false;
        try {
            int code = sunmiPrinterService.updatePrinterState();
            if (code > 0 && code < 505) {
                // "Printer exist"
                result = true;
            } else {
                // "Printer does not exist"
                result = false;
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }

        return result;
    }
}
package com.sunmi.printerhelper.activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.sunmi.peripheral.printer.SunmiPrinterService;
import com.sunmi.printerhelper.R;
import com.sunmi.printerhelper.utils.BluetoothUtil;
import com.sunmi.printerhelper.utils.SunmiPrinter;

public class SimpleActivity extends BaseActivity implements View.OnClickListener {
    SunmiPrinterService sunmiPrinter;
    SunmiPrinter printer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        printer = SunmiPrinter.instance();
        printer.connectWithSunmiPrinter(this);

        setContentView(R.layout.activity_simple);
        setMyTitle("Simple Activity");


        TextView printerInfoTV = findViewById(R.id.tv_yes);
        TextView paperTV = findViewById(R.id.tv_paper);

        boolean res = printer.doesPrinterExist(this);
        String paperSize =  printer.getPaperSize();

        if(res) printerInfoTV.setText("YES"); else printerInfoTV.setText("NO");
        paperTV.setText(paperSize);

        checkAfter2000m();

        Button simpleBut = findViewById(R.id.btn_simple);
        Button exampleBut = findViewById(R.id.btn_example);
        Button reportBut = findViewById(R.id.btn_report);

        simpleBut.setOnClickListener(this);
        exampleBut.setOnClickListener(this);
        reportBut.setOnClickListener(this);

    }

    private void setPrinterInfo(){
        TextView printerInfoTV = findViewById(R.id.tv_yes_2);
        TextView paperTV = findViewById(R.id.tv_paper_2);

        boolean res = printer.doesPrinterExist(this);
        String paperSize =  printer.getPaperSize();

        if(res) printerInfoTV.setText("YES"); else printerInfoTV.setText("NO");
        paperTV.setText(paperSize);
    }

    private void checkAfter2000m() {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                setPrinterInfo();
            }
        }, 2000);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_simple:
                Toast.makeText(this, "Print Simple Example Clicked ", Toast.LENGTH_SHORT).show();
                onSimpleButtonClicked();
                break;
            case R.id.btn_example:
                Toast.makeText(this, "Print Complex Example Clicked", Toast.LENGTH_LONG).show();
                // onComplexButtonClicked();
                break;
            case R.id.btn_report:
                Toast.makeText(this, "Print Simply Report Clicked ", Toast.LENGTH_SHORT).show();
                // onSimplyReportButtonClicked();
                break;
        }

    }


    public void onSimpleButtonClicked() {
        if (sunmiPrinter == null) {
            Toast.makeText(this, "SunmiPrinter is Null SIMPLE BUTTON!!!!", Toast.LENGTH_SHORT).show();
            return;
        }

        Toast.makeText(this, "SunmiPrinter is NOT null!!!", Toast.LENGTH_SHORT).show();

        printer.printText("Start of Sample");
        printer.printTextLeftRight("LEFT", "RIGHT");
        printer.printText("Alignment should be normal");

        printer.printTextInCenter("CENTER\n");
        printer.printText("Alignment should be normal\n");

        // sunmiPrinter.sendRAWData(ESCUtil.boldOn(), null);
        // sunmiPrinter.printText("Bold Feature is ON\n", null);
        // sunmiPrinter.sendRAWData(ESCUtil.boldOff(), null);
        printer.printTextBold("This Text Should be bold!!!\n");
        printer.printText("Text should not be bold\n");


        printer.dashesPlusNextLine();
        printer.printText("This is default Font Size\n");
        printer.setFontSize(16f);
        printer.printText("This is 16 Font Size\n");
        printer.setFontSize(32f);
        printer.printText("This is 32 Font Size\n");
        printer.setFontSize(16f);
        printer.printText("This is again 16 Font Size\n");

        printer.dashesPlusNextLine();
        printer.printTextFontSize("Font Size is increased to 30\n", 30f);
        printer.printText("Does Font Size return to normal\n");
        printer.setFontSize(16f);
        printer.printText("Font Size must be normal\n");
        printer.dashesPlusNextLine();

        //sunmiPrinter.printText("FONT size is increased to 40\n", null);
        //sunmiPrinter.printTextWithFont("ITEM:           MEET", null, 40, null);
        //sunmiPrinter.printTextWithFont("PRICE:          $59\b", null, 40, null);
        //sunmiPrinter.setFontSize(36, null);

        printer.setAlignment(SunmiPrinter.ALIGNMENT.CENTER);
        printer.printTextFontSize("END OF PRINT", 40f);
        printer.setAlignment(SunmiPrinter.ALIGNMENT.LEFT);
        printer.print3Line();

    }

    private void onComplexButtonClicked() {
        if (!BluetoothUtil.isBlueToothPrinter) {
            // SunmiPrinter.instance().printExample(this);
        } else {
            Toast.makeText(this, "Is Bluetooth is on ???", Toast.LENGTH_SHORT).show();
        }
    }

    /*private void onSimplyReportButtonClicked() {
        if (sunmiPrinter == null) {
            Toast.makeText(this, "SunmiPrinter is Null REPORT!!!!", Toast.LENGTH_SHORT).show();
            return;
        }

        String transactionsLabel = "Transaction";
        String turnoverLabel = "TurnOver";
        String netSaleLabel = "NetSale";
        String salesVatLabel = "Sales VAT";
        String returnsLabel = "Returns";
        String returnsVatLabel = "Returns VAT";

        String str_breakdown_by_payment_type = "Breakdown by payment type";
        String str_sales_totals_by_department = "Sales totals by department";
        String str_total_sales = "Total sales:";
        String str_net_sales = "Net sales:";
        String str_vat_ = "VAT:";
        String str_breakdown_by_vat_rate = "Breakdown by VAT Rate";
        String str_breakdown_by_invoice_type = "Break down by Invoice type";

        try {
            sunmiPrinter.printerInit(null);

            Toast.makeText(this, "TRY BLOCK REPORT!!!!", Toast.LENGTH_SHORT).show();

            // itemsString.append("[C]<font size='tall'>Report</font>").append("\n");
            // itemsString.append(getLineSeparator()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_CENTER, null);
            sunmiPrinter.printTextWithFont("Report\n", null, 40, null);

            sunmiPrinter.setFontSize(30, null);
            sunmiPrinter.printText(getLineSeparator() + "\n", null);

            // itemsString.append("[L]Date From").append("[R]" + invoiceReport.getDateFrom()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText("Date From", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText("Monday, August 8, 2022\n", null);


            // itemsString.append("[L]Date To").append("[R]" + invoiceReport.getDateTo()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText("Date To", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText("Monday, August 8, 2022\n", null);

            // itemsString.append(getLineSeparator()).append("\n");
            // itemsString.append("\n");
            sunmiPrinter.printText(getLineSeparator() + "\n\n", null);

            // itemsString.append("[L]<b>" + "Total" + "</b>").append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.sendRAWData(ESCUtil.boldOn(), null);
            sunmiPrinter.printText("Total", null);
            sunmiPrinter.sendRAWData(ESCUtil.boldOff(), null);

            // itemsString.append("[L]" + transactionsLabel + "").append("[R]" + invoiceReport.getTransactions()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText(" " + transactionsLabel + " ", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText(" " + transactionsLabel + " \n", null);

            // itemsString.append("[L]" + turnoverLabel + "").append("[R]" + invoiceReport.getTurnOver()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText(" " + turnoverLabel + " ", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText(" " + turnoverLabel + " \n", null);

            // itemsString.append("[L]" + netSaleLabel + "").append("[R]" + invoiceReport.getNetSales()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText(" " + netSaleLabel + " ", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText(" " + netSaleLabel + " \n", null);


            String txts[] = new String[]{salesVatLabel, salesVatLabel + "\n"};
            int width[] = new int[]{1, 1};
            int align[] = new int[]{0, 2};
            sunmiPrinter.printColumnsString(txts, width, align, null);
            // itemsString.append("[L]" + salesVatLabel + "").append("[R]" + invoiceReport.getSalesVAT()).append("\n");


            // itemsString.append("[L]" + returnsLabel + "").append("[R]" + invoiceReport.getReturns()).append("\n");
            String txts2[] = new String[]{returnsLabel, returnsLabel + "\n"};
            sunmiPrinter.printColumnsString(txts2, width, align, null);

            // itemsString.append("[L]" + returnsVatLabel + "").append("[R]" + invoiceReport.getReturnVAT()).append("\n");
            // itemsString.append("\n");
            String txts3[] = new String[]{returnsVatLabel, returnsVatLabel + "\n"};
            sunmiPrinter.printColumnsString(txts3, width, align, null);

            // itemsString.append(getLineSeparator()).append("\n");
            // itemsString.append("[C]").append("End of Report").append("\n");
            // itemsString.append(getLineSeparator()).append("\n");

            sunmiPrinter.printText(getLineSeparator() + "\n", null);
            sunmiPrinter.setAlignment(ALIGN_CENTER, null);
            sunmiPrinter.printText("End of Report\n", null);

            SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy HH:mm");
            String currentDateandTime = sdf.format(new Date());

            //itemsString.append("[L]" + "Printed on:" + "").append("[R]" + currentDateandTime).append("\n");
            String txts4[] = new String[]{"Printed on:", currentDateandTime + "\n"};
            sunmiPrinter.printColumnsString(txts4, width, align, null);


            // itemsString.append("\n");
            // itemsString.append("\n");
            // itemsString.append("\n");

            sunmiPrinter.lineWrap(3, null);

        } catch (RemoteException e) {
            Toast.makeText(this, "CATCH BLOCK REPORT!!!!", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

    }*/

    public static String getLineSeparator() {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            str.append("-");
        }
        return str.toString();
    }

    /*public void otherWayOfGettingSunmiPrinterService(){
        try {
            boolean result = InnerPrinterManager.getInstance().bindService(this, new InnerPrinterCallback() {
                @Override
                protected void onConnected(SunmiPrinterService service) {
                    Toast.makeText(SimpleActivity.this, "Printer Connected", Toast.LENGTH_SHORT).show();
                    sunmiPrinter = service;
                }

                @Override
                protected void onDisconnected() {

                }
            });
            Log.e("SUNMIDEMO", "Result" + result);
        } catch (InnerPrinterException e) {
            e.printStackTrace();
        }
    }*/

}

package com.sunmi.printerhelper.activity;

import android.content.ComponentName;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.sunmi.peripheral.printer.InnerPrinterCallback;
import com.sunmi.peripheral.printer.InnerPrinterException;
import com.sunmi.peripheral.printer.InnerPrinterManager;
import com.sunmi.peripheral.printer.SunmiPrinterService;
import com.sunmi.printerhelper.R;
import com.sunmi.printerhelper.utils.BluetoothUtil;
import com.sunmi.printerhelper.utils.ESCUtil;
import com.sunmi.printerhelper.utils.SunmiPrintHelper;

import java.security.cert.Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.security.auth.login.LoginException;

public class SimpleActivity extends BaseActivity implements View.OnClickListener {
    SunmiPrinterService sunmiPrinter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            boolean result = InnerPrinterManager.getInstance().bindService(this, new InnerPrinterCallback() {
                @Override
                protected void onConnected(SunmiPrinterService service) {
                    Toast.makeText(SimpleActivity.this, "Printer Connected", Toast.LENGTH_SHORT).show();
                    sunmiPrinter = service;
                }

                @Override
                protected void onDisconnected() {

                }
            });
            Log.e("SUNMIDEMO", "Result" + result);
        } catch (InnerPrinterException e) {
            e.printStackTrace();
        }

        setContentView(R.layout.activity_simple);
        setMyTitle("Simple Activity");

        Button simpleBut = findViewById(R.id.btn_simple);
        Button exampleBut = findViewById(R.id.btn_example);
        Button reportBut = findViewById(R.id.btn_report);

        simpleBut.setOnClickListener(this);
        exampleBut.setOnClickListener(this);
        reportBut.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_simple:
                Toast.makeText(this, "Print Simple Example Clicked ", Toast.LENGTH_SHORT).show();
                onSimpleButtonClicked();
                break;
            case R.id.btn_example:
                Toast.makeText(this, "Print Complex Example Clicked", Toast.LENGTH_LONG).show();
                onComplexButtonClicked();
                break;
            case R.id.btn_report:
                Toast.makeText(this, "Print Simply Report Clicked ", Toast.LENGTH_SHORT).show();
                onSimplyReportButtonClicked();
                break;
        }

    }


    int ALIGN_LEFT = 0;
    int ALIGN_CENTER = 1;
    int ALIGN_RIGHT = 2;

    public void onSimpleButtonClicked() {
        Toast.makeText(this, "INSIDE SIMPLE BUTTON!!!!", Toast.LENGTH_SHORT).show();
        if (sunmiPrinter == null) {
            Toast.makeText(this, "SunmiPrinter is Null SIMPLE BUTTON!!!!", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            sunmiPrinter.printerInit(null);
            Toast.makeText(this, "TRY BLOCK SIMPLE BUTTON!!!!", Toast.LENGTH_SHORT).show();

            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText("LEFT_ALIGNMENT\n", null);

            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText("RIGHT_ALIGNMENT\n", null);

            sunmiPrinter.setAlignment(ALIGN_CENTER, null);
            sunmiPrinter.printText("CENTER_ALIGNMENT\n", null);
            sunmiPrinter.printText("ALIGNMENT is not Changed\n", null);

            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText("NOTICE: ALIGNMENT is Changed\n", null);


            sunmiPrinter.sendRAWData(ESCUtil.boldOn(), null);
            sunmiPrinter.printText("Bold Feature is ON\n", null);

            sunmiPrinter.sendRAWData(ESCUtil.boldOff(), null);
            sunmiPrinter.printText("Bold Feature is OFF\n", null);

            sunmiPrinter.printText("FONT size is increased to 40\n", null);
            sunmiPrinter.printTextWithFont("ITEM:           MEET", null, 40, null);
            sunmiPrinter.printTextWithFont("PRICE:          $59\b", null, 40, null);
            sunmiPrinter.setFontSize(36, null);

            sunmiPrinter.printText("--------------------------------\n", null);
            String[] txts = new String[]{"LEFT", "RIGHT"};
            int[] width = new int[]{1, 1};
            int[] align = new int[]{0, 2};
            sunmiPrinter.printColumnsString(txts, width, align, null);
            sunmiPrinter.printText("--------------------------------\n", null);

            sunmiPrinter.printText("--------------------------------\n", null);
            sunmiPrinter.sendRAWData(ESCUtil.boldOn(), null);
            String txts2[] = new String[]{"LEFT", "CENTER", "RIGHT"};
            int width2[] = new int[]{1, 1, 1};
            int align2[] = new int[]{0, 1, 2};
            sunmiPrinter.printColumnsString(txts2, width2, align2, null);
            sunmiPrinter.sendRAWData(ESCUtil.boldOff(), null);
            sunmiPrinter.printText("--------------------------------\n", null);

            sunmiPrinter.printText("Slash N VS LineWrap()\n", null);
            sunmiPrinter.printText("Slash N VS LineWrap()", null);
            sunmiPrinter.lineWrap(1, null);

            sunmiPrinter.setAlignment(ALIGN_CENTER, null);
            sunmiPrinter.printText("END OF PRINT", null);

            sunmiPrinter.autoOutPaper(null);
        } catch (RemoteException e) {
            Toast.makeText(this, "CATCH BLOCK SIMPLE BUTTON!!!!", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    private void onComplexButtonClicked() {
        if (!BluetoothUtil.isBlueToothPrinter) {
            SunmiPrintHelper.getInstance().printExample(this);
        } else {
            Toast.makeText(this, "Is Bluetooth is on ???", Toast.LENGTH_SHORT).show();
        }
    }

    private void onSimplyReportButtonClicked() {
        if (sunmiPrinter == null) {
            Toast.makeText(this, "SunmiPrinter is Null REPORT!!!!", Toast.LENGTH_SHORT).show();
            return;
        }

        String transactionsLabel = "Transaction";
        String turnoverLabel = "TurnOver";
        String netSaleLabel = "NetSale";
        String salesVatLabel = "Sales VAT";
        String returnsLabel = "Returns";
        String returnsVatLabel = "Returns VAT";

        String str_breakdown_by_payment_type = "Breakdown by payment type";
        String str_sales_totals_by_department = "Sales totals by department";
        String str_total_sales = "Total sales:";
        String str_net_sales = "Net sales:";
        String str_vat_ = "VAT:";
        String str_breakdown_by_vat_rate = "Breakdown by VAT Rate";
        String str_breakdown_by_invoice_type = "Break down by Invoice type";

        try {
            sunmiPrinter.printerInit(null);

            Toast.makeText(this, "TRY BLOCK REPORT!!!!", Toast.LENGTH_SHORT).show();

            // itemsString.append("[C]<font size='tall'>Report</font>").append("\n");
            // itemsString.append(getLineSeparator()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_CENTER, null);
            sunmiPrinter.printTextWithFont("Report\n", null, 40, null);

            sunmiPrinter.setFontSize(30, null);
            sunmiPrinter.printText(getLineSeparator() + "\n", null);

            // itemsString.append("[L]Date From").append("[R]" + invoiceReport.getDateFrom()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText("Date From", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText("Monday, August 8, 2022\n", null);


            // itemsString.append("[L]Date To").append("[R]" + invoiceReport.getDateTo()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText("Date To", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText("Monday, August 8, 2022\n", null);

            // itemsString.append(getLineSeparator()).append("\n");
            // itemsString.append("\n");
            sunmiPrinter.printText(getLineSeparator() + "\n\n", null);

            // itemsString.append("[L]<b>" + "Total" + "</b>").append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.sendRAWData(ESCUtil.boldOn(), null);
            sunmiPrinter.printText("Total", null);
            sunmiPrinter.sendRAWData(ESCUtil.boldOff(), null);

            // itemsString.append("[L]" + transactionsLabel + "").append("[R]" + invoiceReport.getTransactions()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText(" " + transactionsLabel + " ", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText(" " + transactionsLabel + " \n", null);

            // itemsString.append("[L]" + turnoverLabel + "").append("[R]" + invoiceReport.getTurnOver()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText(" " + turnoverLabel + " ", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText(" " + turnoverLabel + " \n", null);

            // itemsString.append("[L]" + netSaleLabel + "").append("[R]" + invoiceReport.getNetSales()).append("\n");
            sunmiPrinter.setAlignment(ALIGN_LEFT, null);
            sunmiPrinter.printText(" " + netSaleLabel + " ", null);
            sunmiPrinter.setAlignment(ALIGN_RIGHT, null);
            sunmiPrinter.printText(" " + netSaleLabel + " \n", null);


            String txts[] = new String[]{salesVatLabel, salesVatLabel + "\n"};
            int width[] = new int[]{1, 1};
            int align[] = new int[]{0, 2};
            sunmiPrinter.printColumnsString(txts, width, align, null);
            // itemsString.append("[L]" + salesVatLabel + "").append("[R]" + invoiceReport.getSalesVAT()).append("\n");


            // itemsString.append("[L]" + returnsLabel + "").append("[R]" + invoiceReport.getReturns()).append("\n");
            String txts2[] = new String[]{returnsLabel, returnsLabel + "\n"};
            sunmiPrinter.printColumnsString(txts2, width, align, null);

            // itemsString.append("[L]" + returnsVatLabel + "").append("[R]" + invoiceReport.getReturnVAT()).append("\n");
            // itemsString.append("\n");
            String txts3[] = new String[]{returnsVatLabel, returnsVatLabel + "\n"};
            sunmiPrinter.printColumnsString(txts3, width, align, null);

            // itemsString.append(getLineSeparator()).append("\n");
            // itemsString.append("[C]").append("End of Report").append("\n");
            // itemsString.append(getLineSeparator()).append("\n");

            sunmiPrinter.printText(getLineSeparator() + "\n", null);
            sunmiPrinter.setAlignment(ALIGN_CENTER, null);
            sunmiPrinter.printText("End of Report\n", null);

            SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy HH:mm");
            String currentDateandTime = sdf.format(new Date());

            //itemsString.append("[L]" + "Printed on:" + "").append("[R]" + currentDateandTime).append("\n");
            String txts4[] = new String[]{"Printed on:", currentDateandTime + "\n"};
            sunmiPrinter.printColumnsString(txts4, width, align, null);


            // itemsString.append("\n");
            // itemsString.append("\n");
            // itemsString.append("\n");

            sunmiPrinter.lineWrap(3, null);

        } catch (RemoteException e) {
            Toast.makeText(this, "CATCH BLOCK REPORT!!!!", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

    }
    public static String getLineSeparator() {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            str.append("-");
        }
        return str.toString();
    }

}
package com.simplypos.simply.util.printUtil;

import static com.simplypos.simply.constant.AppConstants.SP_ESC_POS_PRINTER;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.dantsu.escposprinter.connection.DeviceConnection;
import com.dantsu.escposprinter.connection.bluetooth.BluetoothConnection;
import com.dantsu.escposprinter.connection.bluetooth.BluetoothPrintersConnections;
import com.dantsu.escposprinter.connection.tcp.TcpConnection;
import com.simplypos.simply.R;
import com.simplypos.simply.dao.model.printer.EscPosPrinter;
import com.simplypos.simply.dao.storage.SharedPreference;
import com.simplypos.simply.pojo.data.DepartmentReport;
import com.simplypos.simply.pojo.data.InvoiceAddResponse;
import com.simplypos.simply.pojo.data.InvoiceReport;
import com.simplypos.simply.pojo.data.InvoiceTypesReport;
import com.simplypos.simply.pojo.data.Payment;
import com.simplypos.simply.pojo.data.PrintCompanyDetail;
import com.simplypos.simply.pojo.data.PrintDetails;
import com.simplypos.simply.pojo.data.PrintDetailsLineItem;
import com.simplypos.simply.pojo.data.PrintDetailsTax;
import com.simplypos.simply.pojo.data.VatRateInvoiceTypeReport;
import com.simplypos.simply.pojo.data.VatRateReport;
import com.simplypos.simply.util.NumberUtil;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class PrintUtil {
    private static final String TAG = PrintUtil.class.getSimpleName();

    public static int charactersInLine = 32;
    public static Context mContext = null;

    public static void printData(Context context, InvoiceAddResponse invoiceAddResponse) {
        printData(context, invoiceAddResponse.getPrintDetails());
    }

    public static void printData(Context context, PrintDetails printDetailObj) {
        mContext = context;
        EscPosPrinter printerSettingsObject = getPrinterSettings();
        if (printerSettingsObject != null && printDetailObj != null) {
            DeviceConnection deviceConnection = getDeviceConnection(context, printerSettingsObject);
            if (deviceConnection != null) {
                AsyncEscPosPrinter data = getAsyncEscPosPrinter(deviceConnection, printDetailObj, printerSettingsObject.getSelectedPageSize());
                if (printerSettingsObject.getSelectedInterfaceType().equals(context.getString(R.string.bluetooth))) {
                    new AsyncBluetoothEscPosPrint(
                            context,
                            new AsyncEscPosPrint.OnPrintFinished() {
                                @Override
                                public void onError(AsyncEscPosPrinter asyncEscPosPrinter, int codeException) {
                                    Log.e("Async.OnPrintFinished", "AsyncEscPosPrint.OnPrintFinished : An error occurred !");
                                }

                                @Override
                                public void onSuccess(AsyncEscPosPrinter asyncEscPosPrinter) {
                                    Log.i("Async.OnPrintFinished", "AsyncEscPosPrint.OnPrintFinished : Print is finished !");
                                }
                            }
                    ).execute(data);
                } else {
                    try {
                        new AsyncTcpEscPosPrint(
                                context,
                                new AsyncEscPosPrint.OnPrintFinished() {
                                    @Override
                                    public void onError(AsyncEscPosPrinter asyncEscPosPrinter, int codeException) {
                                        Log.e("Async.OnPrintFinished", "AsyncEscPosPrint.OnPrintFinished : An error occurred !");
                                        if (deviceConnection != null && deviceConnection.isConnected())
                                            deviceConnection.disconnect();
                                    }

                                    @Override
                                    public void onSuccess(AsyncEscPosPrinter asyncEscPosPrinter) {
                                        Log.i("Async.OnPrintFinished", "AsyncEscPosPrint.OnPrintFinished : Print is finished !");
                                        if (deviceConnection != null && deviceConnection.isConnected())
                                            deviceConnection.disconnect();
                                    }
                                }
                        ).execute(data);
                    } catch (Exception e) {
                        new AlertDialog.Builder(context)
                                .setTitle("Invalid TCP port address")