Snippets Collections
Could not find artifact com.aspose:aspose-cells:pom:20.7 in maven-public (http://10.30.154.118:8888/repository/maven-public/)
public static void main(String[] args) {
		

//Reverse numbers in the column.
  
  int [][] array = { 
				{1,2}, 
				{3,4}, 
				{5,6}, };
		
		for(int i= 0; i<array.length; i++) {
			for(int j=array[i].length-1; j>=0; j--) {
				System.out.print(array[i][j] + " ");
			}
			System.out.println();
		}
	}

//OUTPUT:
2 1 
4 3 
6 5 

//Reverse numbers in Row
public static void main(String[] args) {
		
		int [][] array = { 
				{1,2}, 
				{3,4}, 
				{5,6}, };
		
		for(int i=array.length-1; i>=0; i--) {
			for(int j=0; j<array.length-1; j++) {
				System.out.print(array[i][j] + " ");
			}
			System.out.println();
		}
	}

//OUTPUT:
5 6 
3 4 
1 2 

//Reverse numbers both Column and Row.
public static void main(String[] args) {
		
		int [][] array = { 
				{1,2}, 
				{3,4}, 
				{5,6}, };
		
		for(int i=array.length-1; i>=0; i--) {
			for(int j=array[i].length-1; j>=0; j--) {
				System.out.print(array[i][j] + " ");
			}
			System.out.println();
		}
	}
//OOUTPUT:
6 5 
4 3 
2 1 
public static void main(String[] args) {
		
		int [][] array = {
				{1,2,3,4,5},
				{6,7,8,9,10},
				{11,12,13,14,15},
				{16,17,18,19,20},
		};
		for(int row =0; row < array.length; row ++) {
			int total = 0;
			for(int column = 0; column < array[0].length; column++) {
				total = total + array[row] [column];
			}
			System.out.println("Sum for Row " + row + " , is = " + total);
		}
	}

//OUTPUT:

Sum for Row 0 , is = 15
Sum for Row 1 , is = 40
Sum for Row 2 , is = 65
Sum for Row 3 , is = 90
public static void main(String[] args) {
		
		int [][] array = {
				{1,2,3,4,5},
				{6,7,8,9,10},
				{11,12,13,14,15},
				{16,17,18,19,20},
		};
		for(int colomn =0; colomn< array[0].length; colomn ++) {
			int total =0;
			for(int row = 0; row < array.length; row ++) {
				total = total + array[row] [colomn];
			}
			System.out.println("Sum for Colomn " + colomn + " , is = " + total);
		}
	}
//OUtPUT:
Sum for Column 0 , is = 34
Sum for Column 1 , is = 38
Sum for Column 2 , is = 42
Sum for Column 3 , is = 46
Sum for Column 4 , is = 50
public static void main(String[] args) {
		
		int [][] array = {
				{1,2,3,4,5},
				{6,7,8,9,10},
				{11,12,13,14,15},
		};
		int total = 0;
		for(int row = 0; row < array.length; row ++) {
			for(int colomn =0; colomn< array[row].length; colomn ++) {
				total = total + array[row] [colomn];
			}
			System.out.println("total number in each line is = " + total);
		}
	}

//OutPut:
total number in each line is = 15
total number in each line is = 55
total number in each line is = 120
public static void main(String[] args) {
		
		int[] array = {100,22,3,44,55,66,77,88};
		
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter number that you are looking for:");
		int number = scanner.nextInt();
		
		//int search;
		
		for(int i=0; i<array.length; i++) {
			if(number == array[i]) {
				System.out.printf("number %d is in the array it's index %d \n", number, i);
			}
			else {
				System.out.println("sorry");
			}
		}
		
		scanner.close();
	}
}
public static void main(String[] args) {
		
		int [][] array = {
				{1,2,3,4,5},
				{6,7,8,9,10},
				{11,12,13,14,15},
		};
		for(int row = 0; row < array.length; row ++) {
			for(int colomn =0; colomn< array[row].length; colomn ++) {
				System.out.print(array[row] [colomn] + " ");
			}
			System.out.println();
		}
	}

//OutPut:
1 2 3 4 5 
6 7 8 9 10 
11 12 13 14 15 
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
    // Creating an array
    int arr[] = {4, 10, 3, 5, 1};

    // Size of the array
    int size = sizeof(arr) / sizeof(arr[0]);

    // Building a max heap from the array
    make_heap(arr, arr + size);

    cout << "Max heap: ";
    for (int i = 0; i < size; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;

    // Inserting an element into the heap
    int newElement = 7;
    arr[size] = newElement;
    push_heap(arr, arr + size + 1);

    cout << "Max heap after insertion: ";
    for (int i = 0; i < size + 1; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;

    // Removing the maximum element from the heap
    pop_heap(arr, arr + size + 1);
    int maxElement = arr[size];
    --size;

    cout << "Max element removed: " << maxElement << endl;

    cout << "Max heap after removal: ";
    for (int i = 0; i < size; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;

    return 0;
}
#include <iostream>
#include <queue>
using namespace std;

// Binary Tree Node
struct Node {
    int data;
    Node* left;
    Node* right;
};

// Function to create a new node
Node* createNode(int value) {
    Node* newNode = new Node();
    if (!newNode) {
        cout << "Memory error\n";
        return NULL;
    }
    newNode->data = value;
    newNode->left = newNode->right = NULL;
    return newNode;
}

// Function to insert a node in the tree using level-order traversal
Node* levelOrderInsertion(Node* root, int value) {
    if (root == NULL) {
        root = createNode(value);
        return root;
    }
    
    queue<Node*> q;
    q.push(root);
    
    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();
        
        if (temp->left == NULL) {
            temp->left = createNode(value);
            break;
        } else {
            q.push(temp->left);
        }
        
        if (temp->right == NULL) {
            temp->right = createNode(value);
            break;
        } else {
            q.push(temp->right);
        }
    }
    
    return root;
}

// Depth-First Search (DFS) Traversal
void dfsTraversal(Node* root) {
    if (root == NULL) {
        return;
    }
    
    cout << root->data << " ";
    dfsTraversal(root->left);
    dfsTraversal(root->right);
}

// Breadth-First Search (BFS) Traversal
void bfsTraversal(Node* root) {
    if (root == NULL) {
        return;
    }
    
    queue<Node*> q;
    q.push(root);
    
    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();
        
        cout << temp->data << " ";
        
        if (temp->left != NULL) {
            q.push(temp->left);
        }
        
        if (temp->right != NULL) {
            q.push(temp->right);
        }
    }
}

// Function to delete leaf nodes using level-order traversal
Node* levelOrderDeletion(Node* root) {
    if (root == NULL) {
        return NULL;
    }
    
    queue<Node*> q;
    q.push(root);
    
    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();
        
        if (temp->left != NULL) {
            if (temp->left->left == NULL && temp->left->right == NULL) {
                delete temp->left;
                temp->left = NULL;
            } else {
                q.push(temp->left);
            }
        }
        
        if (temp->right != NULL) {
            if (temp->right->left == NULL && temp->right->right == NULL) {
                delete temp->right;
                temp->right = NULL;
            } else {
                q.push(temp->right);
            }
        }
    }
    
    return root;
}

int main() {
    Node* root = NULL;
    
    // Level-order insertion
    root = levelOrderInsertion(root, 1);
    root = levelOrderInsertion(root, 2);
    root = levelOrderInsertion(root, 3);
    root = levelOrderInsertion(root, 4);
    root = levelOrderInsertion(root, 5);
    
    cout << "DFS Traversal: ";
    dfsTraversal(root);
    cout << endl;
    
    cout << "BFS Traversal: ";
    bfsTraversal(root);
    cout << endl;
    
    // Level-order deletion of leaf nodes
    root = levelOrderDeletion(root);
    
    cout << "DFS Traversal after deletion: ";
    dfsTraversal(root);
    cout << endl;
    
    return 0;
}
public class Exercise {

	public static void main(String[] args) {
		int[] array = {2,3,4,1,5};
		int[] myarray = {2,9,5,4,8,1,6};
		
		System.out.println("my normal array is: " + Arrays.toString(array));
		
//bubbleSort array:		
		bubbleSort(array);
		System.out.println();
		System.out.println("After Sorting From Small number to Large number. ");
		System.out.println("\t" + Arrays.toString(array));
		
		sort(array);
		System.out.println();
		System.out.println("After Sorting From Large number to Small number: ");
		System.out.println("\t" + Arrays.toString(array));
		
//selection array
		System.out.println();
		
		System.out.println("my second array is : " + Arrays.toString(myarray));
		selectionArray(myarray);
		System.out.println();
		System.out.println("After Selection Array from minimum number to maximum number: ");
		System.out.println("\t" + Arrays.toString(myarray));
		
		
	}
	public static void bubbleSort(int[] array) {
		for(int i=0; i<array.length; i++) {
			for(int j=0; j<array.length-1-i; j++) {
				if(array[j] > array[j+1]) {
					int temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
	}
	public static void sort(int[] array) {
		for(int i=0; i<array.length; i++) {
			for(int j=0; j<array.length-1-i; j++) {
				if(array[j] < array[j+1]) {
					int temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
	}
	public static void selectionArray(int[] myarray) {
		for(int i =0; i<myarray.length; i++) {
			//find minimum in the list
			int currentMin = myarray[i];
			int currentMinIndex = i;
			
			for(int j= i+1; j< myarray.length; j++) {
				if(currentMin > myarray[j]) {
					currentMin = myarray[j];
					currentMinIndex = j;
				}
			}
			//swap list[i] with list[currentMinIndex]
			if(currentMinIndex != i) {
				myarray[currentMinIndex] = myarray[i];
				myarray[i] = currentMin;
			}
		}
	}

}


public class Exercise {

	public static void main(String[] args) {
		int[] array = {2,3,4,1,5};
		
		System.out.println("my normal array is: " + Arrays.toString(array));
		
		bubbleSort(array);
		System.out.println();
		System.out.println("After Sorting From Small number to Large number. ");
		System.out.println(Arrays.toString(array));
		
		sort(array);
		System.out.println();
		System.out.println("After Sorting From Large number to Small number: ");
		System.out.println(Arrays.toString(array));
		
	}
	public static void bubbleSort(int[] array) {
		for(int i=0; i<array.length; i++) {
			for(int j=0; j<array.length-1-i; j++) {
				if(array[j] > array[j+1]) {
					int temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
	}
	public static void sort(int[] array) {
		for(int i=0; i<array.length; i++) {
			for(int j=0; j<array.length-1-i; j++) {
				if(array[j] < array[j+1]) {
					int temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
	}

}


package com.example.codelearning.api;

import com.aspose.cells.*;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

@RestController
@RequestMapping("excel")
public class ExcelApi {

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadExcel() throws Exception {

        Workbook workbook = new Workbook();
        Worksheet worksheet = workbook.getWorksheets().get(0);

        // Tạo dữ liệu và biểu đồ
        createChartData(worksheet);

        // Lưu workbook vào ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.save(outputStream, SaveFormat.XLSX);

        InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        org.apache.poi.ss.usermodel.Workbook workbookApache = WorkbookFactory.create(inputStream);

        workbookApache.removeSheetAt(1);
        outputStream.reset();
        workbookApache.write(outputStream);

        // Chuẩn bị tệp Excel để tải xuống
        ByteArrayResource resource = new ByteArrayResource(outputStream.toByteArray());

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=chart_example.xlsx")
                .body(resource);
    }

    private void createChartData(Worksheet worksheet) {
        // Tạo dữ liệu mẫu
        Cells cells = worksheet.getCells();
        cells.get("A1").setValue("Month test test test");
        cells.get("A2").setValue("Oct");
        cells.get("A3").setValue("Nov");

        cells.get("B1").setValue("Toyota");
        cells.get("B2").setValue(32);
        cells.get("B3").setValue(42);

        cells.get("C1").setValue("VinFast");
        cells.get("C2").setValue(100);
        cells.get("C3").setValue(125);

        Range range = worksheet.getCells().createRange("A1:C3");
        Style style = worksheet.getWorkbook().createStyle();
        style.setBorder(BorderType.TOP_BORDER, CellBorderType.THIN, Color.getBlack());
        style.setBorder(BorderType.BOTTOM_BORDER, CellBorderType.THIN, Color.getBlack());
        style.setBorder(BorderType.LEFT_BORDER, CellBorderType.THIN, Color.getBlack());
        style.setBorder(BorderType.RIGHT_BORDER, CellBorderType.THIN, Color.getBlack());
        range.setStyle(style);

        // Đặt chiều rộng cho cột A
        Column columnA = worksheet.getCells().getColumns().get(0);
        columnA.setWidth(25);

        // Tạo biểu đồ
        int chartIndex = worksheet.getCharts().add(ChartType.LINE_WITH_DATA_MARKERS, 5, 0, 15, 5);
        Chart chart = worksheet.getCharts().get(chartIndex);

        chart.getNSeries().add("B2:B3", true);
        chart.getNSeries().get(0).setName("Toyota");
        chart.getNSeries().add("C2:C3", true);
        chart.getNSeries().get(1).setName("VinFast");

        chart.getNSeries().setCategoryData("A2:A3");
        PlotArea plotArea = chart.getPlotArea();
        plotArea.getArea().setFormatting(FormattingType.NONE);
        plotArea.getBorder().setTransparency(1.0);

        Title title = chart.getTitle();
        title.setText("Biểu đồ phân tích");
        Font font = title.getFont();
        font.setSize(16);
        font.setColor(Color.getLightGray());

        chart.getChartArea().setWidth(400);
        chart.getChartArea().setHeight(300);
    }
}
//a.
//Problem is (Index 5 out of bounds for length 5)
public static void main(String[] args) {
		
		int[] array = new int[5];
		array[5] = 10;
		System.out.println(array[5]); //Accessing index 5, which is out of bounds
	}

//corect is =    int[] array = new int[6];
                 array[5] = 10;
                   System.out.println(array[5]);    //output: 10



//b.
public class MissingInitialization {
    public static void main(String[] args) {
        int[] array;
        array[0] = 5; // Missing initialization of the array
    }
}
//correct is =  int[] array = {5,2,,3,4}; //initial this way first
or int[] array = new int[5];
array[0] = 5;
System.out.println(Arrays.toString(array[0]));   //output:  5


//C part.
public static void main(String[] args) {
		
		int[] array1 = {1,2,3};
        int[] array2 = {1,2,3};
        
        if(Arrays.equals(array1, array2)) {
        	System.out.println("Arrys are equal.");
        }
        else {
        	System.out.println("Arrays are not equal.");
        }
	}
}
//output: 
Arrys are equal.
public static void main(String[] args) {
		
        int[] myArray={1,2,33,56,34,85,32};
        
        int[]newArray=myArray;
        
        Arrays.sort(newArray); --------> //true becaue we have this method. sort array smallest one to largest one
        
        boolean status= false;
        for(int i=0;i<newArray.length-1;i++)
        {
            
            if (myArray[i]>myArray[i+1])
            {
                status=false;
                break;
            }
            else
            {
                status=true;
            }
        }
        System.out.println(status);
	}
}
//outPut: 
true
public static void main(String[] args) {

  //First Way
        int[] myArray={1,2,33,56,34,85,32};
        
        Arrays.sort(myArray);
        System.out.println(Arrays.toString(myArray));
	}
}

//Second Way

public class QuestionsOfLab_12 {

	//Lab 11 _ Question _3:
	public static void main(String[] args) {
		
		int[] array = {2,9,5,10,-1,0};
		
		bubbleSort(array);
		System.out.println("Array after sorting is : " + Arrays.toString(array));
		
	}
	public static void bubbleSort(int[] array) {
		for(int i=0; i<array.length; i++) {
			for(int j=0; j<array.length-1-i; j++) {
				if(array[j] > array[j+1]) {
					int temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
	}
}

Output:
Array after sorting is : [-1, 0, 2, 5, 9, 10]
public static void main(String[] args) {
		
        int[]myArray={1,2,33,56,34,85,32};
        int[]mystore=new int[7];
        
        int max=0;
        for(int i=0;i<myArray.length;i++)
        {
            if (myArray[i]>max)
            {
                
                max=myArray[i];
            }
        }
        
        System.out.println("maximum num = " + max);
        
        System.out.println(Arrays.toString(mystore));
        
        /*int secondLargest = 0;
        
        for(int i=0; i<myArray.length; i++) {
        	if(myArray[i] < max && myArray[i] > secondLargest) {
        		secondLargest = myArray[i];
        	}
        }
        System.out.println("The second Largest num in the array is = " + secondLargest); */
        
        
        int secondlargest=0;
        for(int i=0;i<myArray.length;i++)
        {
            
            mystore[i]=max-myArray[i]; // max - myArray[i] = 85-1= 84, 85-2= 83, 85-33= 52...
            
        }
        
        System.out.println(Arrays.toString(mystore));
        
        for(int i=0;i<myArray.length-1;i++)
        {
            if ((mystore[i]!=0) && (mystore[i]<=mystore[i+1]+1))
                secondlargest=i;
        }
        System.out.println("second largest num = " + myArray[secondlargest]);
    }
}
//outPut: 
maximum num = 85
[0, 0, 0, 0, 0, 0, 0]
[84, 83, 52, 29, 51, 0, 53]
second largest num = 56
int[]myArray={1,2,33,56,34,85,32};

 //find maximum number in the array

        int max=0;
        for(int i=0;i<myArray.length;i++)
        {
            if (myArray[i]>max)
            {
                
                max=myArray[i];
            }
        }
        
        System.out.println("maximum num in the array is = " + max);
//find second largest number in the array
        
        int secondLargest = 0;
        
        for(int i=0; i<myArray.length; i++) {
        	if(myArray[i] < max && myArray[i] > secondLargest) {
        		secondLargest = myArray[i];
        	}
        }
        System.out.println("The second Largest num in the array is = " + secondLargest);

//find third largest numbr in the array.
        int thirdLargest = 0;
        for(int i=0; i<myArray.length; i++) {
        	if(myArray[i]< secondLargest && myArray[i]> thirdLargest) {
        		thirdLargest = myArray[i];
        	}
        }
public static void main(String[] args) {
		
		int[]myArray={1,2,34};
        int max=0;
        for(int i=0;i<myArray.length;i++) // we don't need = and ()
        {
            if (myArray[i]>max)
            {
                max=myArray[i];
            }
            }
        System.out.println(max);
    }
}
//output: 
34
public static void main(String[] args) {
		int[] array1 = {10,20,30,40,50,60,70,80,90,100};
		int[] array2 = {200,300,400,500,-1,-2,-3};
		int[] array3 = {600,700,800,900,0};
		int[] array4 = {1000,2000,3000,4000,5000};
		
		int[] totalArray = merge(array1, array2, array3, array4);
		
		System.out.println(Arrays.toString(totalArray));
		
		
	}
	public static int[] merge(int[] array1, int[]array2, int[]array3, int[]array4) {
		int[] totalArray = new int[array1.length + array2.length + array3.length + array4.length];
		for(int i=0; i<array1.length; i++) {
			totalArray[i] = array1[i];
		}
		for(int i=0; i<array2.length; i++) {
			totalArray[array1.length +i] = array2[i];
		}
		for(int i=0; i<array3.length; i++) {
			totalArray[array1.length + array2.length + i] = array3[i];
		}
		for(int i=0; i<array3.length; i++) {
			totalArray[array1.length + array2.length + array3.length + i] = array4[i];
		}
		return totalArray;
	}
//output: 
total array are = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, -1, -2, -3, 600, 700, 800, 900, 0, 1000, 2000, 3000, 4000, 5000]
public static void main(String[] args) {
		int[] array1 = {1,2,3,4,5};
		int[] array2 = {6,7,8,9,10};
		int[] array3 = {100,200,300,400};
		
		System.out.println("array1 = " + Arrays.toString(array1));
		System.out.println("array2 = " + Arrays.toString(array2));
		System.out.println("array3 = " + Arrays.toString(array3));
		
		int [] array4 = merge(array1, array2, array3);
		
		System.out.println("After Merge of Three arrays are: ");
		
		System.out.println("array4 = " + Arrays.toString(array4));
		
	}
	public static int[] merge(int[] array1, int[] array2, int[] array3) {
		int[] array4 = new int[array1.length + array2.length + array3.length];
		for(int i=0; i<array1.length; i++) {
			array4[i] = array1[i];
		}
		for(int i=0; i<array2.length; i++) {
			array4[array1.length + i] = array2[i];
		}
		for(int i=0; i<array3.length; i++) {
			array4[array1.length + array2.length + i] = array3[i];
		}
		return array4;
	}
//output: 
public static void main(String[] args) {
		int[] array1 = {1,2,3,4,5};
		int[] array2 = {6,7,8,9,10};
		
		System.out.println("array1 = " + Arrays.toString(array1));
		System.out.println("array2 = " + Arrays.toString(array2));
		
		int [] array3 = merge(array1, array2);
		
		System.out.println("After Merge of two arrays are: ");
		
		System.out.println("array3 = " + Arrays.toString(array3));
		
	}
	public static int[] merge(int[] array1, int[] array2) {
		int[] array3 = new int[array1.length + array2.length];
		for(int i=0; i<array1.length; i++) {
			array3[i] = array1[i];
		}
		for(int i=0; i<array2.length; i++) {
			array3[array1.length + i] = array2[i];
		}
		return array3;
	}

//output:
array1 = [1, 2, 3, 4, 5]
array2 = [6, 7, 8, 9, 10]
After Merge of two arrays are: 
array3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
public static void main(String[] args) {
		int[] array = {1,2,3,4,5};
		
		int myPro = product(array);
		
		System.out.println("The Product numbers in the array are = " + myPro);
		
	}
	public static int product(int[]array) {
		int product = 1;
		for(int i=0; i<array.length; i++) {
			product = product * array[i];
		}
		return product;
	}
}
//output: 
The Product numbers in the array are = 120
	public static void main(String[] args) {
		int[] array = {1,2,3,4,5};
		
		int mySum = sum(array);
		
		System.out.println("Sum of number in the array are = " + mySum);
		
	}
	public static int sum(int[]array) {
		int sum = 0;
		for(int i=0; i<array.length; i++) {
			sum = sum + array[i];
		}
		return sum;
	}
//output: Sum of number in the array are = 15
public static void main(String[] args) {
		int[] array = {1,2,3,4,5};
		
		System.out.println("Array = " + Arrays.toString(array));
		
		
		swapAll(array, 3, 4);
		
		System.out.println("After swaping two number in the array are :");
		
		System.out.println("Array = " + Arrays.toString(array));
		
	}
	public static void swapAll(int[]array, int i, int j) {
		for(int count=0; count<array.length; count++) {
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
		}
	}
}
//output: 
Array = [1, 2, 3, 4, 5]

After swaping two number in the array are :

Array = [1, 2, 3, 5, 4]
public static void main(String[] args) {
		int[] array1 = {1,2,3};
		int[] array2 = {4,5,6};
		
		System.out.println("Array1 = " + Arrays.toString(array1));
		System.out.println("Array2 = " + Arrays.toString(array2));
		
		swapAll(array1, array2);
		
		System.out.println("After swaping Array1 and Array2:");
		
		System.out.println("Array1 = " + Arrays.toString(array1));
		System.out.println("Array2 = " + Arrays.toString(array2));
		
	}
	public static void swapAll(int[]array1, int[]array2) {
		for(int i=0; i<array1.length; i++) {
		int temp = array1[i];
		array1[i] = array2[i];
		array2[i] = temp;
		}
	}
}
//output: Array1 = [1, 2, 3]
Array2 = [4, 5, 6]
After swaping Array1 and Array2:
Array1 = [4, 5, 6]
Array2 = [1, 2, 3]
public static void main(String[] args) {
		int[] array = {1,2,3,4,5,6};
		
		reverse(array);
		
	}
	public static void reverse(int[] array) {
		//revere array.
		for(int i=0; i<array.length; i++) {
			int temp = array[i];
			array[i] = array[array.length-1-i];
			array[array.length-1-i] = temp;
			System.out.print(array[i]+ " ");
		}

	}
public static void main(String[] args) {
		int[] array = {1,2,3,4,5,6,7,8,9,10};
		//revere array.
		for(int i=0; i<array.length; i++) {
			System.out.print(array[array.length-1-i]+ " ");
		}
	}
//output: 10 9 8 7 6 5 4 3 2 1
public static void main(String[] args) {
		
		int a = 100;
		int b = 20;
		System.out.println("a = " +a+ ", b = " + b);
		
		int temp = a;
		a = b;
		b = temp;
		System.out.println("a = " +a+ ", b = " + b);
		
	}
}
//output:
a = 100, b = 20
a = 20, b = 100
1.
public static void main(String[] args) {
		int[] numbers = {1,2,3,4,5,6,7,8,9,10};
		
		for(int i=0; i<numbers.length-1; i++) {
			System.out.print(numbers[i]+ " ");
		}
		System.out.println();
	}
//output:  1 2 3 4 5 6 7 8 9 

2.
public static void main(String[] args) {
		int[] numbers = {10,9,8,7,6,5,4,3,2,1};
		
		for(int i=0; i<numbers.length-1; i++) {
			if(numbers[i] > numbers[i+1]) {
				numbers[i+1] = numbers[i+1] * 2;
				
				System.out.print(numbers[i+1]+ " ");
			}
		}
		System.out.println();
	}
//output: 18 16 14 12 10 8 6 4 2 
import java.util.Scanner;

public class Exercise {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("How many times do you want to say (I LOVE YOU):");
		int number = scanner.nextInt();
		
		
		Love(number);
	
	}
	static void Love(int n){
//base case
		if(n>0) {
			System.out.println("I LOVE YOU " +n+ " times.");
			n--;
			Love(n);
		}
		else {
			System.out.println("have nice day my Love");
		}
	}
	
}
//output:
How many times do you want to say (I LOVE YOU):
10
I LOVE YOU 10 times.
I LOVE YOU 9 times.
I LOVE YOU 8 times.
I LOVE YOU 7 times.
I LOVE YOU 6 times.
I LOVE YOU 5 times.
I LOVE YOU 4 times.
I LOVE YOU 3 times.
I LOVE YOU 2 times.
I LOVE YOU 1 times.
have nice day my Love
import java.util.Scanner;

public class Exercise {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("How far do you want to walk (in meters):");
		int distance = scanner.nextInt();
		
		
		takeAStep(0, distance);
	
	}
	static void takeAStep(int i, int distance) {
//base case
		if(i<distance) {
			i++;
			System.out.println("*You take a step * " +i+ " meter/s.");
			takeAStep(i, distance);
		}
		else {
			System.out.println("You are done walking!");
		}
	}
	
}
//output:
How far do you want to walk (in meters):
10
*You take a step * 1 meter/s.
*You take a step * 2 meter/s.
*You take a step * 3 meter/s.
*You take a step * 4 meter/s.
*You take a step * 5 meter/s.
*You take a step * 6 meter/s.
*You take a step * 7 meter/s.
*You take a step * 8 meter/s.
*You take a step * 9 meter/s.
*You take a step * 10 meter/s.
You are done walking!
https://www.udemy.com/course/java-the-complete-java-developer-course/?LSNPUBID=JVFxdTr9V80&ranEAID=JVFxdTr9V80&ranMID=39197&ranSiteID=JVFxdTr9V80-rDuwRxEjcfBG99QKFOL42Q&utm_medium=udemyads&utm_source=aff-campaign
 public static void count(String str)
	    {
	        // Initially initializing elements with zero
	        // as till now we have not traversed 
	        int vowels = 0, consonants = 0;
	       
	        // Declaring a all vowels String
	        // which contains all the vowels
	        String all_vowels = "aeiouAEIOU";
	       
	        for (int i = 0; i < str.length(); i++) {
	             
	            // Check for any special characters present
	            // in the given string
	            if ((str.charAt(i) >= 'A'
	                 && str.charAt(i) <= 'Z')
	                || (str.charAt(i) >= 'a'
	                    && str.charAt(i) <= 'z')) {
	                if (all_vowels.indexOf(str.charAt(i)) != -1)
	                    vowels++;
	                else if(str.charAt(i) >= 'A' || str.charAt(i)>= 'a' || str.charAt(i)<='z' || str.charAt(i)<='Z') 
	                    consonants++;
	            }
	        }
	       
	        // Print and display number of vowels and consonants
	        // on console
	        System.out.println("Number of Vowels = " + vowels
	                           + "\nNumber of Consonants = "
	                           + consonants);
	    }
	 
	    // Method 2
	    // Main driver method
	    public static void main(String[] args)
	    {
	        // Custom string as input
	        String str = "i am Mohamed Abdirizak";
	       
	        // Calling the method 1
	        count(str);
	    }

}
// OUTPUT:
Number of Vowels = 9
Number of Consonants = 10


//ANOTHER WAY
import java.util.Scanner;
public class Exercise {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		 //Counter variable to store the count of vowels and consonant    
        int vCount = 0, cCount = 0;    
            
        //Declare a string    
        String str = "My names is Mohamed Abdirizak Ali";    
            
        //Converting entire string to lower case to reduce the comparisons    
        str = str.toLowerCase();    
            
        for(int i = 0; i < str.length(); i++) {    
            //Checks whether a character is a vowel    
            if(str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {    
                //Increments the vowel counter    
                vCount++;    
            }    
            //Checks whether a character is a consonant    
            else if(str.charAt(i) >= 'a' && str.charAt(i)<='z') {      
                //Increments the consonant counter    
                cCount++;    
            }    
        }    
        System.out.println("Number of vowels:" + vCount  );    
        System.out.println("Number of consonants: " + cCount);   
        
        scanner.close();
    }    
}   

//OUTPUT: 
Number of vowels:12
Number of consonants: 16
import java.util.Scanner;

public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		
		System.out.print("Enter String name: " );
		String name = scanner.nextLine();
		int k = name.length();
		int f = 1;
		String z = "";
		
		for(int i=0; i<k; i++) {
			char c = name.charAt(i);
			if(c == 'A' || c == 'a' || c == 'E' || c =='e' || c == 'I' || c == 'i' || c == 'O' || c == 'o' || c=='U' || c=='u')
				f=0;
			else
				z = z+c;
			}
		System.out.println("String Without Vowels is : " +z);
		}
	}
public class methods {

	public static void main(String[] args) {
		//Scanner scanner = new Scanner(System.in);
		double[] array = {2.3, 4.5, 6.7, 3.9};
		
		double product = product(array);
		System.out.println("The product of all double number in the array are = " + product);
		
		double sum = sum(array);
		System.out.println("The sum of all number in the array are = " + sum);
	}
	public static double product(double[] array) {
		double product = 1.0;
		for(int i=0; i<array.length; i++) {
			product = product * array[i];
		}
		return product;
	}
	public static double sum(double[] array) {
		double sum =0;
		for(int i=0; i<array.length; i++) {
			sum = sum + array[i];
		}
		return sum;
	}
}
public class methods {

	public static void main(String[] args) {
      
		int[] array = {2, 3, 4, -2, 10, 32};

		int getMax = max(array);
		System.out.println(getMax);
		
		printArray(array);
		
    }
// This is returd method while you call array into the main class

	public static int max(int[] array) {
		int max = array[0];
		for(int i =0; i< array.length; i++) {
			if(array[i]> max) {
				max = array[i];
			}
		}
		return max;
	}

  
	//this is method that print array while you call into main class
	public static void printArray(int [] array) {
		for(int i=0; i<array.length; i++) {
			System.out.print(array [i] + " ");
		}
	}
}
		
public static void main(String[] args) {
//Question 1.
		//int[] array = {1,-2,3,0,5,6,7,8,100,10};
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter the rate of exchange: ");
		double exchange_rate = scanner.nextDouble();
		
		System.out.println("Press 0: to conver Dollar to Turkish Lira  \nPress 1: to conver Turkish Lira to Dollar" );
		int choice = scanner.nextInt();
		
		if(choice == 0) {
			System.out.println("Enter amount in Dollar: ");
			double amount = scanner.nextDouble();
			amount = amount * exchange_rate;
			
			System.out.printf("Your amount from Dollar to Turkish Lira is %.3f: " , amount , " Lira");
		}
		else if(choice == 1)
			System.out.println("Enter amount in Turkish Lira: ");
		    double amount = scanner.nextDouble();
		    amount = amount / exchange_rate;
		    
		    System.out.printf("Your amount from Turkish Lira to Dollar is %.3f: " , amount , " Dollar");
		}
	}
public static void main(String[] args) {

		int[] array = {1,-2,3,0,5,6,7,8,100,10};
		
		int myMin = min(array);
		System.out.println("minimum number in the array is = " + myMin);
}
public static int min(int[] array) {
		int min = 10;
		for(int i=0; i<array.length; i++) {
			if(array[i] < min) {
				min = array[i];
			}
		}
  return min;
}
public static void main(String[] args) {
		int[] array = {1,-2,3,0,5,6,7,8,100,10};
  
		int myMax = max(array);
		System.out.println("maxmimum number in the array is = " + myMax );
}
public static int max(int[] array) {
		int max = 0;
		for(int i =0; i< array.length; i++) {
			if(array[i] > max) {
				max = array[i];
			}
		}
		return max;
	}
public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter, How many Days Temperature: ");
		int days = scanner.nextInt();
		
		int[] temps = new int[days];
		int sum = 0;
		
		for(int i =0; i<days; i++) {
			System.out.println("Day " + (i + 1) + "'s high temperature:");
			temps[i] = scanner.nextInt();
			sum = sum + temps[i];
		}
		
		double average = (double) sum / days;
		int count = 0;
		for(int i=0; i< days; i++) {
			if(temps[i] > average) {
				count ++;
			}
		}
		
		System.out.printf("Average temp =   %.1f\n ", average);
		System.out.println(count + " Days above average");
		
		scanner.close();
	}
}
		
	
// output:
Enter, How many Days Temperature: 
7
Day 1's high temperature:
21
Day 2's high temperature:
24
Day 3's high temperature:
34
Day 4's high temperature:
32
Day 5's high temperature:
28
Day 6's high temperature:
27
Day 7's high temperature:
29
Average temp =   27.9
 4 Days above average
public static void main(String[] args) {
		//int [] numbers = new int[8];
		int [] numbers = {0, 3, 4, 5, 6, 7, 8, 9};
		
		for(int i= 0; i< numbers.length; i++) {
			System.out.print(numbers[i] + " ");
		}
		System.out.println();
	}
}

//output :
0 3 4 5 6 7 8 9 


public static void main(String[] args) {
		//int [] numbers = new int[8];
		int [] numbers = {0, 3, 4, 5, 6, 7, 8, 9};
		
		for(int i= 0; i< numbers.length; i++) {
			numbers[i] = 2 * numbers[i];
			System.out.print(numbers[i] + " ");
		}
		System.out.println();
	}
}
//output:
0 6 8 10 12 14 16 18 

public static void main(String[] args) {
		//int [] numbers = new int[8];
		int [] numbers = {0, 3, 4, 5, 6, 7, 8, 9};
		
		for(int i= 0; i< numbers.length; i++) {
			numbers[i] = 2 * i;
			System.out.print(numbers[i] + " ");
		}
		System.out.println();
	}
}
//output:
0 2 4 6 8 10 12 14 
public static void main(String[] args) {
		int a = 3;
		int b = 5;
		swap(a,b);
		System.out.println(a + " " + b);
		
	}
	public static void swap(int a, int b) {
		int temp = a; 
		a = b;
		b = temp;
		
	}
public static void main(String[] args) {

//Math Class
		double x ;
		double y;
		double z;
		
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter side x:");
		x = scanner.nextInt();
		
		System.out.println("Enter side y:");
		y = scanner.nextInt();
		
		z = Math.sqrt((x*x) + (y*y));
		System.out.println(z);
		
		scanner.close();
	}
}
String day = "Friday";
		
		switch( day) {
		case "Sunday": System.out.println("it's Sunday");
		break;
		case "Monday": System.out.println("it's Monady");
		break;
		case "Tuesday": System.out.println("it's Tuesday");
		break;
		case "Wensday": System.out.println("it's Wensday");
		break;
		case "Thursday": System.out.println("it's THursday");
		break;
		case "Friday": System.out.println("it's Friday");
		break;
		case "Sturday": System.out.println("it's Saturday");
		break;
		
		default : System.out.println("That'is Not A Day");
		}
	
	}
//Write a Java method that takes in an array of doubles and returns the product of all the doubles in the array.

public static void main(String[] args) {
		
		double[] Array1 = {2.9, 2.5, 5.6};
		double myProduct = products(Array1);
		System.out.printf("Product of array1 = %.2f " , myProduct);
		System.out.println();
}
public static double products(double[]arr) {
		double product = arr[0] * arr[1] * arr[2];
		for(int i=1;i<arr.length;i++) {
		}
		return product;
	}

//output 
Product of array1 = 40.60 
	public static void main(String[] args) {
      
//1. product array
		
		int[] Array1 = {2, 2, 5};
		int myProduct = products(Array1);
		System.out.println("Product of array1 = " + myProduct);

//2. Sum array
		int[] Array2  = {7, 5, 8, 9};
		int sum = sum(Array2);
		System.out.println("Sum of array2 are = " + sum);
		

//3. Max number in the array
		
		int[] array3 = {9, 100, 4};
		int max = getMax(array3);
		System.out.println("maximum number of array3 = " + max);
		
//4. Min number in the array
		
		int[] array4 = {10, 20, -2};
		int min = getMin(array4);
		System.out.println("minimum number of array4 = " + min);
	}
	
1.	
	public static int products(int[]arr) {
		int product = arr[0] * arr[1] * arr[2];
		for(int i=1;i<arr.length;i++) {
		}
		return product;
	}

2.	
	public static int sum(int[] arr) {
		int sum = arr[0] + arr[1] + arr[2] + arr[3];
		return sum;
	}

3.
	
	public static int getMax(int[] arr) {
		int max = arr[0];
		for(int i=0; i<arr.length;i++) {
			if(arr[i] > max) {
				max = arr[i];
			}
		}
		return max;
	}

4.
	
	public static int getMin(int[] arr) {
		int min = arr[0];
		for(int i=0; i<arr.length; i++) {
			if(arr[i]<min) {
				min = arr[i];
			}
		}
		return min;
	}
}

			
		
	

public static void main(String[] args) {
		int[] numbers = new int[8];
		numbers[1] = 3;
		numbers[4] = 99;
		numbers[6] = 2;
	
		int x = numbers[1];
		numbers[x] = 42;
		numbers[numbers[6]] = 11;
		
		for(int i=0; i<8; i++) {
			System.out.print(numbers[i] + " ");
		}
		System.out.println(); }
}
//output:
0 3 11 42 99 0 2 0 

name.length
for(int i=0; i<numbers.length; i++) {
			System.out.print(numbers[i] + " ");
		}
//output
0 3 11 42 99 0 2 0 

//sometimnes we assign each element a value in loop

		for(int i=0; i<8; i++) {
			numbers[i] = 2 * i;
			System.out.println(numbers[i]);
        }
//output.
0
2
4
6
8
10
12
14
public class methods {

	public static void main(String[] args) {
//we can initial array into two types:
		
//First This
		int[] array = {1, 2, 3, 4};
		System.out.println(array[0]);
		System.out.println(array[1]);
		System.out.println(array[2]);
		System.out.println(array[3]);

//Second This:
		System.out.println("--------");
		
		int[] array1 = new int[4];
		array1[0] = 10;
		array1[1] = 20;
		array1[2] = 30;
		array1[3] = 40;
		System.out.println(array1[0]);
		System.out.println(array1[1]);
		System.out.println(array1[2]);
		System.out.println(array1[3]);
		
		System.out.println("--------");
		
		
		String[] friends = {"ALi", "Mohamed", "Cade", "Yahya"};
		System.out.println(friends[0]);
		System.out.println(friends[1]);
		System.out.println(friends[2]);
		System.out.println(friends[3]);
		
		System.out.println("--------");
		
		
		String[] fruits = new String[5];
		fruits[0] = "Mango";
		fruits[1] = "Apple";
		fruits[2] = "Bannana";
		fruits[3] = "tomato";
		fruits[4] = "Limon";
		
		System.out.println(fruits[0]);
		System.out.println(fruits[1]);
		System.out.println(fruits[2]);
		System.out.println(fruits[3]);
		System.out.println(fruits[4]);
	
	}
}
public class methods {

	public static void main(String[] args) {
//question 1:
		HelloMessage();

//question 2:		
		double sum = sum(19.50, 100.60);
		System.out.println(sum);
		
//question 3:
		boolean number = number(9);
		System.out.println(number);
   //same
      boolean number = isEven(12);
		System.out.println(number);
		
//question 4:
		String full_name = name("Mohamed " , " Abdirizak");
		System.out.println(full_name);
      //same
      public static void main(String[] args) {
		String marged = concatt("Najma" , " Daud" , " Abdi");
		System.out.println(marged);
		
//question 5:
		double num = remainder(30 , 12);
		System.out.println(num);
		double numb = remainder(40, 12);
		System.out.println(numb);
      
//same Question 5:
        public static void main(String[] args) {
		remainder(28.5, 4.8);
	}
	

1.
	//we use method.
	public static void HelloMessage() {
		System.out.println("Hello world");
    }

2.	
	public static double sum(double a, double b) {
		double sum = a + b;
		return sum;
	}
3.	
	public static boolean number(int number) {
		if(number %2 ==0) {
			return true;
		}
		else {
			return false;
		}
	}
//same
      	public static boolean isEven(int x) {
		if(x%2 == 0)
			return true;
		else
			return false;
	}
4.	
      //we use Return Method.
	public static String name(String firstName, String secondName) {
		String full_name = firstName + secondName;
		return full_name.toUpperCase();
	}
 //same
        public static String concatt(String One , String Two, String Three) {
		String marged = One + Two + Three;
		return marged.toUppercase();
	}

5.
	public static double remainder(double x, double y) {
		double remainder = x / y;
		return remainder;
	}
//same
    public static void remainder(double x, double y) {
		double remainder = x / y;
		System.out.printf("remainder =  %.2f ", remainder);
	}
}
	
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;

public class GUI implements ActionListener {
	
	int count = 0;
	private JFrame frame;
	private JPanel panel;
	private JLabel label;
	
	
	//this public class is constructor.
	public GUI () {
		
		frame = new JFrame();
		
		JButton button = new JButton("Click me");
		button.addActionListener(this);
		
		label = new JLabel("Number of clicks:  0");
		
		
		panel = new JPanel();
		panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
		panel.setLayout(new GridLayout(0, 1));
		panel.add(button);
		panel.add(label);
		
		
		frame.add(panel, BorderLayout.CENTER);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setBackground(new Color(0, 20, 100));
		frame.setTitle("First GUI");
		frame.pack();
		frame.setVisible(true);
		
		button.setBackground(new Color (25, 100, 100));
		button.setForeground(new Color (100, 25, 255));
		
		label.setForeground(new Color (0, 20, 25));
		
		
	}

	public static void main(String[] args) {
		new GUI();

	}

	//we use this to increase count number.
	@Override
	public void actionPerformed(ActionEvent e) {
		count ++;
		label.setText("Number of clicks: " + count);
		
	}

}
public class stringmethods {

	public static void main(String[] args) {
		
		String name = "Mohamed Abdirizak Ali";
		
		System.out.println("Name: " + name);
		System.out.println("Uppercase: " + name.toUpperCase());
		System.out.println("Lowercase: " + name.toLowerCase());
		System.out.println("First char: " + name.charAt(0));
		System.out.println("Length: " + name.length());
		System.out.println("Last char: " + name.charAt(20));
		System.out.println("Your name: " + name.substring(0, 7));
		System.out.println("Your Father name: " + name.substring(8, 17));
	    System.out.println("Your surname is: " + name.substring(18, 21));
	}

}
//First way Method
public static void main(String[] args) {
		printMessage();
		add(5,9);
		multiply(10, 10);
  
        boolean sum = sum(3,1,5);
		System.out.println(sum);
	}
	
	public static void printMessage() {
		System.out.println("hapy birthday to you: ");
	}
	
	public static void add(int a, int b) {
		System.out.println(a + b);
	}

	public static void multiply(int a, int b) {
		System.out.println(a * b);
	}
}  //output: 
hapy birthday to you: 
14
100

// second way Return Method:
public static void main(String[] args) {
		int sum = add(5,9);
		System.out.println(sum);
		
		int product = multiply(10,10);
		System.out.println(product);
		
	}
	public static int add(int a, int b) {
		return a+b;
	}
	
	public static int multiply(int a, int b) {
		return a * b;
	}
}
//output:
14
100

// String type Method.
public static void main(String[] args) {
		String name = self("my name is mohamed, i am 20 years old!");
		System.out.println(name);
		
		String home = house("My house is very beautifull! ");
		System.out.println(home);
	}
	
	public static String self(String n) {
		return n.toLowerCase();
	}
	
	public static String house(String h) {
		return  h.toUpperCase();
	}
}

//Array Method:
public static void main(String[] args) {
		String array = myArray("This is my aweosme array:");
		System.out.println(array);
		
		int[] awesomeArray = arrayFromInt(4, 6, 7, 8);
		System.out.println(awesomeArray[0]);
		System.out.println(awesomeArray[1]);
		System.out.println(awesomeArray[2]);
		System.out.println(awesomeArray[3]);
	}
	
	public static String myArray(String a) {
		return a.toUpperCase();
	}
	
	public static int[] arrayFromInt(int a, int b, int c, int d) {
		int[] array = new int[4];
		array [0] = a;
		array [1] = b;
		array [2] = c;
		array [3] = d; 
		return array;
		
	}
//output: 
THIS IS MY AWEOSME ARRAY:
4
6
7
8

	public static boolean sum(int x, int y, int z) {
		if(x<=y && y<= z ) {
			return true;
		}
		else {
			return false;
		}
	}
}
//output: 
false




 public static void main (String args[]) {
        
       int number1 = (int)(Math.random() *10);
       int number2 = (int)(Math.random() *10);
	Scanner input = new Scanner(System.in);
        System.out.print("what is " + number1 + "+" + number2 + "?");
        int answer = input.nextInt();
        
        while(number1 + number2 != answer)
        {
            System.out.print("Wrong answer. Try again. What is " + number1 + "+" + number2 + "?");
            answer= input.nextInt();
        }
        System.out.println("You got it.");
}
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;



public class MainClass implements ActionListener {
	
	private static JLabel userLabel;
	private static JTextField userText;
	private static JLabel passwordLabel;
	private static JPasswordField passwordText;
	private static JButton button;
	private static JLabel success;
	public static void main(String[] args) {
		
		JPanel panel = new JPanel();
		JFrame frame = new JFrame();
		frame.setSize(350, 200);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.add(panel);
		
		panel.setLayout(null);
		
		userLabel = new JLabel("User");
		userLabel.setBounds(10, 20, 80, 25);
		panel.add(userLabel);
		
		userText = new JTextField();
		userText.setBounds(100, 20, 165, 25);
		panel.add(userText);
		
		passwordLabel = new JLabel("Password");
		passwordLabel.setBounds(10, 50, 80, 25);
		panel.add(passwordLabel);
		
		passwordText = new JPasswordField();
		passwordText.setBounds(100, 50, 165, 25);
		panel.add(passwordText);
		
		button = new JButton("Login");
		button.setBounds(130, 90, 80, 30);
		button.addActionListener(new MainClass());
		panel.add(button);
		
		success = new JLabel("");
		success.setBounds(130, 110, 300, 30);
		panel.add(success);
		
		frame.setVisible(true);
	}
	


	@Override
	public void actionPerformed(ActionEvent e) {
		String user = userText.getText();
		@SuppressWarnings("deprecation")
		String password = passwordText.getText();
		
		if(user.equals("Mohamed") && password.equals("abc885932"))
		{
			success.setText("Login successful!");
		}
		else
		{
			success.setText("Wrong!, Please Try again");
		}
	}
}
-----
----
---
--
-
    for(int line=1; line<=5; line++)
        {
            for(int j=1; j<=5 - (line -1); j++)
            {
                System.out.print("-");
            }
            System.out.println();
        }
*
***
*****
*******
*********      for(int line=1; line<=5; line++)
        {
            for(int j=1; j<=(2* line -1); j++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
*********
*******
*****
***
*        for(int line=5; line>=1; line--)
        {
            for(int j=1; j<=(2* line -1); j++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
1
222
33333
4444444
555555555


for(int line=1; line<=5; line++)
        {
            for(int j=1; j<=(2* line -1); j++)
            {
                System.out.print(line);
            }
            System.out.println();
        }
        
-----
----*
---**
--***
-****
*****
  
  
  for(int line = 1; line <=6; line ++)
        {
          //for(int j=1; j<= ( 5- (line -1); j++))
            for(int j= 1; j<= (-1 * line + 6); j++)
            {
                System.out.print("-");
            }
            for(int k= 1; k<= (1* line -1); k++)
            {
                System.out.print("*");
            }
            
            System.out.println();
        }
-----
----*
---**
--***
-****
*****    for(int line=1; line<=6; line++)
        {
            for(int j=1; j<=5 - (line -1); j++)
            {
                System.out.print("-");
            }
        for(int k=1; k<= (line -1); k++)
        {
            System.out.print("*");
        }
        System.out.println();
        }
---1---
--222--
-33333-
4444444

for(int line = 1; line <=4; line ++)
        {
            for(int j= 1; j<= ( -1 * line +4); j++)
            {
                System.out.print("-");
            }
            for(int k= 1; k<= ( 2* line -1); k++)
            {
                System.out.print(line);
            }
            for(int j= 1; j<= ( -1 * line + 4); j++)
            {
                System.out.print("-");
            }
            System.out.println();
        }
              for(int line=1; line<=4; line++)
        {
            for(int j=1; j<=(-1 * line + 4); j++)
            {
                System.out.print(" ");
            }
            for(int k=1; k<= (2 * line -1); k++)
            {
                System.out.print("*");
            }
            System.out.println();
   *    }
  ***
 *****
*******    






---*---
--***--
-*****-
*******
  
  for(int line = 1; line <=4; line ++)
        {
          //for(int j=1; j<=4-line; j++)
            for(int j= 1; j<= ( -1 * line +4); j++)
            {
                System.out.print("-");
            }
            for(int k= 1; k<= ( 2* line -1); k++)
            {
                System.out.print("*");
            }
          //for(int j=1; j<=( 4- line); j++)
            for(int j= 1; j<= ( -1 * line + 4); j++)
            {
                System.out.print("-");
            }
            System.out.println();
        }
#================#
|      <><>      |
|    <>....<>    |
|  <>........<>  |
|<>............<>|
|<>............<>|
|  <>........<>  |
|    <>....<>    |
|      <><>      |
#================#
  
  
  public static void main(String[] args) {
        topHalf();
        bottomHalf();
    }
    public static void topHalf() {
        
        System.out.println("#================#");
        
    for ( int line = 1; line <=4; line ++)
    {
        System.out.print("|");
        for(int space = 1; space <= ( line * - 2 + 8); space ++)
        {
            System.out.print(" ");
        }
        System.out.print("<>");
        for(int dot = 1; dot <= (4 * line -4); dot ++)
        {
            System.out.print(".");
        }
        System.out.print("<>");
        for(int space = 1; space <= (line * - 2 + 8); space ++)
        {
            System.out.print(" ");
        }
        System.out.println("|");
    }
}
    public static void bottomHalf() {
        for(int line = 1; line <=4; line ++)
        {
            System.out.print("|");
            for(int space = 1; space <= ( 2 * line -2); space ++)
                {
                    System.out.print(" ");
                }
            System.out.print("<>");
            for(int dot = 1; dot <=( -4 * line + 16); dot ++)
            {
                System.out.print(".");
            }
            System.out.print("<>");
            for(int space = 1; space <= ( 2 * line -2); space++)
            {
                System.out.print(" ");
            }
            System.out.println("|");
        }
        System.out.print("#================#");
    }
}

....1
...2
..3
.4
5

for (int line = 1; line <=5; line++) 
      {
          for( int j= 1; j<= (-1 * line + 5); j++)
          {
              System.out.print(" . ");
          }
          System.out.println(line);
      }

....1
...22
..333
.4444
55555      for (int line = 1; line <=5; line++) 
      {
          for( int j= 1; j<= (-1 * line + 5); j++)
          {
              System.out.print(".");
          }
          for(int k = 1; k<= line; k++)
          {
              System.out.print(line);
          }
          System.out.println();
      }


....1
...2.
..3..
.4...
5....      for (int line = 1; line <=5; line++) 
      {
          for( int j= 1; j<= (-1 * line + 5); j++)
          {
              System.out.print(".");
          }
              System.out.print(line);
              for(int j=1; j<= (line - 1); j++)
              {
                  System.out.print(".");
              }
              System.out.println();
      }


. . . . .
. . . .
. . .
. . 
.
        for (int line = 1; line <=5; line++) 
      {
          for( int j= 1; j<= (5 - (line - 1)); j++)
          {
              System.out.print(" . ");
          }
          System.out.println();
      }
//output
4  7  10  13  16

for (int count = 1; count <=5; count++) 
      {
         System.out.print(3 * count + 1 + " ");
      }

//output
2 7 12 17 22 

 for (int count = 1; count <=5; count++) 
      {
              System.out.print(5 * count -3 + " ");
      }
// same output
int num = 2;
      for (int count = 1; count <=5; count++) 
      {
          System.out.print(num +" ");
          num = num + 5;
      }

// outpu
17  13 9 5 1

for (int count = 1; count <=5; count++) 
      {
          System.out.print(-4 * count + 21 +" ");
      }
//output
1
22
333
4444
55555        for (int i = 1; i <= 5; i++) 
           {
             for(int j= 1; j<=i; j++)
           {
              System.out.print( i );
           }
              System.out.println();
           }
55555
4444
333
22
1
          for (int i = 5; i >=1; i--) 
         {
          for(int j= 1; j<=i; j++)
         {
            System.out.print( i );
         }
            System.out.println();
           

55555
4444
333
22
1           
           
           for (int i = 1; i <=5; i++) 
         {
          for(int j= 1; j<= 5 - (i - 1); j++)
          {
              System.out.print(5- (i - 1));
          }
          System.out.println();
          
         }
          
55555
4444
333
22
1          
           
           int num = 5;
      for (int i = 1; i <=5; i++) 
      {
          for(int j= 1; j<=num; j++)
          {
              System.out.print(num);
          }
          num--;
          System.out.println();
          
      }
// output

 * 
 *  * 
 *  *  * 
 *  *  *  * 
 *  *  *  *  * 
   
                 for (int i = 1; i <= 5; i++) 
                {
                 for(int j= 1; j<=i; j++)
                {
                   System.out.print(" * ");
                }
                   System.out.println();
                }
                
 *  *  *  *  * 
 *  *  *  * 
 *  *  * 
 *  * 
 *             for (int i = 5; i >=1; i--) 
              {
               for(int j= 1; j<=i; j++)
              {
                System.out.print(" * ");
              }
                System.out.println();
              }
          
 //output
 *  *  *  *  *  *  *  *  *  * 
 *  *  *  *  *  *  *  *  *  * 
 *  *  *  *  *  *  *  *  *  * 
 *  *  *  *  *  *  *  *  *  * 
 *  *  *  *  *  *  *  *  *  * 
   
   for (int i = 1; i <= 5; i++)  // outer loop
      {
          for(int j= 1; j<=10; j++) // inner loop
          {
              System.out.print(" * ");
          }
          System.out.println(); // end the line
      }
    }
public static void main(String[] args) {
        
      Scanner scanner = new Scanner(System.in);
      
      System.out.println("Enter a character: ");
      char input = scanner.next().charAt(0);
      
      if(input >= 'A' && input <='Z')
      {
          System.out.println(input + " is an Upper Case character.");
      }
      else if ( input >= 'a' && input <= 'z')
      {
          System.out.println(input + " is a Lower Case character.");
      }
      else if ( input >= '0' && input <= '9')
      {
          System.out.println(input + " is a Digit character. ");
      }
      else
      {
          System.out.println(input + " is a valid. is not Upper Case, Lower Case and Digit character.");
      }
    }
}
/*Question 2.  
    Write a program that prompts the user to enter the exchange rate 
    from currency in U.S. dollars to Turkish Lira. 
    Prompt the user to enter 0 to convert from U.S. dollars to Turkish Lira
    and 1 to convert from Turkish Lira and U.S. dollars. 
    Prompt the user to enter the amount in U.S. dollars 
    or Turkish Lira to convert it to Turkish Lira or U.S. dollars, respectively.
        */
                
        Scanner scanner = new Scanner(System.in);
        
       
        System.out.println("Enter the rate of exchange:");
        double exchangeRate = scanner.nextDouble();
        
        System.out.println("press 0: to convert Dollar to Turkish Lira\npress 1: to convert Turkish Lira to Dollar  ");
        int choice = scanner.nextInt();
        double amount;
        if(choice == 1)
        {
            System.out.println("Enter the amount in Dollar: ");
            amount = scanner.nextDouble();
            amount = amount * exchangeRate;
            System.out.println("The amount in Dollar is: " + amount);
        }
        else if ( choice == 0)
        {
            System.out.println("Enter the amount in Turkish Lira: ");
            amount = scanner.nextDouble();
            amount = amount / exchangeRate;
            System.out.println("The amount in Turkish Lira is: " + amount);
        }
    }
}
import java.util.Scanner;
public class Lab_5 {

    public static void main(String[] args) {
        
/*Question 1. Write a program that prompts the user to enter a string 
        and determines whether it is a palindrome string. 
        A string is palindrome if it reads the same 
        from right to left and from left to right. */
                
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a string:");
        String str = scanner.nextLine();
        
        int count = 0;
        for(int counter =0; counter < str.length(); counter++)
        {
            if(str.charAt(counter)==str.charAt(str.length()-1-counter))
                count = count + 1;
        }
        
        if( count == str.length())
        {
            System.out.println("The string " + str + " is palindrome");
        }
        else
        {
            System.out.println("The string " + str + " is not palindrome");
        }
    }
}
public static void main(String[] args) {
        
      Scanner scanner = new Scanner(System.in);
      
      System.out.println("what is your name : ");
      String name = scanner.next();
      
      
      if(name.startsWith("najma"))
      {
          System.out.println("welcome najma");
      }
      if(name.endsWith("mohamed"))
      {
          System.out.println("welcome mohamed");
      }
      else if( name.equalsIgnoreCase("najma"))
      {
          System.out.println("you are beautiful");
      }
      if (name.contains("najma mohamed"))
      {
          System.out.println("awesome, let's do it agian.");
      }
              
     
    }
}
Scanner scanner = new Scanner(System.in);
      
      System.out.println("what is your name: ");
      String name = scanner.next();
      
      if( name.equals("najma"))
      {
          System.out.println("İ love you very much, You love me: ");
      }
      System.out.println("Enter your answer. ");
      String answer = scanner.next();
      if(answer.equals("yes"))
      {
          System.out.println("we are happy family.");
      }
      else 
        {
          System.out.println("i hate you.")
        }
 1    2    3    4    5    6    7    8    9   10 
 2    4    6    8   10   12   14   16   18   20 
 3    6    9   12   15   18   21   24   27   30 

 for(int i=1; i <= 3; i++)
      {
          for(int j=1; j<=10; j++)
          {
              System.out.printf("%4d ", (i * j));
          }
          System.out.println();
      }
      
String name = "mohamed";
      name = name.toUpperCase();
      System.out.println("The uppercase of name is " +name);
      
      int length = name.length();
      System.out.println("The length of name is " +length);
      
      char first = name.charAt(2);
      System.out.println("The first letter of name is " +first);
import java.util.Scanner;
public class Exam_preparation {

    public static void main(String[] args) {
        
      Scanner scanner = new Scanner(System.in);
      int sum = 0;
      
      for(int i=1; i<=10; i++)
      {
          System.out.println("enter a number ");
          sum = sum + scanner.nextInt();
          //sum = sum + i;
      }
      System.out.println("the sum of number is " + sum);
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <property name="LOGS" value="./logs" />

    <appender name="Console"
              class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable
            </Pattern>
        </layout>
    </appender>

    <appender name="RollingFile"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOGS}/spring-boot-logger.log</file>
        <encoder
                class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
        </encoder>

        <rollingPolicy
                class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- rollover daily and when the file reaches 10 MegaBytes -->
            <fileNamePattern>${LOGS}/archived/spring-boot-logger-%d{yyyy-MM-dd}.%i.log
            </fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>

    <!-- LOG everything at INFO level -->
    <root level="info">
        <appender-ref ref="RollingFile" />
        <appender-ref ref="Console" />
    </root>

    <!-- LOG "com.baeldung*" at TRACE level -->
    <logger name="com.baeldung" level="trace" additivity="false">
        <appender-ref ref="RollingFile" />
        <appender-ref ref="Console" />
    </logger>

</configuration>
+----+
\    /
/    \
\    /
/    \
\    /
/    \
+----+
  
  public class Java_Quiz_App {

    public static void main(String[] args) {
        
        System.out.println("+----+");
      for (int i = 1; i <= 3; i++) 
      {
          System.out.println("\\    /");
          System.out.println("/    \\");
      }
        System.out.println("+----+");
    }
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileLineByLineUsingBufferedReader {

	public static void main(String[] args) {
		BufferedReader reader;

		try {
			reader = new BufferedReader(new FileReader("sample.txt"));
			String line = reader.readLine();

			while (line != null) {
				System.out.println(line);
				// read next line
				line = reader.readLine();
			}

			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
import java.util.*;

class Solution {
    public static void main(String[] args) {
        String str = "sinstriiintng";

        int[] counts = new int[26];

        for (int i = 0; i < str.length(); i++)
            counts[str.charAt(i) - 'a']++;

        for (int i = 0; i < 26; i++)
            if (counts[i] > 1)
                System.out.println((char)(i + 'a') + " - " + counts[i]);
    }
}
import java.util.*;
public class Main
{
	public static void main(String[] args) {
		System.out.println("Hello World");
		int n=52;
		for(int i=2;i<=Math.sqrt(n);i++){
		    if(n%i==0){
		        System.out.print("YES");
		        System.exit(1);
		    }
		    
		      
		}
		
		        System.out.println("NOT");
		    
	}
}
import java.util.Scanner;
public class BooleanExpression2 {
    

    public static void main(String[] args) {
        

//QUESTİON 8.	What is wrong in the following code? 


    Scanner scanner = new Scanner(System.in);
    
    System.out.println("Enter your score, please. ");
    Double score = scanner.nextDouble();
    
    if (score >= 90.0) 
        System.out.println("Your grade letter is: A");
    else if (score >= 80.0)
        System.out.println("Your grade letter is: B");
    else if (score >= 70.0)
        System.out.println("Your grade letter is: C");
    else if (score >= 60.0) 
        System.out.println("Your grade letter is: D");
    else
        System.out.println("Your grade letter is: F");
    
    }
}


/*output:
Enter your score, please. 
59.90
Your grade letter is: F
*/
import java.util.Scanner;
public class BooleanExpression2 {
    

    public static void main(String[] args) {
        
/*Question 6. 
re-write the following using nested if statements.
int numberOne,numberTwo,numberThree;
  please read the values from the keyboard
if(numberOne>numberTwo && numberTwo>numberThree)
{
System.out.println(“numberOne is the largest”);
}
*/

    Scanner scanner = new Scanner(System.in);
    
    System.out.println("Enter a number One, please: ");
    int numberOne = scanner.nextInt();
    
    System.out.println("Enter a number Two: ");
    int numberTwo = scanner.nextInt();
    
    System.out.println("Enter number Three: ");
    int numberThree = scanner.nextInt();
    
    if(numberOne > numberTwo && numberOne > numberThree)
    {
        System.out.println(numberOne + " = number One is largest. ");
    }
    if(numberTwo > numberOne && numberTwo > numberThree)
    {
        System.out.println(numberTwo + " = number Two is the largest. ");
    }
    else
    {
        System.out.println(numberThree +  " = number Three is largest. ");
    }
    }
}
import java.util.Scanner;
public class BooleanExpression2 {
    

    public static void main(String[] args) {
        
/*Question 5.What is the output of the code in (a) and (b) 
    if number is 30? What if number is 35? 

 if (number % 2 == 0)
 System.out.println(number + " is even."); 
 System.out.println(number + " is odd.");

 (a)

 if (number % 2 == 0) 
System.out.println(number + " is even."); 
else 
System.out.println(number + " is odd.");
		(b)
*/

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter a number: ");
    int number = scanner.nextInt();
    
    if(number % 2== 0)
    {
        System.out.println(number + ": is even");
    }
    else
    {
        System.out.println(number + ": is odd");
    }
    }
}

output: 
30 is even and odd 
35 is odd
import java.util.Scanner;
public class BooleanExpression2 {
    

    public static void main(String[] args) {
        
/*   Question 4.
write a program that increases score by 3 % if attendance 
 is greater than 9 and displays the final score.
*/
    Scanner scanner = new Scanner(System.in);
       
    System.out.println("Enter your score, Please: ");
    double score = scanner.nextDouble();
//data type   
    System.out.println("Enter the days you have attended, Please: ");
    int attendence = scanner.nextInt();
    
    if(attendence > 9)
    {
        score = score + score * 0.03;
    }
    System.out.println("Your final score is: "+score);
    
    }
}

//output:
/*Please Enter your score: 
80
Please Enter your attendence: 
10
Your final score is= 82.4
*/
import java.util.Scanner;
public class BooleanExpression2 {
    

    public static void main(String[] args) {
        
/*Question 3.
    Write a program that prompts the user to enter an integer. 
    If the number is a multiple of 5, the program displays HiFive. 
    If the number is divisible by 2, it displays HiEven.
*/
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please Enter a number:");
    int number = scanner.nextInt();
    if(number % 2 == 0)
    {
        System.out.println("Hi Even ");
    }
    else if( number % 5 == 0)
    {
        System.out.println("Hi Five: ");
    }
    }
}
public class BooleanExpression2 {
    

    public static void main(String[] args) {
        
/*Question 2.	Can the following conversions  be allowed?
        What is this type of conversion called?
        Write a test program to verify your answer. 
       boolean b = true;
       i = (int)b;
       int i = 1; 
       boolean b = (boolean)i;
*/
//boolean cannot converte into i.
       boolean b = true;
       int i = (int)b;
       System.out.println(i);
       int i = 1; 
       boolean b = (boolean)i;
       
       // this is incorrect answer.
       
    }
}
public class BooleanExpression2 {
    

    public static void main(String[] args) {
        
        int x=1;
        /*
        System.out.println(x>0);
        System.out.println(x<0);
        System.out.println(x!=0);
        System.out.println(x>=0);
        System.out.println(x!=1);
        */
        
        //we make assigning value.
        
        boolean expressionOne, expressionTwo, expressionThree;
        expressionOne= x>0;
        expressionTwo = x<0;
        expressionThree = x!=0;
        
        System.out.println(expressionOne);
        System.out.println(expressionTwo);
        System.out.println(expressionThree);
       
    }
}
package com.mycompany.java_quiz_app;

import java.util.Scanner;

public class Java_Quiz_App {

    public static void main(String[] args) {
        
        Scanner scanner = new Scanner(System.in);
        System.out.println("what is the percent did you earn: ");
        int percent = scanner.nextInt();
        
        if(percent >=90)
        {
            System.out.println("You got an A:");
        }
        else if(percent >=80)
        {
            System.out.println("You got a B:");
        }
        else if(percent >=60)
        {
            System.out.println("You got a C:");
        }
        else if(percent >=50)
        {
            System.out.println("You got a D:");
        }
        else
        {
            System.out.println("You got an F!: ");
        }
        
    }
}
 //Rewrite the above program by using static methods.
// static method help you to make your code more than one time.

public static void main(String[] args) {
        top();
        middle();
        lower();
        top();
        middle();
        lower();
        
    }
        public static void top() {
            
        System.out.println("  ________");
        System.out.println(" /        \\");
        System.out.println("/          \\");
        }
        public static void middle() {
            
        System.out.println("-\"-\'-\"-\'-\"-");
        }
        public static void lower() {
            
        System.out.println("\\          /");
        System.out.println(" \\________/");
        
        }
}
public class Lab_3 {
    
    //Question 3.	
    /*write program called Egg displays the following out shape */
    
    public static void main(String[] args) {
        
        System.out.println("  ________");
        System.out.println(" /        \\");
        System.out.println("/          \\");
        System.out.println("-\"-\'-\"-\'-\"-");
        System.out.println("\\          /");
        System.out.println(" \\________/");
        
        
    }
}
(Print a table) 
/*Write a program that displays the following table. 
Calculate the middle point of two points. */

 a	 b	middle point
(0,0)	(2,1)	(1.0,0.5)
(1,4)	(4,2)	(2.5,3.0)
(2,7)	(6,3)	(4.0,5.0)
(3,9)	(10,5)	(6.5,7.0)
(4,11)	(12,7)	(8.0,9.0)

 public static void main(String[] args) {
        
        System.out.println(" a\t b\tmiddle point");

        System.out.println("(0,0)\t(2,1)\t("+ (double)(0+2)/2 +"," + (double)(0+1)/2+")");
        
        System.out.println("(1,4)\t(4,2)\t("+ (double)(1+4)/2 +"," + (double)(4+2)/2+")");
        
        System.out.println("(2,7)\t(6,3)\t("+ (double)(2+6)/2 +"," + (double)(7+3)/2+")");
        
        System.out.println("(3,9)\t(10,5)\t("+ (double)(3+10)/2 +"," + (double)(9+5)/2+")");
        
        System.out.println("(4,11)\t(12,7)\t("+ (double)(4+12)/2 +"," + (double)(11+7)/2+")");
 }
// Question 1. 
// Write a program that reads in the length of sides 
// of an equilateral triangle and computes the area and volume.
import static java.lang.Math.sqrt;
import java.util.Scanner;

public class Lab_3 {
    
    public static void main(String[] args) {
        
    
        Scanner scanner = new Scanner(System.in);
        //input step.
        System.out.println("Please Enter the lenght of the sides: ");
        double lengthSide = scanner.nextDouble();
        
        System.out.println("Please Enter the height of the triangle: ");
        double height = scanner.nextDouble();
        
        //procesing step.
        double areaOfTriangle = sqrt(3)/4 * (Math.pow(lengthSide,2));
        //heighL*height = Math.pow(height,2)
        double volumeOfTriangle = areaOfTriangle * height;
        
        //telling user what happen.
      //you can use (format function) if you want after point (two,three or one number digits). like first one.
        System.out.format("The area of Triangle is :%.03f ",areaOfTriangle);
        System.out.println("The area of Triangle is: "+areaOfTriangle);
        System.out.println("The volume of Triangle is: "+volumeOfTriangle);
        
   
    }
}
star shape. 

  **   
 **** 
******
******
 **** 
  ** 
  
  
  public static void main(String[] args) {
        
        System.out.println("  **  ");
        System.out.println(" **** ");
        System.out.println("******");
        System.out.println("******");
        System.out.println(" **** ");
        System.out.println("  **  "); 
write program to display this shape.

  /\ 
 /""\ 
/""""\
\""""/
 \""/ 
  \/  
  
 public static void main(String[] args) {

        System.out.println("  /\\ ");
        System.out.println(" /\"\"\\ ");
        System.out.println("/\"\"\"\"\\");
        System.out.println("\\\"\"\"\"/");
        System.out.println(" \\\"\"/ ");
        System.out.println("  \\/  ");
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

//Main method make different main.
public class Main {

	public static void main(String[] args) {
		
		TicTacToe tictactoe = new TicTacToe();
		
	}

}
// make different class.

public class TicTacToe implements ActionListener {
	
	Random random = new Random();
	JFrame frame = new JFrame();
	JPanel title_panel = new JPanel();
	JPanel button_panel = new JPanel();
	JLabel textfield = new JLabel();
	JButton[] buttons = new JButton[9];
	boolean player1_turn;
	
	
	TicTacToe() {
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800,800);
        frame.getContentPane().setBackground(new Color(50,50,100));
        frame.setLayout(new BorderLayout());
        frame.setVisible(true);
        
        textfield.setBackground(new Color(50,50,100));
        textfield.setForeground(new Color(25,255,0));
        textfield.setFont(new Font("Ink Free", Font.BOLD,75));
        textfield.setHorizontalAlignment(JLabel.CENTER);
        textfield.setText("Tic-Tac-Toe");
        textfield.setOpaque(true);
        
        title_panel.setLayout(new BorderLayout());
        title_panel.setBounds(0,0,800,100);
        
        button_panel.setLayout(new GridLayout(3,3));
        button_panel.setBackground(new Color(150,150,150));
        
        for(int i=0;i<9;i++)
        {
            buttons[i] = new JButton();
            button_panel.add(buttons[i]);
            buttons[i].setFont(new Font("MV Boli",Font.BOLD,120));
            buttons[i].setFocusable(false);
            buttons[i].addActionListener(this);
            
        }

        
        title_panel.add(textfield);
        frame.add(title_panel,BorderLayout.NORTH);
        frame.add(button_panel);
       
        firstTurn();
        
	}
	
	
	 @Override
	 public void actionPerformed(ActionEvent e) {
		 
		 for(int i=0;i<9;i++) {
	            if(e.getSource()==buttons[i]) {
	            	if(player1_turn) {
	                    if(buttons[i].getText()=="") {
	                        buttons[i].setForeground(new Color(255,0,0));
	                        buttons[i].setText("X");
	                        player1_turn=false;
	                        textfield.setText("O turn");
	                        check();
	                    }
	                }
	                else {
	                    if(buttons[i].getText()=="") {
	                        buttons[i].setForeground(new Color(0,0,255));
	                        buttons[i].setText("O");
	                        player1_turn=true;
	                        textfield.setText("X turn");
	                        check();
	                    }
	                }
	            }
	        }
	 }
	 
	 public void firstTurn() {
		 
		 try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 if(random.nextInt(2)==0) {
			 player1_turn=true;
			 textfield.setText("X turn");
	            
	        }
	        else {
	            player1_turn=false;
	            textfield.setText("O turn");
	        }
		 
	 }
	 
	 public void check() {
		 
		 //check X win conditions
		 if(
				 (buttons[0].getText()=="X") &&
				 (buttons[1].getText()=="X") &&
				 (buttons[2].getText()=="X")
				 ) {
			 xWins(0,1,2);
		 }
		 if(
				 (buttons[3].getText()=="X") &&
				 (buttons[4].getText()=="X") &&
				 (buttons[5].getText()=="X")
				 ) {
			 xWins(3,4,5);
		 }
		 if(
				 (buttons[6].getText()=="X") &&
				 (buttons[7].getText()=="X") &&
				 (buttons[8].getText()=="X")
				 ) {
			 xWins(6,7,8);
		 }
		 if(
				 (buttons[0].getText()=="X") &&
				 (buttons[3].getText()=="X") &&
				 (buttons[6].getText()=="X")
				 ) {
			 xWins(0,3,6);
		 }
		 if(
				 (buttons[1].getText()=="X") &&
				 (buttons[4].getText()=="X") &&
				 (buttons[7].getText()=="X")
				 ) {
			 xWins(1,4,7);
		 }
		 if(
				 (buttons[2].getText()=="X") &&
				 (buttons[5].getText()=="X") &&
				 (buttons[8].getText()=="X")
				 ) {
			 xWins(2,5,8);
		 }
		 if(
				 (buttons[0].getText()=="X") &&
				 (buttons[4].getText()=="X") &&
				 (buttons[8].getText()=="X")
				 ) {
			 xWins(0,4,8);
		 }
		 if(
				 (buttons[2].getText()=="X") &&
				 (buttons[4].getText()=="X") &&
				 (buttons[6].getText()=="X")
				 ) {
			 xWins(2,4,6);
		 }
		 
		 
		 //check O win conditions
		 if(
				 (buttons[0].getText()=="O") &&
				 (buttons[1].getText()=="O") &&
				 (buttons[2].getText()=="O")
				 ) {
			 oWins(0,1,2);
		 }
		 if(
				 (buttons[3].getText()=="O") &&
				 (buttons[4].getText()=="O") &&
				 (buttons[5].getText()=="O")
				 ) {
			 oWins(3,4,5);
		 }
		 if(
				 (buttons[6].getText()=="O") &&
				 (buttons[7].getText()=="O") &&
				 (buttons[8].getText()=="O")
				 ) {
			 oWins(6,7,8);
		 }
		 if(
				 (buttons[0].getText()=="O") &&
				 (buttons[3].getText()=="O") &&
				 (buttons[6].getText()=="O")
				 ) {
			 oWins(0,3,6);
		 }
		 if(
				 (buttons[1].getText()=="O") &&
				 (buttons[4].getText()=="O") &&
				 (buttons[7].getText()=="O")
				 ) {
			 oWins(1,4,7);
		 }
		 if(
				 (buttons[2].getText()=="O") &&
				 (buttons[5].getText()=="O") &&
				 (buttons[8].getText()=="O")
				 ) {
			 oWins(2,5,8);
		 }
		 if(
				 (buttons[0].getText()=="O") &&
				 (buttons[4].getText()=="O") &&
				 (buttons[8].getText()=="O")
				 ) {
			 oWins(0,4,8);
		 }
		 if(
				 (buttons[2].getText()=="O") &&
				 (buttons[4].getText()=="O") &&
				 (buttons[6].getText()=="O")
				 ) {
			 oWins(2,4,6);
		 }
		 
	 }
	 
	 public void xWins(int a, int b, int c) {
		 
		 buttons[a].setBackground(Color.GREEN);
	     buttons[b].setBackground(Color.GREEN);
	     buttons[c].setBackground(Color.GREEN);
	        
	     for(int i=0;i<9;i++) {
	    	 buttons[i].setEnabled(false);
	    	 }
	        textfield.setText("X wins");
	    }
		 
	 public void oWins(int a, int b, int c) {
		 
		 buttons[a].setBackground(Color.GREEN);
	     buttons[b].setBackground(Color.GREEN);
	     buttons[c].setBackground(Color.GREEN);
	        
	     for(int i=0;i<9;i++) {
	    	 buttons[i].setEnabled(false);
	    	 }
	        textfield.setText("O wins");
	    }
		 
		 
	 }

package com.mycompany.converttemperature;

import java.util.Scanner;
public class ConvertTemperature {

    public static void main(String[] args) {
        
    // Question 5. Write a program to convert a temperature given in degree Fahrenheit to degree Celsius.
    //    Hint use oC=5/9 *(oF-32)
    
    
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter degree of Fahrenheit: ");
        double Fahrenheit = scanner.nextDouble();
        
      
        double Celsius = 5.0/9 * (Fahrenheit - 32);
        System.out.println("The degree of Celsius is:- "+Celsius);
      
      //now you will get double number when you write one of them double division. like 5.0/9 * ( F - 32);
        
     
    }
}
package com.mycompany.currenttime;


public class Currenttime {

    public static void main(String[] args) {
        
    //4.  Write a program that will tell the current time.
    //   Hint use System.currentTimemillis() to get the total number of seconds

        long currentTimemillis = System.currentTimeMillis();
        long totalseconds = currentTimemillis / 1000;
        long secondsnow = totalseconds % 60;
        long totalminutes = totalseconds / 60;
        long minutesnow = totalminutes % 60;
        long totalhours = totalminutes / 60;
        long hoursnow = totalhours % 24;
        
        System.out.println("The current time is: " + hoursnow + ":" +minutesnow + ":" + secondsnow );
        
        
    }
}
import java.util.Scanner;

public class Dayafter100 {

    public static void main(String[] args) {
        
    //3. Write a program that will find the day after 100 days from today.
    //   Hint: count from 1 starting from Monday, use modulo operator
        
        int dayNow = 27;
        //int daysAfter = 100;
        
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please Enter daysAfter: ");
        int daysAfter = scanner.nextInt();
        
        int dayAfter100 = (daysAfter + dayNow)%7;
        
        if (dayAfter100 == 1)
        {
            System.out.println("The day in 100 will be Monday. ");
        }
        if (dayAfter100 == 2)
        {
            System.out.println("The day in 100 will be Tuesday. ");
        }
        if (dayAfter100 == 3)
        {
            System.out.println("The day in 100 will be Wendsday. ");
        }
        if (dayAfter100 == 4)
        {
            System.out.println("The day in 100 will be Thursday. ");
        }
        if (dayAfter100 == 5)
        {
            System.out.println("The day in 100 will be Friday. ");
        }
        if (dayAfter100 == 6)
        {
            System.out.println("The day in 100 will be Saturday. ");
        }
        if (dayAfter100 == 7)
        {
            System.out.println("The day in 100 will be Sunday. ");
        }
        
        
    }
}
package com.mycompany.areaofcircle;

//import java.util.Scanner;
public class Areaofcircle {
    
    //Lab 2,   Question 2.

    public static void main(String[] args) {
        
        // Question 2.	Translate the following algorithm into Java code:
        
//   Step 1: Declare a double variable named miles with initial value 100.
//   Step 2: Declare a double constant named KILOMETERS_PER_MILE with value 1.609.
//   Step 3: Declare a double variable named kilometers, multiply miles and KILOMETERS_PER_MILE, and assign the result to kilometers. 
//   Step 4: Display kilometers to the console. 
//   What is kilometers after Step 4?

        
        double miles = 100;
        final double KILOMETERS_PER_MILE = 1.609;
        double kilometers;
        
        kilometers = miles * KILOMETERS_PER_MILE;
        
        System.out.println("kilometers is: "+kilometers);
        
        
    }
}
package com.mycompany.areaofcircle;

import java.util.Scanner;
public class Areaofcircle {
    
    //Lab 2,   Question 1.

    public static void main(String[] args) {
        //required variables:- radius, pi
        //pi is constant= 3.14
        
//input step.        
        final double pi = 3.14;
        
        //ask user to enter radius number.
        Scanner read = new Scanner(System.in);
        System.out.println("Enter the radius of the circle: ");
        double radius = read.nextDouble();
        
//procesing step.
        double area = pi*radius*radius;
        
        System.out.println("The area of circle is "+area);
        
        
    }
}
package net.javaguides.hibernate.dao;

import org.hibernate.Session;
import org.hibernate.Transaction;

import net.javaguides.hibernate.entity.Instructor;
import net.javaguides.hibernate.util.HibernateUtil;

public class InstructorDao {
    public void saveInstructor(Instructor instructor) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();
            // save the student object
            session.save(instructor);
            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public void updateInstructor(Instructor instructor) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();
            // save the student object
            session.update(instructor);
            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public void deleteInstructor(int id) {

        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();

            // Delete a instructor object
            Instructor instructor = session.get(Instructor.class, id);
            if (instructor != null) {
                session.delete(instructor);
                System.out.println("instructor is deleted");
            }

            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public Instructor getInstructor(int id) {

        Transaction transaction = null;
        Instructor instructor = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();
            // get an instructor object
            instructor = session.get(Instructor.class, id);
            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
        return instructor;
    }
}
// 
@Id
 @GenericGenerator(name = "generator", strategy = "guid", parameters = {})
 @GeneratedValue(generator = "generator")
 @Column(name = "APPLICATION_ID" , columnDefinition="uniqueidentifier")
 private String id;
//hibernate import 
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core-jakarta</artifactId>
    <version>5.6.10.Final</version>
</dependency>
<dependency>
    <groupId>jakarta.persistence</groupId>
    <artifactId>jakarta.persistence-api</artifactId>
    <version>3.1.0</version>
</dependency>\

//
<dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>3.0.2</version>
        </dependency>
//JSTL
<dependency>
    <groupId>jakarta.servlet.jsp.jstl</groupId>
    <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
    <version>2.0.0</version>
</dependency>
<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>jakarta.servlet.jsp.jstl</artifactId>
    <version>2.0.0</version>
</dependency>
//Lombox


<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.24</version>
    <scope>provided</scope>
</dependency>

//MSSQL JDBC
<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>9.4.1.jre16</version>
</dependency>

//MySQL
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.31</version>
</dependency>
///JPA
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>2.7.0</version>
</dependency>


//Spring Validator
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
//Loop - JSTL
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
  
  //Form - JSTL
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
import java.util.Scanner;

public class FirstPrograming {
    public static void main(String[] args) {
        
        System.out.println("welcome java programing: ");
        
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter number one: ");
        int numOne = scanner.nextInt();
        System.out.println("Enter number Two: ");
        int numTwo = scanner.nextInt();
        System.out.println("Enter number three: ");
        int numThree = scanner.nextInt();
        
        int sum= numOne+numTwo-numThree;
        
        System.out.println("sum of two numbers is: " +sum);
        
    }
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        
        Scanner scanner = new Scanner(System.in);
        
        
        System.out.println("what is your name: ");
        String name = scanner.nextLine();
        System.out.println("how old are you: ");
        int age = scanner.nextInt();
        
        scanner.nextLine();
        System.out.println("what is your favorite food: ");
        String food = scanner.nextLine();
        
        
        System.out.println("hello "+name);
        System.out.println("you are "+age+" years old.");
        System.out.println("you like "+food);
    }
}
public class FirstPrograming {
    public static void main(String[] args) {
        
        String x = "mother";
        String y= "father";
        String temp;
        
        temp=x;
        x=y;
        y=temp;
        
        System.out.println("x: "+x);
        System.out.println("y: "+y);
    }
}
public class FirstPrograming {
  public static void main(string[] args) {
    System.out.println("hello world.");
    
    byte age = 30;
    long viesCount = 3_123_456_789L;
    float price = 10.99F;
    char letter = 'A';
    boolean = true/false;
  }
  
}
import java.util.Scanner;



public class Main{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Your Number : ");
        int n = in.nextInt();
        System.out.println("Your number is : " +  ArmStrong(n));
        
        
    }
    static boolean ArmStrong(int n){
        int sum = 0;
        int num = n;
        while(n>0){
            int lastdig = n%10;
            sum  = sum+lastdig*lastdig*lastdig;
            n=n/10;
        }
        if(sum==num){
            return true;
        }
        else{
            return false;
        }
    }
    

    

}
import java.util.Scanner;



public class Main{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Your Number : ");
        int n = in.nextInt();
        System.out.println("Your Given Number :" +isPrime(n));
        
    }

    static Boolean isPrime(int n){
        if(n<=1){
            return false;
        }
        int c = 2;
        while(c*c<=n){
            if(n%c==0){
                return false;
            }
            c++;
        }
        if(c*c > n){
            return true;
        }else{
            return false;
        }

    }

}
public class mayank {
    public static void main(String[] args) {
        System.out.println("Enter the numbers");
        Scanner sc =new Scanner(System.in);
        int a = sc.nextInt();
        int b= sc.nextInt();
        int gcd=0;
        for (int i=1;i<=a || i<=b;i++){
            if (a%i ==0 && b%i==0){
                gcd = i;
            }
        }
        int lcm = (a*b) /gcd;
        System.out.println(lcm);

        /*int hcf=0;
        for (int i =1;i<=a||i<=b;i++){
            if(a%i==0 && b%i==0){
                hcf =i;
            }

        }
        System.out.println(hcf);*/
    }
}
class Sample 
{int a;
	{
		System.out.println("Inside Non-static/Instance block");
		a=100;
	}
	Sample()
		{
			System.out.println("Inside Constructors"+  a);
			a = 2000;
			System.out.println("Hello World!"+a);
		}
	Sample(boolean x)
		{
			System.out.println("Inside Constru"+a);
			a=3000;
			System.out.println("Hello World!"+a);
		}

	public static void main(String[] args) 
	{
		System.out.println("Start");
		Sample s1 = new Sample();
		Sample s2 = new Sample(true);
		System.out.println("Stop");

	}
}
import java.util.Scanner;

public class Main{
  public static void main(String[] args) {
    int ans = sum2();
    System.out.println("Your Answer = "+ans);
    
  }

    static int sum2(){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Number 1 : ");
        int num1 = in.nextInt();
        System.out.print("Enter Number 2 : ");
        int num2 = in.nextInt();

        int sum = num1+num2;
        return sum;
    }
}    
import java.util.Scanner;

public class Main{
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter Your Year : ");
    int n = in.nextInt();
    
    if(n%100==0){
      if(n%400==0){
        System.out.println("Its Leap/Century Year");
      }
      else{
        System.out.println("Not a Leap year");
      }
    }else if(n%4==0){
      System.out.println("Its a Leap Year");
    }
    else{
      System.out.println("Not a leap year");
    }
  } 
}
import java.util.Scanner;

public class Main{
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter Your Number");
    int n = in.nextInt();
    int sum = 0;
    while(n>0){
      int lastdig = n%10;
       sum = sum+lastdig;
       n = n/10;
    }
    System.out.println(sum);
  } 
}
class Biba
{{
	System.out.println("Hi");
}
Biba()
{
	System.out.println("Inside Constructors");
	
}
Biba(int a)
	{
		System.out.println("Inside Constructors 1");
		System.out.println(a);
	}
	public static void main(String[] args) 
	{
		System.out.println("Start");
		Biba s2 = new Biba();
		//Biba s3 = new Biba(45);
		System.out.println("Stop");

	}
}
import java.util.Scanner;

public class Main{
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String name = in.next();
    int size = name.length();
    String word = "";
    for (int i = 0; i < name.length(); i++) {
      char rev = name.charAt(size-i-1); // Index is Zero..... size = 4, i=0, -1 == 3;
      word = word + rev;
    }
    System.out.println(word);
  } 
}
import java.util.Scanner;
//To find Armstrong Number between two given number.
public class Main{
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    //input
    int sum = 0;
    System.out.println("Enter Your Number");
    int n = in.nextInt();
    int input = n;

    while(n>0){
     int lastdig = n%10; //To get the last Dig;
      sum = sum + lastdig*lastdig*lastdig;
      n = n/10;   //removes last dig from number;
    }
    if(input==sum){
      System.out.println("Number is Armstrong Number :" + input + " : "+ sum);
    }else{
      System.out.println("Number is Not Armstrong Number :" + input + " : "+ sum); 
    }
  } 
}
import java.util.Scanner;
//To find out whether the given String is Palindrome or not.  121 , 1331 
public class Main{
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    //input
    int sum = 0;
    int lastdig = 0;
    System.out.println("Enter Your Number");
    int n = in.nextInt();
    int input = n;

    while(n>0){
      lastdig = n%10; //To get the last Dig;
      sum = sum*10+lastdig;
      n = n/10;   //removes last dig from number;
    }
    if(input == sum){
      System.out.println("Number is Palindrome : "+ input + " : " + sum);
    }else{
      System.out.println("Number is Not Palindrome : " + input +" : "+ sum);
    }
    
  } 
}
import java.util.Scanner;
//To calculate Fibonacci Series up to n numbers.
public class Main{
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    //input
    System.out.print("Enter Your Number :");
    int n = in.nextInt();
    // 0 1 1 2 3 5 8 13

    int a = 0;
    int b = 1;
    int count = 2;
    while(count<n){
      int temp = b;
      b = a+b;
      a = temp;
      count++;
    }
    System.out.println(b);
  } 
}
Button myButton = findViewById(R.id.my_button);
myButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        doSomething();
    }
});

private void doSomething() {
    // Do something when the button is clicked
}
package database;

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

public class OracleConnection{

    public static Connection getConnection()
    {
         Connection myConnection = null;
         String userName, password, service, url;

         userName = "vehiculefleetdb" ;
         password = "123" ;
         service = "localhost" ;

         url = "jdbc:oracle:thin:";

        try {

                myConnection = DriverManager.getConnection(url + userName + "/" + password + "@" + service);
                 System.out.println(" Connection successfull");

        } catch (SQLException ex) {
              ex.printStackTrace();
                  System.out.println(" Connection failed  ");
        }

        return myConnection;
    }


}
package bus ;

import java.io.Serializable;

public class Vehicule implements IMileageEfficiency, Serializable{


	private static final long serialVersionUID = 1L;
	double ME;
	double serialNumber;
	String made;
	String model;
	String color;
	int lenghtInFeet;
	protected int tripCounter;
	double energyConsumed;
	String eSuffix;

	Vehicule(double serialNumber, String made, String model, String color,
			 int lenghtInFeet, int tripCounter, String eSuffix){
		ME = 0;
		this.tripCounter = tripCounter;
		energyConsumed = 0;
		this.serialNumber = serialNumber;
		this.made = made;
		this.model = model;
		this.color = color;
		this.lenghtInFeet = lenghtInFeet;
		this.eSuffix = eSuffix;
		
	};
	
	public double getSN() {
		return this.serialNumber;
	}
	
	public double getMilePerUnitOfEnergy() {
		if (energyConsumed == 0) {
			return 0;
		}else {
		ME = this.tripCounter/this.energyConsumed;
		return ME;
		}
	}
	
	public void makeTrip(int tripCounter, double energyConsumed) {
		this.energyConsumed = energyConsumed;
		this.tripCounter = tripCounter;
		
	}
System.out.printf("--------------------------------%n");
System.out.printf(" Java's Primitive Types         %n");
System.out.printf(" (printf table example)         %n");

System.out.printf("--------------------------------%n");
System.out.printf("| %-10s | %-8s | %4s |%n", "CATEGORY", "NAME", "BITS");
System.out.printf("--------------------------------%n");

System.out.printf("| %-10s | %-8s | %04d |%n", "Floating", "double",  64);
System.out.printf("| %-10s | %-8s | %04d |%n", "Floating", "float",   32);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "long",    64);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "int",     32);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "char",    16);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "short",   16);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "byte",    8);
System.out.printf("| %-10s | %-8s | %04d |%n", "Boolean",  "boolean", 1);

System.out.printf("--------------------------------%n");
[/* package whatever; // don't place package name! */

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

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
	public static void main (String[] args) throws java.lang.Exception
	{
		
		int x=add(1,2,3,4,5);
		System.out.println(x);
		// your code goes here
	}
	public static int add(int ...args)
	{
		int ans=0;
		for(int x:args)
		{
			ans+=x;
		}
		return ans;
	}
}]
Step 3: Authentication
Next, we will move on to API authentication methods. API authentication aims to check and verify if the user making the request is who they claim to be. The API authentication process will first validate the identity of the client attempting to make a connection by using an authentication protocol. The credentials from the client requesting the connection is sent over to the server in either plain text or encrypted form. The server checks that the credentials are correct before granting the request. The system needs to ensure each end user is properly validated. This is to ensure that the right user is accessing the service and not someone without the right access who might be an attacker trying to hack into the system.

HTTP Basic Authentication
Different API systems use different methods of authentication. First, we have HTTP basic authentication. This method of authentication makes use of a username and password that is put into the Authorization header of an API request. It is recommended to use this method of authentication through hypertext transfer protocol secure (HTTPS) so that the connection between the client and server is encrypted.

Bearer Authentication
Another method of authentication is Bearer Authentication. A token is used to authenticate and authorize a user request. The token is usually given to the user by the server after the user has authenticated through a login or verification method. The token is then put into the Authorization header of an API request. The issued tokens are short-lived and expire at some point. 

API Keys
Authentication with API keys is similar to Bearer Authentication. However, in the case of API keys, the keys are obtained by the user instead of issued by the server for bearer authentication. API keys do not have an expiry date and are usually provided by API vendors or through creating an account. Most APIs accept API keys via HTTP request headers. However, as there is no common header field to send the API key, it would be easier to consult the API vendor or refer to the appropriate documentation for the correct use of the API key when sending an API request. For this campaign, Circle uses the API key authentication method.

No Authentication
There are also some API systems where you can submit an API request without any authentication. Anyone can simply make a request to the specific URL and get a response without a token or API key. This method of authentication is not recommended and is usually used either for testing or for in-house premises.
  public static boolean isNotNullAll(Object... objects){
    for (Object element:
         objects) {
      if (Objects.isNull(element)) return false;
      if (element instanceof String){
        String temp = (String) element;
        if (temp.trim().isEmpty()) return false;
      }
    }
    return true;
  }
public class ZeroOneKnapsack {
    public static int zerOneKnapsack(int[] val, int[] wt, int w, int i){
        if(w==0 || i==0) return 0;
        if(wt[i-1]<=w){
            int ans1= val[i-1]+zerOneKnapsack(val,wt,w-wt[i-1],i-1);
            int ans2= zerOneKnapsack(val,wt,w,i-1);
            return Math.max(ans1,ans2);
        }
        else return zerOneKnapsack(val,wt,w,i-1);
    }

    public static int memoZerOneKnapsack(int[] val, int[]wt, int w,int i, int[][] arr){
        if(w==0 || i==0){
            return 0;
        }
        if(arr[i][w]!=-1){
            return arr[i][w];
        }
        if(wt[i-1]<=w){
            int ans1= val[i-1]+memoZerOneKnapsack(val,wt,w-wt[i-1],i-1,arr);
            int ans2= memoZerOneKnapsack(val,wt,w,i-1,arr);
            arr[i][w]= Math.max(ans1,ans2);
        }
        else {
           arr[i][w]= memoZerOneKnapsack(val, wt, w, i - 1, arr);
        }
        return arr[i][w];
    }//all elements of table must be initialised with -1's.

    public static int tabZeroOneKnapsack(int[] val, int[] wt, int w){
        int n= val.length;
        int[][] dp =new int[n+1][w+1];
        for (int i = 0; i < n+1; i++) dp[i][0]=0;
        for(int i=0;i<w+1;i++) dp[0][i]=0;
        for (int i = 1; i < n+1; i++) {
            for (int j = 1; j < w+1; j++) {
                int v=val[i-1];
                int weight=wt[i-1];
                if(weight<=j){
                    int incProfit=v+dp[i-1][j-weight];
                    int excProfit=dp[i-1][j];
                    dp[i][j]=Math.max(incProfit,excProfit);
                } else{
                    dp[i][j]=dp[i-1][weight];
                }
            }
        }
        return dp[n][w];
    }

    public static void main(String[] args){
        int[] val={15,14,10,45,30};
        int[] wt={2,5,1,3,4};
        int w=7;
        System.out.println(zerOneKnapsack(val,wt,w,val.length));
        int[][] arr=new int[val.length+1][w+1]; // for memoZeroKnapsack
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[0].length; j++) {
                arr[i][j]=-1;
            }
        }
        System.out.println(memoZerOneKnapsack(val,wt,w,val.length,arr));
    }
}
src/main/java
    +- com
        +- example
            +- Application.java
            +- ApplicationConstants.java
                +- configuration
                |   +- ApplicationConfiguration.java
                +- controller
                |   +- ApplicationController.java
                +- dao
                |   +- impl
                |   |   +- ApplicationDaoImpl.java
                |   +- ApplicationDao.java
                +- dto
                |   +- ApplicationDto.java
                +- service
                |   +- impl
                |   |   +- ApplicationServiceImpl.java
                |   +- ApplicationService.java
                +- util
                |   +- ApplicationUtils.java
                +- validation
                |   +- impl
                |   |   +- ApplicationValidationImpl.java
                |   +- ApplicationValidation.java
@Override
    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof WrongVoucher))
            return false;
        WrongVoucher other = (WrongVoucher)o;
        boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null)
                || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode));
        boolean storeEquals = (this.store == null && other.store == null)
                || (this.store != null && this.store.equals(other.store));
        return this.amount == other.amount && currencyCodeEquals && storeEquals;
    }
package com.company;
import java.util.Scanner;

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

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

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

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

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

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

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

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

    public static Node root = new Node();

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

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


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

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

    public static Node root = new Node();

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

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

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


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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    static class info{
        int diam;
        int ht;

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

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

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

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

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

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

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

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

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



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

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


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

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

    }

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

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

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

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

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

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

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

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

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

mport java.util.Random;

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

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

  /* Constructors */
  // Removed in checkpoint 3

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

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

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

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

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

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

public class CrystalBall extends Thread{
  private Question question;

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

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


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

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

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

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

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

public class FortuneTeller {

  public static void main(String[] args) {

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

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

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

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

	}
}

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

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

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

  // inner class
  static class Book {
    String description;

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

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

  }
}
class Lib {
  String objType;
  String objName;

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

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

  // Inner class
  class Book {
    String description;

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

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

    Lib.Book book1 = fiction.new Book();
    book1.setDescription();
    System.out.println("Fiction Book Description = " + book1.getDescription());
 
    Lib nonFiction = new Lib("book", "nonfiction");
    Lib.Book book2 = nonFiction.new Book();
    book2.setDescription();
    System.out.println("Non-fiction Book Description = " + book2.getDescription());
  }
}
class Outer {
  String outer;
  // Assign values using constructor
  public Outer(String name) {
    this.outer = name;
  }
 
  // private method
  private String getName() {
    return this.outer;
  }
}
 
  // Non-static nested class
  class Inner {
    String inner;
    String outer;
    
    public String getOuter() {
  // Instantiate outer class to use its method
  outer = Outer.this.getName();
}
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.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.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);
titleIs;
titleContains;
presenceOfElementLocated;
visibilityOfElementLocated;
visibilityOf;
presenceOfAllElementsLocatedBy;
textToBePresentInElement;
textToBePresentInElementValue;
frameToBeAvailableAndSwitchToIt;
invisibilityOfElementLocated;
elementToBeClickable;
stalenessOf;
elementToBeSelected;
elementSelectionStateToBe;
alertIsPresent;
WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);

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

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

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

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

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

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

<suite name="TestNG">

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

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

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

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

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

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

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

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