Dataset Viewer
Auto-converted to Parquet
classname
stringlengths
3
26
id
stringlengths
27
50
original_code
stringlengths
1.08k
59.9k
num_file
int64
2
14
num_line
int64
32
1.88k
Programming Language
stringclasses
3 values
emailgenerator
./ProjectTest/Java/emailgenerator.java
// emailgenerator/EmailApp.java package projecttest.emailgenerator; import com.sun.security.jgss.GSSUtil; import java.sql.SQLOutput; import java.util.Scanner; public class EmailApp { public static void main(String[] args) { System.out.println("Generate Organization's Email ==>"); Scanner sc=new Scanner(System.in); // String x=sc.nextLine(); System.out.println("Generating the email..."); System.out.println("Enter firstname :"); String first=sc.nextLine(); System.out.println("Enter Lastname :"); String second=sc.nextLine(); Email em=new Email(first,second); while(true) { System.out.println("1 : Information "); System.out.println("2 : Change Email"); System.out.println("3 : Change Password"); System.out.println("4 : Disclose Password"); System.out.println("5 : Exit"); System.out.println("Enter operation code :"); int a = sc.nextInt(); switch (a) { case 1: System.out.println(em.showInfo()); break; case 2: System.out.println("Enter alternate email prefix :"); sc.nextLine(); String alt = sc.nextLine(); em.setEmail(alt+"@drngpit.ac.in"); break; case 3: System.out.println("Enter the verification code :"); sc.nextLine(); String s = sc.nextLine(); if (s.equals(em.getVcode())) { System.out.println("Enter alternate password :"); String p = sc.nextLine(); em.setPassword(p); } else { System.out.println("Please Enter valid verification code !!!"); } System.out.println("Password updated successfully !!!"); break; case 4: System.out.println("Password disclose warning !!!"); System.out.println("Enter the verification code :"); sc.nextLine(); String s1 = sc.nextLine(); if (s1.equals(em.getVcode())) { System.out.println("Your password : " + em.getPassword()); } else { System.out.println("Please Enter valid verification code !!!"); } case 5: System.out.println("Have a great day ahead ! BYE "); return ; } } } } // emailgenerator/Email.java package projecttest.emailgenerator; import java.util.Scanner; public class Email { private String firstName; private String lastName; private String password; private String department; private String email; private int defaultPasswordLength=8; private int codelen=5; private String Vcode; private String company="drngpit.ac.in"; private String name; public Email(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; System.out.println("Kindly ! Enter department for email creation dear "+this.firstName+" "+this.lastName); //dept this.department=setDepartment(); System.out.println("Department:"+department); //pass this.password=randomPass(defaultPasswordLength); System.out.println("New Password :"+password); //clipping name as one this.name=firstName+lastName; //verification code this.Vcode=vcode(codelen); System.out.println("Your verification code : "+Vcode); //Binding email=name.toLowerCase()+"."+department+"@"+company; System.out.println("Official mail :"+email); } private String setDepartment(){ System.out.println("Enter the department Id\nSales : 1\nDevelopment : 2\nAccounting : 3"); Scanner in=new Scanner(System.in); int dep=in.nextInt(); if(dep==1){ return "sales"; } else if(dep==2){ return"dev"; } else if(dep==3){ return "acc"; } return""; } private String randomPass(int length){ String password="ABCEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%"; char[]pass=new char[length]; for(int i=0;i<length;i++){ int rand=(int)(Math.random()*password.length()); pass[i]=password.charAt(rand); } return new String(pass); } private String vcode(int codelen){ String samcode="1234567890"; char[]code=new char[codelen]; for(int i=0;i<codelen;i++){ int c=(int)(Math.random()*samcode.length()); code[i]=samcode.charAt(c); } return new String(code); } public void setPassword(String password) { this.password = password; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword(){ return password; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getVcode() { return Vcode; } public String getDept(String dep){ if(dep.equals("dev")){ return "Developers"; } else if(dep.equals("acc")){ return "Accounts"; } else if(dep.equals("sales")){ return "Sales"; } return ""; } public String showInfo(){ return "Name : "+name+"\nOfficial email : "+email+"\nDepartment : "+getDept(department); } }
2
194
Java
heap
./ProjectTest/Java/heap.java
// heap/LeftistHeap.java package projecttest.heap; import java.util.ArrayList; /* * This is a leftist heap that follows the same operations as a * binary min heap, but may be unbalanced at times and follows a * leftist property, in which the left side is more heavy on the * right based on the null-path length (npl) values. * * Source: https://iq.opengenus.org/leftist-heap/ * */ public class LeftistHeap { private class Node { private int element, npl; private Node left, right; // Node constructor setting the data element and left/right pointers to null private Node(int element) { this.element = element; left = right = null; npl = 0; } } private Node root; // Constructor public LeftistHeap() { root = null; } // Checks if heap is empty public boolean isEmpty() { return root == null; } // Resets structure to initial state public void clear() { // We will put head is null root = null; } // Merge function that merges the contents of another leftist heap with the // current one public void merge(LeftistHeap h1) { // If the present function is rhs then we ignore the merge root = merge(root, h1.root); h1.root = null; } // Function merge with two Nodes a and b public Node merge(Node a, Node b) { if (a == null) return b; if (b == null) return a; // Violates leftist property, so must do a swap if (a.element > b.element) { Node temp = a; a = b; b = temp; } // Now we call the function merge to merge a and b a.right = merge(a.right, b); // Violates leftist property so must swap here if (a.left == null) { a.left = a.right; a.right = null; } else { if (a.left.npl < a.right.npl) { Node temp = a.left; a.left = a.right; a.right = temp; } a.npl = a.right.npl + 1; } return a; } // Function insert. Uses the merge function to add the data public void insert(int a) { root = merge(new Node(a), root); } // Returns and removes the minimum element in the heap public int extract_min() { // If is empty return -1 if (isEmpty()) return -1; int min = root.element; root = merge(root.left, root.right); return min; } // Function returning a list of an in order traversal of the data structure public ArrayList<Integer> in_order() { ArrayList<Integer> lst = new ArrayList<>(); in_order_aux(root, lst); return new ArrayList<>(lst); } // Auxiliary function for in_order private void in_order_aux(Node n, ArrayList<Integer> lst) { if (n == null) return; in_order_aux(n.left, lst); lst.add(n.element); in_order_aux(n.right, lst); } } // heap/FibonacciHeap.java package projecttest.heap; public class FibonacciHeap { private static final double GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2; private HeapNode min; private static int totalLinks = 0; private static int totalCuts = 0; private int numOfTrees = 0; private int numOfHeapNodes = 0; private int markedHeapNoodesCounter = 0; /* * a constructor for an empty Heap * set the min to be null */ public FibonacciHeap() { this.min = null; } /* * a constructor for a Heap with one element * set the min to be the HeapNode with the given key * @pre key>=0 * @post empty == false */ public FibonacciHeap(int key) { this.min = new HeapNode(key); this.numOfTrees++; this.numOfHeapNodes++; } /* * check if the heap is empty * $ret == true - if the tree is empty */ public boolean empty() { return (this.min == null); } /** * Creates a node (of type HeapNode) which contains the given key, and inserts it into the heap. * * @pre key>=0 * @post (numOfnodes = = $prev numOfnodes + 1) * @post empty == false * $ret = the HeapNode we inserted */ public HeapNode insert(int key) { HeapNode toInsert = new HeapNode(key); // creates the node if (this.empty()) { this.min = toInsert; } else { // tree is not empty min.setNext(toInsert); this.updateMin(toInsert); } this.numOfHeapNodes++; this.numOfTrees++; return toInsert; } /** * Delete the node containing the minimum key in the heap * updates new min * * @post (numOfnodes = = $prev numOfnodes - 1) */ public void deleteMin() { if (this.empty()) { return; } if (this.numOfHeapNodes == 1) { // if there is only one tree this.min = null; this.numOfTrees--; this.numOfHeapNodes--; return; } // change all children's parent to null// if (this.min.child != null) { // min has a child HeapNode child = this.min.child; HeapNode tmpChild = child; child.parent = null; while (child.next != tmpChild) { child = child.next; child.parent = null; } } // delete the node// if (this.numOfTrees > 1) { (this.min.prev).next = this.min.next; (this.min.next).prev = this.min.prev; if (this.min.child != null) { (this.min.prev).setNext(this.min.child); } } else { // this.numOfTrees = 1 this.min = this.min.child; } this.numOfHeapNodes--; this.successiveLink(this.min.getNext()); } /** * Return the node of the heap whose key is minimal. * $ret == null if (empty==true) */ public HeapNode findMin() { return this.min; } /** * Meld the heap with heap2 * * @pre heap2 != null * @post (numOfnodes = = $prev numOfnodes + heap2.numOfnodes) */ public void meld(FibonacciHeap heap2) { if (heap2.empty()) { return; } if (this.empty()) { this.min = heap2.min; } else { this.min.setNext(heap2.min); this.updateMin(heap2.min); } this.numOfTrees += heap2.numOfTrees; this.numOfHeapNodes += heap2.numOfHeapNodes; } /** * Return the number of elements in the heap * $ret == 0 if heap is empty */ public int size() { return this.numOfHeapNodes; } /** * Return a counters array, where the value of the i-th index is the number of trees with rank i * in the heap. returns an empty array for an empty heap */ public int[] countersRep() { if (this.empty()) { return new int[0]; /// return an empty array } int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; // creates the array rankArray[this.min.rank]++; HeapNode curr = this.min.next; while (curr != this.min) { rankArray[curr.rank]++; curr = curr.next; } return rankArray; } /** * Deletes the node x from the heap (using decreaseKey(x) to -1) * * @pre heap contains x * @post (numOfnodes = = $prev numOfnodes - 1) */ public void delete(HeapNode x) { this.decreaseKey(x, x.getKey() + 1); // change key to be the minimal (-1) this.deleteMin(); // delete it } /** * The function decreases the key of the node x by delta. * * @pre x.key >= delta (we don't realize it when calling from delete()) * @pre heap contains x */ private void decreaseKey(HeapNode x, int delta) { int newKey = x.getKey() - delta; x.key = newKey; if (x.isRoot()) { // no parent to x this.updateMin(x); return; } if (x.getKey() >= x.parent.getKey()) { return; } // we don't need to cut HeapNode prevParent = x.parent; this.cut(x); this.cascadingCuts(prevParent); } /** * returns the current potential of the heap, which is: * Potential = #trees + 2*#markedNodes */ public int potential() { return numOfTrees + (2 * markedHeapNoodesCounter); } /** * This static function returns the total number of link operations made during the run-time of * the program. A link operation is the operation which gets as input two trees of the same * rank, and generates a tree of rank bigger by one. */ public static int totalLinks() { return totalLinks; } /** * This static function returns the total number of cut operations made during the run-time of * the program. A cut operation is the operation which disconnects a subtree from its parent * (during decreaseKey/delete methods). */ public static int totalCuts() { return totalCuts; } /* * updates the min of the heap (if needed) * @pre this.min == @param (posMin) if and only if (posMin.key < this.min.key) */ private void updateMin(HeapNode posMin) { if (posMin.getKey() < this.min.getKey()) { this.min = posMin; } } /* * Recursively "runs" all the way up from @param (curr) and mark the nodes. * stop the recursion if we had arrived to a marked node or to a root. * if we arrived to a marked node, we cut it and continue recursively. * called after a node was cut. * @post (numOfnodes == $prev numOfnodes) */ private void cascadingCuts(HeapNode curr) { if (!curr.isMarked()) { // stop the recursion curr.mark(); if (!curr.isRoot()) this.markedHeapNoodesCounter++; } else { if (curr.isRoot()) { return; } HeapNode prevParent = curr.parent; this.cut(curr); this.cascadingCuts(prevParent); } } /* * cut a node (and his "subtree") from his origin tree and connect it to the heap as a new tree. * called after a node was cut. * @post (numOfnodes == $prev numOfnodes) */ private void cut(HeapNode curr) { curr.parent.rank--; if (curr.marked) { this.markedHeapNoodesCounter--; curr.marked = false; } if (curr.parent.child == curr) { // we should change the parent's child if (curr.next == curr) { // curr do not have brothers curr.parent.child = null; } else { // curr have brothers curr.parent.child = curr.next; } } curr.prev.next = curr.next; curr.next.prev = curr.prev; curr.next = curr; curr.prev = curr; curr.parent = null; this.min.setNext(curr); this.updateMin(curr); this.numOfTrees++; totalCuts++; } /* * */ private void successiveLink(HeapNode curr) { HeapNode[] buckets = this.toBuckets(curr); this.min = this.fromBuckets(buckets); } /* * */ private HeapNode[] toBuckets(HeapNode curr) { HeapNode[] buckets = new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; curr.prev.next = null; HeapNode tmpCurr; while (curr != null) { tmpCurr = curr; curr = curr.next; tmpCurr.next = tmpCurr; tmpCurr.prev = tmpCurr; while (buckets[tmpCurr.rank] != null) { tmpCurr = this.link(tmpCurr, buckets[tmpCurr.rank]); buckets[tmpCurr.rank - 1] = null; } buckets[tmpCurr.rank] = tmpCurr; } return buckets; } /* * */ private HeapNode fromBuckets(HeapNode[] buckets) { HeapNode tmpMin = null; this.numOfTrees = 0; for (int i = 0; i < buckets.length; i++) { if (buckets[i] != null) { this.numOfTrees++; if (tmpMin == null) { tmpMin = buckets[i]; tmpMin.next = tmpMin; tmpMin.prev = tmpMin; } else { tmpMin.setNext(buckets[i]); if (buckets[i].getKey() < tmpMin.getKey()) { tmpMin = buckets[i]; } } } } return tmpMin; } /* * link between two nodes (and their trees) * defines the smaller node to be the parent */ private HeapNode link(HeapNode c1, HeapNode c2) { if (c1.getKey() > c2.getKey()) { HeapNode c3 = c1; c1 = c2; c2 = c3; } if (c1.child == null) { c1.child = c2; } else { c1.child.setNext(c2); } c2.parent = c1; c1.rank++; totalLinks++; return c1; } /** * public class HeapNode * each HeapNode belongs to a heap (Inner class) */ public class HeapNode { public int key; private int rank; private boolean marked; private HeapNode child; private HeapNode next; private HeapNode prev; private HeapNode parent; /* * a constructor for a heapNode withe key @param (key) * prev == next == this * parent == child == null */ public HeapNode(int key) { this.key = key; this.marked = false; this.next = this; this.prev = this; } /* * returns the key of the node. */ public int getKey() { return this.key; } /* * checks whether the node is marked * $ret = true if one child has been cut */ private boolean isMarked() { return this.marked; } /* * mark a node (after a child was cut) * @inv root.mark() == false. */ private void mark() { if (this.isRoot()) { return; } // check if the node is a root this.marked = true; } /* * add the node @param (newNext) to be between this and this.next * works fine also if @param (newNext) does not "stands" alone */ private void setNext(HeapNode newNext) { HeapNode tmpNext = this.next; this.next = newNext; this.next.prev.next = tmpNext; tmpNext.prev = newNext.prev; this.next.prev = this; } /* * returns the next node to this node */ private HeapNode getNext() { return this.next; } /* * check if the node is a root * root definition - this.parent == null (uppest in his tree) */ private boolean isRoot() { return (this.parent == null); } } } // heap/HeapPerformanceTest.java package projecttest.heap; import java.util.HashMap; import java.util.Random; import java.util.ArrayList; public class HeapPerformanceTest { private final int numElements; public HeapPerformanceTest(int numElements) { this.numElements = numElements; } public HashMap<String, Long> test() { // Number of elements to test // Create heaps for insertion and deletion tests FibonacciHeap fibonacciHeap = new FibonacciHeap(); LeftistHeap leftistHeap = new LeftistHeap(); HashMap<String, Long> ret = new HashMap<>(); // Insertion test long startTime = System.currentTimeMillis(); for (int i = 0; i < numElements; i++) { fibonacciHeap.insert(new Random().nextInt()); } long endTime = System.currentTimeMillis(); ret.put("Fibonacci Heap Insertion Time", endTime - startTime); startTime = System.currentTimeMillis(); for (int i = 0; i < numElements; i++) { leftistHeap.insert(new Random().nextInt()); } endTime = System.currentTimeMillis(); ret.put("Leftist Heap Insertion Time", endTime - startTime); // Deletion test startTime = System.currentTimeMillis(); while (!fibonacciHeap.empty()) { fibonacciHeap.deleteMin(); } endTime = System.currentTimeMillis(); ret.put("Fibonacci Heap Deletion Time", endTime - startTime); startTime = System.currentTimeMillis(); while (!leftistHeap.isEmpty()) { leftistHeap.extract_min(); } endTime = System.currentTimeMillis(); ret.put("Leftist Heap Deletion Time", endTime - startTime); // Merge test FibonacciHeap fibonacciHeap1 = new FibonacciHeap(); FibonacciHeap fibonacciHeap2 = new FibonacciHeap(); LeftistHeap leftistHeap1 = new LeftistHeap(); LeftistHeap leftistHeap2 = new LeftistHeap(); // Populate the heaps for merge test for (int i = 0; i < numElements / 2; i++) { fibonacciHeap1.insert(new Random().nextInt()); fibonacciHeap2.insert(new Random().nextInt()); leftistHeap1.insert(new Random().nextInt()); leftistHeap2.insert(new Random().nextInt()); } // Merge performance test startTime = System.currentTimeMillis(); fibonacciHeap1.meld(fibonacciHeap2); endTime = System.currentTimeMillis(); ret.put("Fibonacci Heap Merge Time", endTime - startTime); startTime = System.currentTimeMillis(); leftistHeap1.merge(leftistHeap2); endTime = System.currentTimeMillis(); ret.put("Leftist Heap Merge Time", endTime - startTime); return ret; } public static void main(String[] args){ int numElements = Integer.parseInt(args[0]); HeapPerformanceTest t = new HeapPerformanceTest(numElements); HashMap<String, Long> ret = t.test(); for (String key : ret.keySet()) { System.out.println(key + ": " + ret.get(key) + "ms"); } } }
3
629
Java
servlet
./ProjectTest/Java/servlet.java
// servlet/registration.java package projecttest.servlet; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class registration extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String f=request.getParameter("fname"); String c=request.getParameter("cardno"); String cn=request.getParameter("cono"); String ad=request.getParameter("add"); String dob=request.getParameter("dob"); String email=request.getParameter("email"); String pin=request.getParameter("pin"); try { Class.forName("com.mysql.jdbc.Driver"); Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/votingdb","Vaishnavi","Nelavetla@537"); PreparedStatement ps=con.prepareStatement("insert into register values(?,?,?,?,?,?,?)"); ps.setString(1,f); ps.setString(2,c); ps.setString(3,cn); ps.setString(4,ad); ps.setString(5,dob); ps.setString(6,email); ps.setString(7,pin); int i=ps.executeUpdate(); if(i>0) { out.print("Successfully your account has been created...PLEASE LOGIN"); RequestDispatcher rd=request.getRequestDispatcher("loginpage.html"); rd.include(request,response); } else { out.print("Failed account creation try again"); RequestDispatcher rd=request.getRequestDispatcher("registration.html"); rd.include(request,response); } } catch (Exception e2) { out.print("Invalid , Failed account creation try again "+e2); RequestDispatcher rd=request.getRequestDispatcher("registration.html"); rd.include(request,response); } out.close(); } protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } } // servlet/loginpage.java package projecttest.servlet; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class loginpage extends HttpServlet { private static final long serialVersionUID = 1L; final static Connection con=DBUtilR.getDBConnection(); static PreparedStatement ps = null; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String card=request.getParameter("cardno"); Integer pin=Integer.parseInt(request.getParameter("pin")); try { if(check(card,pin)) { out.print("Successful Login...You Can Vote Now"); RequestDispatcher rd=request.getRequestDispatcher("vote.html"); rd.include(request,response); } else { out.print("Sorry username or password error , Make new account"); RequestDispatcher rd=request.getRequestDispatcher("registration.html"); rd.include(request,response); } } catch (SQLException e) { e.printStackTrace(); } } static boolean check(String card,Integer pin) throws SQLException { boolean r=false; ps=con.prepareStatement("Select * from register where cardno=? and pin=?"); ps.setString(1,card); ps.setInt(2,pin); ResultSet rs=ps.executeQuery(); r=rs.next(); return r; } static boolean checkvote(String card) throws SQLException { boolean r=false; ps=con.prepareStatement("Select * from vote where cardno=?"); ps.setString(1,card); ResultSet rs=ps.executeQuery(); r=rs.next(); return r; } } // servlet/againvote.java package projecttest.servlet; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; public class againvote extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } // servlet/thankyou.java package projecttest.servlet; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; public class thankyou extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } // servlet/DBUtilR.java package projecttest.servlet; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBUtilR { static Connection conn = null; static { try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/votingdb", "Vaishnavi", "Nelavetla@537"); if(!conn.isClosed()) { System.out.println("Connection established"); } } catch (ClassNotFoundException | SQLException e) { System.out.println("Error in DBUtilFile"); e.printStackTrace(); } } public static Connection getDBConnection() { // TODO Auto-generated method stub return conn; } } // servlet/vote.java package projecttest.servlet; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLIntegrityConstraintViolationException; public class vote extends HttpServlet { private static final long serialVersionUID = 1L; final static Connection con=DBUtilR.getDBConnection(); static PreparedStatement ps = null; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String f=request.getParameter("cardno"); String l=request.getParameter("party"); try { Class.forName("com.mysql.jdbc.Driver"); Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/votingdb","Vaishnavi","Nelavetla@537"); if(checkLogin(f)) { ps=con.prepareStatement("insert into vote values(?,?)"); ps.setString(1,f); ps.setString(2,l); int i=ps.executeUpdate(); if(i>0) { out.print("Your Vote has been submitted successfully..."); RequestDispatcher rd=request.getRequestDispatcher("thankyou.html"); rd.include(request,response); } else { out.print("Failed to submit vote, try again"); RequestDispatcher rd=request.getRequestDispatcher("vote.html"); rd.include(request,response); } } else { out.print("Please enter correct card number"); RequestDispatcher rd=request.getRequestDispatcher("vote.html"); rd.include(request,response); } } catch (SQLIntegrityConstraintViolationException e2) { out.print("Please select any party"); RequestDispatcher rd=request.getRequestDispatcher("vote.html"); rd.include(request,response); } catch(Exception e) { out.print(" " +e); RequestDispatcher rd=request.getRequestDispatcher("vote.html"); rd.include(request,response); } out.close(); } protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } static boolean checkLogin(String card) throws SQLException { boolean r=false; ps=con.prepareStatement("Select * from register where cardno = ?"); ps.setString(1,card); ResultSet rs=ps.executeQuery(); r=rs.next(); return r; } }
6
308
Java
libraryApp
./ProjectTest/Java/libraryApp.java
// libraryApp/Book.java package projecttest.libraryApp; public class Book { private int isbn; private String title; private String author; private String genre; private int quantity; private int checkedOut; private int checkedIn; //Constructor for book object public Book(int isbn, String title, String author, String genre, int quantity, int checkedOut) { this.isbn = isbn; this.title = title; this.author = author; this.genre = genre; this.quantity = quantity; this.checkedOut = checkedOut; this.checkedIn = quantity-checkedOut; } public int getCheckedIn() { return checkedIn; } public void setCheckedIn(int checkedIn) { this.checkedIn = checkedIn; } public void setIsbn(int isbn) { this.isbn = isbn; } public void setTitle(String title) { this.title = title; } public void setAuthor(String author) { this.author = author; } public void setGenre(String genre) { this.genre = genre; } public void setQuantity(int quantity) { this.quantity = quantity; } public void setCheckedOut(int checkedOut) { this.checkedOut = checkedOut; } //Getter Methods public int getIsbn() { return isbn; } public String getTitle() { return title; } public String getAuthor() { return author; } public String getGenre() { return genre; } public int getQuantity() { return quantity; } public int getCheckedOut() { return checkedOut; } } // libraryApp/LibraryApp.java package projecttest.libraryApp; public class LibraryApp { BookRepository repo = new BookRepository(); public void findByTitle(String title) { repo.searchByTitle(title); return; } public void findByISBN(int isbn) { repo.searchByISBN(isbn); return; } public boolean findByGenre(String genre) { if(repo.searchByGenre(genre)) return true; else return false; } public int findISBN(int isbn) { return repo.searchISBN(isbn); } public boolean withdrawBook(int isbn) { return repo.getBook(isbn); } public boolean depositBook(int isbn) { return repo.submitBook(isbn); } public void getStatus(int isbn) { repo.bookStatus(isbn); } } // libraryApp/Main.java package projecttest.libraryApp; import java.util.Scanner; public class Main{ static Scanner scan = new Scanner(System.in); static LibraryApp app = new LibraryApp(); public static void main(String[] args) { int userChoice=0; System.out.println("-----Welcome to the Library!-----\n"); do{ System.out.println("\n-----------------------------------"); System.out.println("1. Search book by Title keyword."); System.out.println("2. Search book by ISBN number."); System.out.println("3. Search book by Genre."); System.out.println("4. Book Check In"); System.out.println("5. Book Check Out"); System.out.println("6. Exit from the library."); System.out.println("-----------------------------------"); System.out.print("\nChoose any option: "); userChoice = scan.nextInt(); scan.nextLine(); switch(userChoice){ case 1: System.out.print("Enter the Title of Book: "); app.findByTitle(scan.nextLine()); break; case 2: System.out.println("Enter ISBN number: "); app.findByISBN(scan.nextInt()); break; case 3: System.out.println("Enter Genre: "); app.findByGenre(scan.nextLine()); break; case 4: checkIn(); break; case 5: checkOut(); break; case 6: System.out.println("\nThanks for visiting. \nSee you again."); break; default: System.out.println("\nInvalid Choice!"); } }while(userChoice!=6); } //Checking book In private static void checkIn() { System.out.println("Enter Book's ISBN number : "); int isbnNum = scan.nextInt(); getStatus(isbnNum); int bookAvailable = app.findISBN(isbnNum); if(bookAvailable==1) { System.out.println(isbnNum); app.withdrawBook(isbnNum); System.out.println("Book CheckIn successful."); getStatus(isbnNum); } else System.out.printf("Book with %d ISBN number not Found in inventory.",isbnNum); } //Checking book Out private static void checkOut() { System.out.println("\nEnter Book's ISBN number : "); int isbnNum = scan.nextInt(); int bookAvailable = app.findISBN(isbnNum); if(bookAvailable==1) { if(app.depositBook(isbnNum)) System.out.println("Book CheckOut successful."); else System.out.println("No Space for more Books."); } else System.out.printf("Book with %d ISBN number not Found in inventory.",isbnNum); } private static void getStatus(int isbn) { app.getStatus(isbn); } } // libraryApp/BookRepository.java package projecttest.libraryApp; import java.util.ArrayList; public class BookRepository { private ArrayList<Book> books = new ArrayList<>(); private int booksFound = 0; //Constructor to initialize books public BookRepository(){ books.add(new Book(253910,"Pride and Prejudice C", "Jane Austen", "Love",10,7)); books.add(new Book(391520,"Programming in ANSI C", "E. Balagurusamy", "Educational",15,10)); books.add(new Book(715332,"Shrimad Bhagavad Gita", "Krishna Dvaipayana", "Motivational",20,18)); books.add(new Book(935141,"Java: The Complete Reference", "Herbert Schildt", "Educational",12,9)); books.add(new Book(459901,"It", "Stephan King", "Horror",7,5)); books.add(new Book(855141,"Disneyland", "Mickey & Minnie", "Love",10,3)); } //Searching books by Title Keyword public void searchByTitle(String title) { booksFound = 0; for(Book book : books) { String bookTitle = book.getTitle(); if(bookTitle.toLowerCase().contains(title.toLowerCase())) { bookDetails(book); booksFound++; } } System.out.printf("\n%d Book%s Found.\n",booksFound,booksFound>1?"s":""); return; } //Searching books by ISBN Number public void searchByISBN(int isbn) { booksFound = 0; for(Book book : books) { if(book.getIsbn()==isbn) { bookDetails(book); booksFound++; break; } } System.out.printf("\n%d Book%s Found.\n",booksFound,booksFound>1?"s":""); return; } //Searching books by Genre public boolean searchByGenre(String genre){ booksFound = 0; for(Book book : books) { String bookGenre = book.getGenre(); if(bookGenre.toLowerCase().equals(genre.toLowerCase())) { bookDetails(book); booksFound++; } } System.out.printf("\n%d Book%s Found.\n",booksFound,booksFound>1?"s":""); if(booksFound>0) return true; else return false; } // Display Book Details public void bookDetails(Book book) { System.out.println("\n+> Book details: \n"); System.out.println("\tTitle: "+book.getTitle()+"\n\tAuthor: "+ book.getAuthor()+"\n\tGenre: "+book.getGenre()+"\n\tISBN: "+book.getIsbn()+"\n\tQuantity: "+book.getQuantity()+"\n\tChecked Out: "+String.valueOf(book.getCheckedOut())+"\n\tAvailable: "+String.valueOf(book.getQuantity()-book.getCheckedOut())); } //Searching for ISBN number for checkIn and checkOut public int searchISBN(int isbn) { for(Book book:books) if(book.getIsbn()==isbn) return 1; return 0; } //withdrawing book public boolean getBook(int isbn) { for(Book book: books) { if(book.getIsbn()==isbn) { if((book.getQuantity()-book.getCheckedOut())>0) { book.setCheckedOut(book.getCheckedOut()+1); return true; } } } return false; } //submitting book public boolean submitBook(int isbn) { for(Book book: books) { if(book.getQuantity()>book.getCheckedIn()) { book.setCheckedOut(book.getCheckedOut()-1); return true; } } return false; } //Showing status of book public void bookStatus(int isbn) { for(Book book: books) { if(book.getIsbn()==isbn) { bookDetails(book); break; } } } }
4
340
Java
libraryManagement
./ProjectTest/Java/libraryManagement.java
// libraryManagement/LibFunctions.java package projecttest.libraryManagement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.Scanner; public class LibFunctions { public static void callIssueMenu() { System.out.println("Reached inside issue book menu"); Member m = new Member(); Book b = new Book(); Scanner sc = new Scanner(System.in); int addStatus = 0; while (addStatus == 0) { try { System.out.println("Enter the member id "); m.setMemberId(Integer.parseInt(sc.nextLine().toString())); System.out.println("Enter the isbn code "); b.setIsbnCode(sc.nextLine().toString()); issueBook(m, b); addStatus = 1; } catch (Exception e) { addStatus = 0; } } } public static void issueBook(Member m, Book b) { Connection conn = LibUtil.getConnection(); try { Statement stmt = conn.createStatement(); ResultSet rs = null; String qry = "select m.member_id, b.isbn_code, mbr.rec_id from members m,books b,member_book_record mbr\n" + "where m.member_id= " + m.getMemberId() + " \n" + "and b.isbn_code = '" + b.getIsbnCode() + "' \n" + "and m.member_id=mbr.member_id\n" + "and b.isbn_code=mbr.isbn_code and mbr.dor is null "; rs=stmt.executeQuery(qry); if (rs.next()) { System.out.println("The book is already issued and cannot be issued again"); } else { int k = stmt.executeUpdate("insert into member_book_record values(lib_seq.nextval," + m.getMemberId() + ",'" + b.getIsbnCode() + "',sysdate,null)"); if(k > 0){ k = stmt.executeUpdate("update books set units_available= (units_available-1) where isbn_code = '"+ b.getIsbnCode() +"' "); conn.commit(); System.out.println("The book is issued successfully"); }else{ conn.rollback(); } } conn.close(); } catch (Exception e) { e.printStackTrace(); } } public static void callReturnMenu() { System.out.println("Reached inside return book menu"); Member m = new Member(); Book b = new Book(); Scanner sc = new Scanner(System.in); int addStatus = 0; while (addStatus == 0) { try { System.out.println("Enter the member id "); m.setMemberId(Integer.parseInt(sc.nextLine().toString())); System.out.println("Enter the isbn code "); b.setIsbnCode(sc.nextLine().toString()); returnBook(m, b); addStatus = 1; } catch (Exception e) { addStatus = 0; } } } public static void returnBook(Member m, Book b) { Connection conn = LibUtil.getConnection(); try { Statement stmt = conn.createStatement(); ResultSet rs = null; String qry = "select m.member_id, b.isbn_code, mbr.rec_id from members m,books b,member_book_record mbr\n" + "where m.member_id= " + m.getMemberId() + " \n" + "and b.isbn_code = '" + b.getIsbnCode() + "' \n" + "and m.member_id=mbr.member_id\n" + "and b.isbn_code=mbr.isbn_code and mbr.dor is null "; rs=stmt.executeQuery(qry); if (rs.next()) { Integer recId= rs.getInt(3); System.out.println("The book is already issued and starting the process to return "); int k = stmt.executeUpdate("update books set units_available= (units_available+1) where isbn_code = '"+ b.getIsbnCode() +"' "); if(k > 0){ k = stmt.executeUpdate("update member_book_record set dor= sysdate where rec_id = "+ recId +" "); conn.commit(); System.out.println("The book is returned successfully"); }else{ conn.rollback(); } } else{ System.out.println("This book is not issued for the user"); } conn.close(); } catch (Exception e) { e.printStackTrace(); } } } // libraryManagement/Member.java package projecttest.libraryManagement; import java.sql.Date; /** * * @author testuser */ public class Member { private Integer memberId; private String memberName; private Date dateOfJoining; public Member() { } public Member(Integer memberId, String memberName, Date dateOfJoining) { this.memberId = memberId; this.memberName = memberName; this.dateOfJoining = dateOfJoining; } public Date getDateOfJoining() { return dateOfJoining; } public void setDateOfJoining(Date dateOfJoining) { this.dateOfJoining = dateOfJoining; } public Integer getMemberId() { return memberId; } public void setMemberId(Integer memberId) { this.memberId = memberId; } public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } } // libraryManagement/Book.java package projecttest.libraryManagement; /** * * @author testuser */ public class Book { private String isbnCode; private String bookName; private String bookDesc; private String authorName; private String subjectName; private Integer unitsAvailable; public Book(){ } public Book(String isbnCode, String bookName, String bookDesc, String authorName, String subjectName, Integer unitsAvailable) { this.isbnCode = isbnCode; this.bookName = bookName; this.bookDesc = bookDesc; this.authorName = authorName; this.subjectName = subjectName; this.unitsAvailable = unitsAvailable; } public Integer getUnitsAvailable() { return unitsAvailable; } public void setUnitsAvailable(Integer unitsAvailable) { this.unitsAvailable = unitsAvailable; } public String getIsbnCode() { return isbnCode; } public void setIsbnCode(String isbnCode) { this.isbnCode = isbnCode; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getBookDesc() { return bookDesc; } public void setBookDesc(String bookDesc) { this.bookDesc = bookDesc; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } } // libraryManagement/UserMenu.java package projecttest.libraryManagement; import java.util.Scanner; /** * * @author testuser */ public class UserMenu { public static void main(String[] args) { String input=""; Scanner sc = new Scanner(System.in); while(input != "5"){ System.out.println("---------------------------------------------------------"); System.out.println("---------------------------------------------------------"); System.out.println("---------------------------------------------------------"); System.out.println("Select the following options"); System.out.println("Enter 1 for adding a book"); System.out.println("Enter 2 for adding a member"); System.out.println("Enter 3 for issuing a book "); System.out.println("Enter 4 for returning a book "); System.out.println("Enter 5 to exit"); input = processUserInput(sc.nextLine().toString()); } } public static String processUserInput(String in) { String retVal="5"; switch(in){ case "1": System.out.println("---------------------------------------------------------"); System.out.println("You have selected option 1 to add a book"); AddBookMenu.addBookMenu(); return "1"; case "2": System.out.println("---------------------------------------------------------"); System.out.println("You have selected option 2 to add a member"); AddMemberMenu.addMemberMenu(); return "2"; case "3": System.out.println("---------------------------------------------------------"); System.out.println("You have selected option 3 to issue a book"); LibFunctions.callIssueMenu(); return "3"; case "4": System.out.println("---------------------------------------------------------"); System.out.println("You have selected option 4 to return a book"); LibFunctions.callReturnMenu(); return "4"; default: System.out.println("---------------------------------------------------------"); System.out.println("Thanks for working on this!!"); return "5"; } } } // libraryManagement/LibUtil.java package projecttest.libraryManagement; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author testuser */ public class LibUtil { public static Connection getConnection() { Connection conn = null; try { Properties prop = new Properties(); FileInputStream in = new FileInputStream("src/DBProperties"); prop.load(in); String driverName= prop.getProperty("DBDriver"); Class.forName(driverName); String dbName,user,password; dbName= prop.getProperty("DBName"); user = prop.getProperty("User"); password= prop.getProperty("Password"); conn= DriverManager.getConnection(dbName, user, password); return conn; } catch (Exception e) { } return conn; } } // libraryManagement/AddMemberMenu.java package projecttest.libraryManagement; import java.sql.Connection; import java.sql.Statement; import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author testuser */ public class AddMemberMenu { public static void addMemberMenu() { System.out.println("Reached the add member menu"); Member m = new Member(); Scanner sc = new Scanner(System.in); int addStatus = 0; while (addStatus == 0) { try { System.out.println("Enter the member id "); m.setMemberId(Integer.parseInt(sc.nextLine().toString())); System.out.println("Enter the member name"); m.setMemberName(sc.nextLine().toString()); addMember(m); addStatus = 1; } catch (Exception e) { addStatus=0; } } } public static void addMember(Member m) { System.out.println("Reached inside add member for member "+m.getMemberId()); Connection conn = LibUtil.getConnection(); try { Statement stmt = conn.createStatement(); int k = stmt.executeUpdate("insert into members values ("+m.getMemberId()+",'"+m.getMemberName()+"',sysdate)"); if(k>0){ System.out.println("Added Member successfully"); conn.commit(); }else{ conn.rollback(); } conn.close(); } catch (Exception e) { } } } // libraryManagement/AddBookMenu.java package projecttest.libraryManagement; import java.sql.Connection; import java.sql.Statement; import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author testuser */ public class AddBookMenu { public static void addBookMenu() { System.out.println("Reached the add book menu"); Book b = new Book(); Scanner sc = new Scanner(System.in); int addStatus = 0; while (addStatus == 0) { try { System.out.println("Enter the isbn code"); b.setIsbnCode(sc.nextLine().toString()); System.out.println("Enter the book name"); b.setBookName(sc.nextLine().toString()); System.out.println("Enter the book desc"); b.setBookDesc(sc.nextLine().toString()); System.out.println("Enter the author name"); b.setAuthorName(sc.nextLine().toString()); System.out.println("Enter the subject "); b.setSubjectName(sc.nextLine().toString()); System.out.println("Enter the units available"); b.setUnitsAvailable(Integer.parseInt(sc.nextLine().toString())); addBook(b); addStatus = 1; } catch (Exception e) { addStatus=0; } } } public static void addBook(Book b) { System.out.println("Reached inside addBook for book "+b.getIsbnCode()); Connection conn = LibUtil.getConnection(); try { Statement stmt = conn.createStatement(); int k = stmt.executeUpdate("insert into books values ('"+b.getIsbnCode()+"','"+b.getBookName()+"','"+b.getBookDesc()+"'," + "'"+b.getAuthorName()+"','"+b.getSubjectName()+"',"+b.getUnitsAvailable()+")"); if(k>0){ System.out.println("Added Book successfully"); conn.commit(); }else{ conn.rollback(); } conn.close(); } catch (Exception e) { } } }
7
483
Java
SimpleChat
./ProjectTest/Java/SimpleChat.java
// SimpleChat/Server.java package projecttest.SimpleChat; import java.io.*; import java.net.*; import java.util.*; class VerySimpleChatServer { ArrayList clientOutputStreams; public class ClientHandler implements Runnable { BufferedReader reader; Socket sock; public ClientHandler(Socket clientSocket) { try { sock = clientSocket; InputStreamReader isReader = new InputStreamReader(sock.getInputStream()); reader = new BufferedReader(isReader); } catch (Exception ex) { ex.printStackTrace(); } } // close constructor public void run() { String message; try { while ((message = reader.readLine()) != null) { System.out.println("read " + message); tellEveryone(message); } // close while } catch (Exception ex) { ex.printStackTrace(); } } // close run } // close inner class public static void main(String[] args) { new VerySimpleChatServer().go(); } public void go() { clientOutputStreams = new ArrayList(); try { ServerSocket serverSock = new ServerSocket(5000); while (true) { Socket clientSocket = serverSock.accept(); PrintWriter writer = new PrintWriter(clientSocket.getOutputStream()); clientOutputStreams.add(writer); Thread t = new Thread(new ClientHandler(clientSocket)); t.start(); System.out.println("got a connection"); } } catch (Exception ex) { ex.printStackTrace(); } } // close go public void tellEveryone(String message) { Iterator it = clientOutputStreams.iterator(); while (it.hasNext()) { try { PrintWriter writer = (PrintWriter) it.next(); writer.println(message); writer.flush(); } catch (Exception ex) { ex.printStackTrace(); } } // end while } // close tellEveryone } // close class // SimpleChat/Client.java package projecttest.SimpleChat; import java.io.*; import java.net.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Client { JTextArea incoming; JTextField outgoing; BufferedReader reader; PrintWriter writer; Socket sock; public static void main(String[] args) { Client client = new Client(); client.go(); } public void go() { JFrame frame = new JFrame("Ludicrously Simple Chat Client"); JPanel mainPanel = new JPanel(); incoming = new JTextArea(15, 50); incoming.setLineWrap(true); incoming.setWrapStyleWord(true); incoming.setEditable(false); JScrollPane qScroller = new JScrollPane(incoming); qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); outgoing = new JTextField(20); JButton sendButton = new JButton("Send"); sendButton.addActionListener(new SendButtonListener()); mainPanel.add(qScroller); mainPanel.add(outgoing); mainPanel.add(sendButton); setUpNetworking(); Thread readerThread = new Thread(new IncomingReader()); readerThread.start(); frame.getContentPane().add(BorderLayout.CENTER, mainPanel); frame.setSize(400, 500); frame.setVisible(true); } private void setUpNetworking() { try { sock = new Socket("192.168.5.16", 5000); InputStreamReader streamReader = new InputStreamReader(sock.getInputStream()); reader = new BufferedReader(streamReader); writer = new PrintWriter(sock.getOutputStream()); System.out.println("networking established"); } catch (IOException ex) { ex.printStackTrace(); } } // close setUpNetworking public class SendButtonListener implements ActionListener { public void actionPerformed(ActionEvent ev) { try { writer.println(outgoing.getText()); writer.flush(); } catch (Exception ex) { ex.printStackTrace(); } outgoing.setText(""); outgoing.requestFocus(); } } // close inner class public class IncomingReader implements Runnable { public void run() { String message; try { while ((message = reader.readLine()) != null) { System.out.println("read " + message); incoming.append(message + "\n"); } // close while } catch (Exception ex) { ex.printStackTrace(); } } // close run } }
2
170
Java
springmicrometerundertow
./ProjectTest/Java/springmicrometerundertow.java
// springmicrometerundertow/SpringMicrometerUndertowApplication.java package projecttest.springmicrometerundertow; import io.micrometer.core.instrument.MeterRegistry; import io.undertow.server.HandlerWrapper; import io.undertow.server.handlers.MetricsHandler; import io.undertow.servlet.api.MetricsCollector; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.embedded.undertow.UndertowDeploymentInfoCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class SpringMicrometerUndertowApplication { public static void main(String[] args) { SpringApplication.run(SpringMicrometerUndertowApplication.class, args); } @Bean UndertowDeploymentInfoCustomizer undertowDeploymentInfoCustomizer(UndertowMetricsHandlerWrapper undertowMetricsHandlerWrapper) { return deploymentInfo -> deploymentInfo.addOuterHandlerChainWrapper(undertowMetricsHandlerWrapper); //return deploymentInfo -> deploymentInfo.addOuterHandlerChainWrapper(MetricsHandler.WRAPPER); } @Bean MeterRegistryCustomizer<MeterRegistry> micrometerMeterRegistryCustomizer(@Value("${spring.application.name}") String applicationName) { return registry -> registry.config().commonTags("application.name", applicationName); } @GetMapping(value = "/hello", produces = MediaType.APPLICATION_JSON_VALUE) public String hello(@RequestParam(name = "name", required = true) String name) { return "Hello " + name + "!"; } } // springmicrometerundertow/UndertowMeterBinder.java package projecttest.springmicrometerundertow; import io.micrometer.core.instrument.FunctionCounter; import io.micrometer.core.instrument.FunctionTimer; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.TimeGauge; import io.micrometer.core.instrument.binder.MeterBinder; import io.undertow.server.handlers.MetricsHandler; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; import java.util.function.ToDoubleFunction; import java.util.function.ToLongFunction; @Component public class UndertowMeterBinder implements ApplicationListener<ApplicationReadyEvent> { private final UndertowMetricsHandlerWrapper undertowMetricsHandlerWrapper; public UndertowMeterBinder(UndertowMetricsHandlerWrapper undertowMetricsHandlerWrapper) { this.undertowMetricsHandlerWrapper = undertowMetricsHandlerWrapper; } @Override public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { bindTo(applicationReadyEvent.getApplicationContext().getBean(MeterRegistry.class)); } public void bindTo(MeterRegistry meterRegistry) { bind(meterRegistry, undertowMetricsHandlerWrapper.getMetricsHandler()); } public void bind(MeterRegistry registry, MetricsHandler metricsHandler) { bindTimer(registry, "undertow.requests", "Number of requests", metricsHandler, m -> m.getMetrics().getTotalRequests(), m2 -> m2.getMetrics().getMinRequestTime()); bindTimeGauge(registry, "undertow.request.time.max", "The longest request duration in time", metricsHandler, m -> m.getMetrics().getMaxRequestTime()); bindTimeGauge(registry, "undertow.request.time.min", "The shortest request duration in time", metricsHandler, m -> m.getMetrics().getMinRequestTime()); bindCounter(registry, "undertow.request.errors", "Total number of error requests ", metricsHandler, m -> m.getMetrics().getTotalErrors()); } private void bindTimer(MeterRegistry registry, String name, String desc, MetricsHandler metricsHandler, ToLongFunction<MetricsHandler> countFunc, ToDoubleFunction<MetricsHandler> consumer) { FunctionTimer.builder(name, metricsHandler, countFunc, consumer, TimeUnit.MILLISECONDS) .description(desc).register(registry); } private void bindTimeGauge(MeterRegistry registry, String name, String desc, MetricsHandler metricResult, ToDoubleFunction<MetricsHandler> consumer) { TimeGauge.builder(name, metricResult, TimeUnit.MILLISECONDS, consumer).description(desc) .register(registry); } private void bindCounter(MeterRegistry registry, String name, String desc, MetricsHandler metricsHandler, ToDoubleFunction<MetricsHandler> consumer) { FunctionCounter.builder(name, metricsHandler, consumer).description(desc) .register(registry); } } // springmicrometerundertow/UndertowMetricsHandlerWrapper.java package projecttest.springmicrometerundertow; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.handlers.MetricsHandler; import org.springframework.stereotype.Component; @Component public class UndertowMetricsHandlerWrapper implements HandlerWrapper { private MetricsHandler metricsHandler; @Override public HttpHandler wrap(HttpHandler handler) { metricsHandler = new MetricsHandler(handler); return metricsHandler; } public MetricsHandler getMetricsHandler() { return metricsHandler; } }
3
130
Java
logrequestresponseundertow
./ProjectTest/Java/logrequestresponseundertow.java
// logrequestresponseundertow/Song.java package projecttest.logrequestresponseundertow; import lombok.*; @Getter @Setter @Builder @NoArgsConstructor @AllArgsConstructor public class Song { private Long id; private String name; private String author; } // logrequestresponseundertow/Application.java package projecttest.logrequestresponseundertow; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; import org.springframework.context.annotation.Bean; import io.undertow.server.handlers.RequestDumpingHandler; import lombok.extern.log4j.Log4j2; @SpringBootApplication @Log4j2 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public UndertowServletWebServerFactory undertowServletWebServerFactory() { UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory(); factory.addDeploymentInfoCustomizers(deploymentInfo -> deploymentInfo.addInitialHandlerChainWrapper(handler -> { return new RequestDumpingHandler(handler); })); return factory; } @Bean public UndertowServletWebServerFactory UndertowServletWebServerFactory() { UndertowServletWebServerFactory UndertowServletWebServerFactory = new UndertowServletWebServerFactory(); UndertowServletWebServerFactory.addDeploymentInfoCustomizers(deploymentInfo -> deploymentInfo.addInitialHandlerChainWrapper(handler -> { return new RequestDumpingHandler(handler); })); return UndertowServletWebServerFactory; } } // logrequestresponseundertow/SongController.java package projecttest.logrequestresponseundertow; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.springframework.web.bind.annotation.*; @RestController public class SongController { @PostMapping("/songs") public Song createSong(@RequestBody Song song) { song.setId(new Random().nextLong()); return song; } @GetMapping("/songs") public List<Song> getSongs() { List<Song> songs = new ArrayList<>(); songs.add(Song.builder().id(1L).name("name1").author("author2").build()); songs.add(Song.builder().id(2L).name("name2").author("author2").build()); return songs; } }
3
85
Java
Train
./ProjectTest/Java/Train.java
// Train/Driver.java package projecttest.Train; public class Driver { /** * This testdriver wil test the difrent methods from train and trainstation */ public static void test() { Train t1 = new Train("Aarhus", "Berlin", 999); Train t2 = new Train("Herning", "Copenhagen", 42); Train t3 = new Train("Aarhus", "Herning", 66); Train t4 = new Train("Odense", "Herning", 177); Train t5 = new Train("Aarhus", "Copenhagen", 122); System.out.println("Opgave 3:"); System.out.println("*******************"); System.out.println(t1); System.out.println(t2); System.out.println(t3); System.out.println(t4); System.out.println(t5); System.out.println("*******************"); System.out.println(""); TrainStation ts = new TrainStation("Herning"); ts.addTrain(t1); ts.addTrain(t2); ts.addTrain(t3); ts.addTrain(t4); ts.addTrain(t5); System.out.println("Opgave 8:"); System.out.println("*******************"); System.out.println("No. of trains going from or to Herning:"); System.out.println(ts.connectingTrains()); System.out.println("*******************"); System.out.println(""); System.out.println("Opgave 9:"); System.out.println("*******************"); System.out.println("The cheapest train going to Copenhagen is going:"); System.out.println(ts.cheapTrainTo("Copenhagen")); System.out.println("*******************"); System.out.println(""); System.out.println("Opgave 10:"); System.out.println("*******************"); ts.printTrainStation(); System.out.println("*******************"); System.out.println(""); System.out.println("Opgave 11:"); System.out.println("*******************"); System.out.println("Trains going from Aarhus to Herning:"); for(Train t : ts.trainsFrom("Aarhus")) { System.out.println(t); } System.out.println("*******************"); System.out.println(""); System.out.println("Opgave 12:"); System.out.println("*******************"); System.out.println("The cheapest train going from herning to Copenhagen:"); System.out.println(ts.cheapTrain("Copenhagen")); System.out.println("*******************"); System.out.println(""); } } // Train/TrainStation.java package projecttest.Train; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.Comparator; public class TrainStation { private String city; private ArrayList<Train> trains; public TrainStation(String city) { this.city = city; trains = new ArrayList<Train>(); } /** * this method adds trains tot the ArrayList trains */ public void addTrain(Train t) { trains.add(t); } /** * Method will return the number of trains that starts or ends in the * city of the Trainstation */ public int connectingTrains() { int result = 0; for(Train t : trains) { if(city.equals(t.getDeparture()) || city.equals(t.getDestiantion())) { result ++; } } return result; } /** * This method returns the chepest train go to a spesific destination */ public Train cheapTrainTo(String destination) { Train result = null; for(Train t : trains) { if(destination.equals(t.getDestiantion())) { if(result == null || result.getPrice() > t.getPrice()) { result = t; } } } return result; } /** * This method prints out all trains in the ArrayList trains * in sorted order after the departurs in alphabeticly order * if they have the same departures then it wil sort after price * from lovest til highest */ public void printTrainStation() { Collections.sort(trains); System.out.println("The trainstaion in " + city + " has following trains:"); for(Train t : trains) { System.out.println(t); } } /** * This method will return all trains that starts in a given place * going to the Trainstations city. */ public List<Train> trainsFrom(String departure) { return trains.stream() .filter(t -> t.getDeparture().equals(departure) && t.getDestiantion().equals(city)) .collect(Collectors.toList()); } /** * This method returns the cheapest train strating in the Trainstations * city, and ends in a given destination */ public Train cheapTrain(String destination) { return trains.stream() .filter(t -> t.getDeparture().equals(city) && t.getDestiantion().equals(destination)) .min(Comparator.comparing(t -> t.getPrice())) .orElse(null); } } // Train/Train.java package projecttest.Train; import java.util.Collections; public class Train implements Comparable<Train> { private String departure; private String destination; private int price; public Train(String departure, String destination, int price) { this.departure = departure; this.destination = destination; this.price = price; } /** * A method to get the departure */ public String getDeparture() { return departure; } /** * A method to get the destiantion */ public String getDestiantion() { return destination; } /** * A method to get grice */ public int getPrice() { return price; } /** * This method will format a String of the given way */ public String toString() { return "From " + departure + " to " + destination + " for " + price + " DKK"; } /** * This method sorts departures alphabeticly, if they have the same * departures then it wil sort after price from lovest til highest */ public int compareTo(Train other) { if(!departure.equals(other.departure)) { return departure.compareTo(other.departure); } else { return price - other.price; } } }
3
216
Java
bankingApplication
./ProjectTest/Java/bankingApplication.java
// bankingApplication/bankManagement.java package projecttest.bankingApplication; import java.io.BufferedReader; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLIntegrityConstraintViolationException; import java.sql.Statement; public class bankManagement { // these class provides all // bank method private static final int NULL = 0; static Connection con = connection.getConnection(); static String sql = ""; public static boolean createAccount(String name, int passCode) // create account function { try { // validation if (name == "" || passCode == NULL) { System.out.println("All Field Required!"); return false; } // query Statement st = con.createStatement(); sql = "INSERT INTO customer(cname,balance,pass_code) values('" + name + "',1000," + passCode + ")"; // Execution if (st.executeUpdate(sql) == 1) { System.out.println(name + ", Now You Login!"); return true; } // return } catch (SQLIntegrityConstraintViolationException e) { System.out.println("Username Not Available!"); } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean loginAccount(String name, int passCode) // login method { try { // validation if (name == "" || passCode == NULL) { System.out.println("All Field Required!"); return false; } // query sql = "select * from customer where cname='" + name + "' and pass_code=" + passCode; PreparedStatement st = con.prepareStatement(sql); ResultSet rs = st.executeQuery(); // Execution BufferedReader sc = new BufferedReader( new InputStreamReader(System.in)); if (rs.next()) { // after login menu driven interface method int ch = 5; int amt = 0; int senderAc = rs.getInt("ac_no"); ; int receiveAc; while (true) { try { System.out.println( "Hallo, " + rs.getString("cname")); System.out.println( "1)Transfer Money"); System.out.println("2)View Balance"); System.out.println("5)LogOut"); System.out.print("Enter Choice:"); ch = Integer.parseInt( sc.readLine()); if (ch == 1) { System.out.print( "Enter Receiver A/c No:"); receiveAc = Integer.parseInt( sc.readLine()); System.out.print( "Enter Amount:"); amt = Integer.parseInt( sc.readLine()); if (bankManagement .transferMoney( senderAc, receiveAc, amt)) { System.out.println( "MSG : Money Sent Successfully!\n"); } else { System.out.println( "ERR : Failed!\n"); } } else if (ch == 2) { bankManagement.getBalance( senderAc); } else if (ch == 5) { break; } else { System.out.println( "Err : Enter Valid input!\n"); } } catch (Exception e) { e.printStackTrace(); } } } else { return false; } // return return true; } catch (SQLIntegrityConstraintViolationException e) { System.out.println("Username Not Available!"); } catch (Exception e) { e.printStackTrace(); } return false; } public static void getBalance(int acNo) // fetch balance method { try { // query sql = "select * from customer where ac_no=" + acNo; PreparedStatement st = con.prepareStatement(sql); ResultSet rs = st.executeQuery(sql); System.out.println( "-----------------------------------------------------------"); System.out.printf("%12s %10s %10s\n", "Account No", "Name", "Balance"); // Execution while (rs.next()) { System.out.printf("%12d %10s %10d.00\n", rs.getInt("ac_no"), rs.getString("cname"), rs.getInt("balance")); } System.out.println( "-----------------------------------------------------------\n"); } catch (Exception e) { e.printStackTrace(); } } public static boolean transferMoney(int sender_ac, int reveiver_ac, int amount) throws SQLException // transfer money method { // validation if (reveiver_ac == NULL || amount == NULL) { System.out.println("All Field Required!"); return false; } try { con.setAutoCommit(false); sql = "select * from customer where ac_no=" + sender_ac; PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(); if (rs.next()) { if (rs.getInt("balance") < amount) { System.out.println( "Insufficient Balance!"); return false; } } Statement st = con.createStatement(); // debit con.setSavepoint(); sql = "update customer set balance=balance-" + amount + " where ac_no=" + sender_ac; if (st.executeUpdate(sql) == 1) { System.out.println("Amount Debited!"); } // credit sql = "update customer set balance=balance+" + amount + " where ac_no=" + reveiver_ac; st.executeUpdate(sql); con.commit(); return true; } catch (Exception e) { e.printStackTrace(); con.rollback(); } // return return false; } } // bankingApplication/connection.java package projecttest.bankingApplication; import java.sql.Connection; import java.sql.DriverManager; // Global connection Class public class connection { static Connection con; // Global Connection Object public static Connection getConnection() { try { String mysqlJDBCDriver = "com.mysql.cj.jdbc.Driver"; //jdbc driver String url = "jdbc:mysql://localhost:3306/mydata"; //mysql url String user = "root"; //mysql username String pass = "Pritesh4@"; //mysql passcode Class.forName(mysqlJDBCDriver); con = DriverManager.getConnection(url, user, pass); } catch (Exception e) { System.out.println("Connection Failed!"); } return con; } } // bankingApplication/bank.java package projecttest.bankingApplication; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class bank { public static void main(String args[]) //main class of bank throws IOException { BufferedReader sc = new BufferedReader( new InputStreamReader(System.in)); String name = ""; int pass_code; int ac_no; int ch; while (true) { System.out.println( "\n ->|| Welcome to InBank ||<- \n"); System.out.println("1)Create Account"); System.out.println("2)Login Account"); try { System.out.print("\n Enter Input:"); //user input ch = Integer.parseInt(sc.readLine()); switch (ch) { case 1: try { System.out.print( "Enter Unique UserName:"); name = sc.readLine(); System.out.print( "Enter New Password:"); pass_code = Integer.parseInt( sc.readLine()); if (bankManagement.createAccount( name, pass_code)) { System.out.println( "MSG : Account Created Successfully!\n"); } else { System.out.println( "ERR : Account Creation Failed!\n"); } } catch (Exception e) { System.out.println( " ERR : Enter Valid Data::Insertion Failed!\n"); } break; case 2: try { System.out.print( "Enter UserName:"); name = sc.readLine(); System.out.print( "Enter Password:"); pass_code = Integer.parseInt( sc.readLine()); if (bankManagement.loginAccount( name, pass_code)) { System.out.println( "MSG : Logout Successfully!\n"); } else { System.out.println( "ERR : login Failed!\n"); } } catch (Exception e) { System.out.println( " ERR : Enter Valid Data::Login Failed!\n"); } break; default: System.out.println("Invalid Entry!\n"); } if (ch == 5) { System.out.println( "Exited Successfully!\n\n Thank You :)"); break; } } catch (Exception e) { System.out.println("Enter Valid Entry!"); } } sc.close(); } }
3
357
Java
springuploads3
./ProjectTest/Java/springuploads3.java
// springuploads3/service/StorageService.java package projecttest.springuploads3.service; import org.springframework.web.multipart.MultipartFile; import projecttest.springuploads3.service.model.DownloadedResource; public interface StorageService { String upload(MultipartFile multipartFile); DownloadedResource download(String id); } // springuploads3/service/model/DownloadedResource.java package projecttest.springuploads3.service.model; import lombok.Builder; import lombok.Data; import java.io.InputStream; @Data @Builder public class DownloadedResource { private String id; private String fileName; private Long contentLength; private InputStream inputStream; } // springuploads3/service/S3StorageService.java package projecttest.springuploads3.service; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.S3Object; import projecttest.springuploads3.service.model.DownloadedResource; import lombok.SneakyThrows; @Service public class S3StorageService implements StorageService { private static final String FILE_EXTENSION = "fileExtension"; private final AmazonS3 amazonS3; private final String bucketName; public S3StorageService(AmazonS3 amazonS3, @Value("${aws.s3.bucket-name}") String bucketName) { this.amazonS3 = amazonS3; this.bucketName = bucketName; initializeBucket(); } @SneakyThrows @Override public String upload(MultipartFile multipartFile) { String key = RandomStringUtils.randomAlphanumeric(50); amazonS3.putObject(bucketName, key, multipartFile.getInputStream(), extractObjectMetadata(multipartFile)); return key; } @Override public DownloadedResource download(String id) { S3Object s3Object = amazonS3.getObject(bucketName, id); String filename = id + "." + s3Object.getObjectMetadata().getUserMetadata().get(FILE_EXTENSION); Long contentLength = s3Object.getObjectMetadata().getContentLength(); return DownloadedResource.builder().id(id).fileName(filename).contentLength(contentLength).inputStream(s3Object.getObjectContent()) .build(); } private ObjectMetadata extractObjectMetadata(MultipartFile file) { ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(file.getSize()); objectMetadata.setContentType(file.getContentType()); objectMetadata.getUserMetadata().put(FILE_EXTENSION, FilenameUtils.getExtension(file.getOriginalFilename())); return objectMetadata; } private void initializeBucket() { if (!amazonS3.doesBucketExistV2(bucketName)) { amazonS3.createBucket(bucketName); } } } // springuploads3/controller/FileUploadController.java package projecttest.springuploads3.controller; import projecttest.springuploads3.service.StorageService; import lombok.extern.log4j.Log4j2; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller @Log4j2 public class FileUploadController { private final StorageService storageService; public FileUploadController(StorageService storageService) { this.storageService = storageService; } @PostMapping(value = "/upload", produces = "application/json") public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) { String key = storageService.upload(file); return new ResponseEntity<>(key, HttpStatus.OK); } } // springuploads3/controller/FileDownloadController.java package projecttest.springuploads3.controller; import projecttest.springuploads3.service.model.DownloadedResource; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import projecttest.springuploads3.service.StorageService; import lombok.extern.log4j.Log4j2; @Controller @Log4j2 public class FileDownloadController { private final StorageService storageService; public FileDownloadController(StorageService storageService) { this.storageService = storageService; } @GetMapping("/download") public ResponseEntity<Resource> download(String id) { DownloadedResource downloadedResource = storageService.download(id); return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + downloadedResource.getFileName()) .contentLength(downloadedResource.getContentLength()).contentType(MediaType.APPLICATION_OCTET_STREAM) .body(new InputStreamResource(downloadedResource.getInputStream())); } } // springuploads3/SpringUploadS3Application.java package projecttest.springuploads3; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringUploadS3Application { public static void main(String[] args) { SpringApplication.run(SpringUploadS3Application.class, args); } } // springuploads3/configuration/S3ClientConfiguration.java package projecttest.springuploads3.configuration; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; @Configuration public class S3ClientConfiguration { @Value("${aws.s3.endpoint-url}") private String endpointUrl; @Bean AmazonS3 amazonS3() { AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(endpointUrl, Regions.US_EAST_1.getName()); return AmazonS3ClientBuilder.standard().withEndpointConfiguration(endpointConfiguration).withPathStyleAccessEnabled(true).build(); } }
7
192
Java
CalculatorOOPS
./ProjectTest/Java/CalculatorOOPS.java
// CalculatorOOPS/Divide.java package projecttest.CalculatorOOPS; public class Divide implements Operate { @Override public Double getResult(Double... numbers){ Double div = numbers[0]; for(int i=1;i< numbers.length;i++){ div /= numbers[i]; } return div; } } // CalculatorOOPS/Modulus.java package projecttest.CalculatorOOPS; public class Modulus implements Operate{ @Override public Double getResult(Double... numbers){ Double mod = numbers[0]; for (int i = 1; i < numbers.length; i++) { mod %= numbers[i]; } return mod; } } // CalculatorOOPS/ReadInput.java package projecttest.CalculatorOOPS; import java.util.Scanner; public class ReadInput { public static String read(){ Scanner scanner = new Scanner(System.in); System.out.println("Input Expression Example: 4*3/2"); String inputLine = scanner.nextLine(); scanner.close(); return inputLine; } } // CalculatorOOPS/Operate.java package projecttest.CalculatorOOPS; public interface Operate { Double getResult(Double... numbers); } // CalculatorOOPS/Add.java package projecttest.CalculatorOOPS; public class Add implements Operate{ @Override public Double getResult(Double... numbers){ Double sum = 0.0; for(Double num: numbers){ sum += num; } return sum; } } // CalculatorOOPS/Sub.java package projecttest.CalculatorOOPS; public class Sub implements Operate{ @Override public Double getResult(Double... numbers){ Double sub = numbers[0]; for(int i=1;i< numbers.length;i++){ sub -= numbers[i]; } return sub; } } // CalculatorOOPS/Multiply.java package projecttest.CalculatorOOPS; public class Multiply implements Operate { @Override public Double getResult(Double... numbers){ Double mul = 1.0; for(Double num: numbers){ mul *= num; } return mul; } } // CalculatorOOPS/Calculator.java package projecttest.CalculatorOOPS; import java.util.Arrays; import java.util.LinkedList; import java.util.Objects; import java.util.Queue; public class Calculator { public static void main(String[] args){ final String inputExp = ReadInput.read(); Queue<String> operations; Queue<String> numbers; String[] numbersArr = inputExp.split("[-+*/%]"); // String[] operArr = inputExp.split("[0-9]+"); String[] operArr = inputExp.split("\\d+"); numbers = new LinkedList<>(Arrays.asList(numbersArr)); operations = new LinkedList<>(Arrays.asList(operArr)); Double res = Double.parseDouble(Objects.requireNonNull(numbers.poll())); while(!numbers.isEmpty()){ String opr = operations.poll(); Operate operate; switch(Objects.requireNonNull(opr)){ case "+": operate = new Add(); break; case "-": operate = new Sub(); break; case "*": operate = new Multiply(); break; case "/": operate = new Divide(); break; case "%": operate = new Modulus(); break; default: continue; } Double num = Double.parseDouble(Objects.requireNonNull(numbers.poll())); res = operate.getResult(res, num); } System.out.println(res); } }
8
138
Java
passwordGenerator
./ProjectTest/Java/passwordGenerator.java
// passwordGenerator/GeneratorTest.java package projecttest.passwordGenerator; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class GeneratorTest { private final Password password= new Password("Secret"); private final Alphabet firstAlphabet = new Alphabet(true,false,false,false); private final Alphabet secondAlphabet = new Alphabet(false,true,true,true); private final Generator generator = new Generator(true,false,false,false); // private final Password generatedPassword = generator.GeneratePassword(4); @Test void test1() { assertEquals("Secret", password.toString()); } @Test void test2() { assertEquals(firstAlphabet.getAlphabet(), Alphabet.UPPERCASE_LETTERS); } @Test void test3() { assertEquals(secondAlphabet.getAlphabet(), Alphabet.LOWERCASE_LETTERS + Alphabet.NUMBERS + Alphabet.SYMBOLS); } @Test void test4() { assertEquals(generator.alphabet.getAlphabet(), Alphabet.UPPERCASE_LETTERS); } @Test void test5() { assertEquals(generator.alphabet.getAlphabet().length(), 26); } } // passwordGenerator/Main.java package projecttest.passwordGenerator; import java.util.Scanner; public class Main { public static final Scanner keyboard = new Scanner(System.in); public static void main(String[] args) { Generator generator = new Generator(keyboard); generator.mainLoop(); keyboard.close(); } } // passwordGenerator/Generator.java package projecttest.passwordGenerator; import java.util.Objects; import java.util.Scanner; public class Generator { Alphabet alphabet; public static Scanner keyboard; public Generator(Scanner scanner) { keyboard = scanner; } public Generator(boolean IncludeUpper, boolean IncludeLower, boolean IncludeNum, boolean IncludeSym) { alphabet = new Alphabet(IncludeUpper, IncludeLower, IncludeNum, IncludeSym); } public void mainLoop() { System.out.println("Welcome to Ziz Password Services :)"); printMenu(); String userOption = "-1"; while (!userOption.equals("4")) { userOption = keyboard.next(); switch (userOption) { case "1": { requestPassword(); printMenu(); } case "2": { checkPassword(); printMenu(); } case "3": { printUsefulInfo(); printMenu(); } case "4": printQuitMessage(); default: { System.out.println(); System.out.println("Kindly select one of the available commands"); printMenu(); } } } } private Password GeneratePassword(int length) { final StringBuilder pass = new StringBuilder(""); final int alphabetLength = alphabet.getAlphabet().length(); int max = alphabetLength - 1; int min = 0; int range = max - min + 1; for (int i = 0; i < length; i++) { int index = (int) (Math.random() * range) + min; pass.append(alphabet.getAlphabet().charAt(index)); } return new Password(pass.toString()); } private void printUsefulInfo() { System.out.println(); System.out.println("Use a minimum password length of 8 or more characters if permitted"); System.out.println("Include lowercase and uppercase alphabetic characters, numbers and symbols if permitted"); System.out.println("Generate passwords randomly where feasible"); System.out.println("Avoid using the same password twice (e.g., across multiple user accounts and/or software systems)"); System.out.println("Avoid character repetition, keyboard patterns, dictionary words, letter or number sequences," + "\nusernames, relative or pet names, romantic links (current or past) " + "and biographical information (e.g., ID numbers, ancestors' names or dates)."); System.out.println("Avoid using information that the user's colleagues and/or " + "acquaintances might know to be associated with the user"); System.out.println("Do not use passwords which consist wholly of any simple combination of the aforementioned weak components"); } private void requestPassword() { boolean IncludeUpper = false; boolean IncludeLower = false; boolean IncludeNum = false; boolean IncludeSym = false; boolean correctParams = false; System.out.println(); System.out.println("Hello, welcome to the Password Generator :) answer" + " the following questions by Yes or No \n"); do { System.out.println("Do you want Lowercase letters \"abcd...\" to be used? "); String input = keyboard.nextLine(); if (isInclude(input)) IncludeLower = true; System.out.println("Do you want Uppercase letters \"ABCD...\" to be used? "); input = keyboard.nextLine(); if (isInclude(input)) IncludeUpper = true; System.out.println("Do you want Numbers \"1234...\" to be used? "); input = keyboard.nextLine(); if (isInclude(input)) IncludeNum = true; System.out.println("Do you want Symbols \"!@#$...\" to be used? "); input = keyboard.nextLine(); if (isInclude(input)) IncludeSym = true; //No Pool Selected if (!IncludeUpper && !IncludeLower && !IncludeNum && !IncludeSym) { System.out.println("You have selected no characters to generate your " + "password at least one of your answers should be Yes"); correctParams = true; } System.out.println("Great! Now enter the length of the password"); int length = keyboard.nextInt(); final Generator generator = new Generator(IncludeUpper, IncludeLower, IncludeNum, IncludeSym); final Password password = generator.GeneratePassword(length); System.err.println("Your generated password -> " + password); } while (correctParams); } private boolean isInclude(String Input) { if (Input.equalsIgnoreCase("yes")) { return true; } else { if (!Input.equalsIgnoreCase("no")) { PasswordRequestError(); } return false; } } private void PasswordRequestError() { System.out.println("You have entered something incorrect let's go over it again \n"); } private void checkPassword() { String input; final Scanner in = new Scanner(System.in); System.out.print("\nEnter your password:"); input = in.nextLine(); final Password p = new Password(input); System.out.println(p.calculateScore()); in.close(); } private void printMenu() { System.out.println(); System.out.println("Enter 1 - Password Generator"); System.out.println("Enter 2 - Password Strength Check"); System.out.println("Enter 3 - Useful Information"); System.out.println("Enter 4 - Quit"); System.out.print("Choice:"); } private void printQuitMessage() { System.out.println("Closing the program bye bye!"); } } // passwordGenerator/Alphabet.java package projecttest.passwordGenerator; public class Alphabet { public static final String UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz"; public static final String NUMBERS = "1234567890"; public static final String SYMBOLS = "!@#$%^&*()-_=+\\/~?"; private final StringBuilder pool; public Alphabet(boolean uppercaseIncluded, boolean lowercaseIncluded, boolean numbersIncluded, boolean specialCharactersIncluded) { pool = new StringBuilder(); if (uppercaseIncluded) pool.append(UPPERCASE_LETTERS); if (lowercaseIncluded) pool.append(LOWERCASE_LETTERS); if (numbersIncluded) pool.append(NUMBERS); if (specialCharactersIncluded) pool.append(SYMBOLS); } public String getAlphabet() { return pool.toString(); } } // passwordGenerator/Password.java package projecttest.passwordGenerator; public class Password { String Value; int Length; public Password(String s) { Value = s; Length = s.length(); } public int CharType(char C) { int val; // Char is Uppercase Letter if ((int) C >= 65 && (int) C <= 90) val = 1; // Char is Lowercase Letter else if ((int) C >= 97 && (int) C <= 122) { val = 2; } // Char is Digit else if ((int) C >= 60 && (int) C <= 71) { val = 3; } // Char is Symbol else { val = 4; } return val; } public int PasswordStrength() { String s = this.Value; boolean UsedUpper = false; boolean UsedLower = false; boolean UsedNum = false; boolean UsedSym = false; int type; int Score = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); type = CharType(c); if (type == 1) UsedUpper = true; if (type == 2) UsedLower = true; if (type == 3) UsedNum = true; if (type == 4) UsedSym = true; } if (UsedUpper) Score += 1; if (UsedLower) Score += 1; if (UsedNum) Score += 1; if (UsedSym) Score += 1; if (s.length() >= 8) Score += 1; if (s.length() >= 16) Score += 1; return Score; } public String calculateScore() { int Score = this.PasswordStrength(); if (Score == 6) { return "This is a very good password :D check the Useful Information section to make sure it satisfies the guidelines"; } else if (Score >= 4) { return "This is a good password :) but you can still do better"; } else if (Score >= 3) { return "This is a medium password :/ try making it better"; } else { return "This is a weak password :( definitely find a new one"; } } @Override public String toString() { return Value; } }
5
344
Java
springdatamongowithcluster
./ProjectTest/Java/springdatamongowithcluster.java
// springdatamongowithcluster/SpringDataMongoWithClusterApplication.java package projecttest.springdatamongowithcluster; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Query; import lombok.extern.log4j.Log4j2; @SpringBootApplication @Log4j2 public class SpringDataMongoWithClusterApplication implements CommandLineRunner { @Autowired MongoTemplate mongoTemplate; public static void main(String[] args) { SpringApplication.run(SpringDataMongoWithClusterApplication.class, args); } @Override public void run(String... args) { mongoTemplate.dropCollection(Car.class); mongoTemplate.save(Car.builder().name("Tesla Model S").build()); mongoTemplate.save(Car.builder().name("Tesla Model 3").build()); log.info("-------------------------------"); log.info("Cards found: " + mongoTemplate.count(new Query(), Car.class)); log.info("-------------------------------"); } } // springdatamongowithcluster/Car.java package projecttest.springdatamongowithcluster; import org.springframework.data.annotation.Id; import lombok.Builder; @Builder public class Car { @Id private String id; private String name; }
2
51
Java
idcenter
./ProjectTest/Java/idcenter.java
// idcenter/IdWorker.java package projecttest.idcenter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; /** * from https://github.com/twitter/snowflake/blob/master/src/main/scala/com/twitter/service/snowflake/IdWorker.scala * * @author adyliu ([email protected]) * @since 1.0 */ public class IdWorker { private final long workerId; private final long datacenterId; private final long idepoch; private static final long workerIdBits = 5L; private static final long datacenterIdBits = 5L; private static final long maxWorkerId = -1L ^ (-1L << workerIdBits); private static final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); private static final long sequenceBits = 12L; private static final long workerIdShift = sequenceBits; private static final long datacenterIdShift = sequenceBits + workerIdBits; private static final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; private static final long sequenceMask = -1L ^ (-1L << sequenceBits); private long lastTimestamp = -1L; private long sequence; private static final Random r = new Random(); public IdWorker() { this(1344322705519L); } public IdWorker(long idepoch) { this(r.nextInt((int) maxWorkerId), r.nextInt((int) maxDatacenterId), 0, idepoch); } public IdWorker(long workerId, long datacenterId, long sequence) { this(workerId, datacenterId, sequence, 1344322705519L); } // public IdWorker(long workerId, long datacenterId, long sequence, long idepoch) { this.workerId = workerId; this.datacenterId = datacenterId; this.sequence = sequence; this.idepoch = idepoch; if (workerId < 0 || workerId > maxWorkerId) { throw new IllegalArgumentException("workerId is illegal: " + workerId); } if (datacenterId < 0 || datacenterId > maxDatacenterId) { throw new IllegalArgumentException("datacenterId is illegal: " + workerId); } if (idepoch >= System.currentTimeMillis()) { throw new IllegalArgumentException("idepoch is illegal: " + idepoch); } } public long getDatacenterId() { return datacenterId; } public long getWorkerId() { return workerId; } public long getTime() { return System.currentTimeMillis(); } public long getId() { long id = nextId(); return id; } private synchronized long nextId() { long timestamp = timeGen(); if (timestamp < lastTimestamp) { throw new IllegalStateException("Clock moved backwards."); } if (lastTimestamp == timestamp) { sequence = (sequence + 1) & sequenceMask; if (sequence == 0) { timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0; } lastTimestamp = timestamp; long id = ((timestamp - idepoch) << timestampLeftShift)// | (datacenterId << datacenterIdShift)// | (workerId << workerIdShift)// | sequence; return id; } /** * get the timestamp (millis second) of id * @param id the nextId * @return the timestamp of id */ public long getIdTimestamp(long id) { return idepoch + (id >> timestampLeftShift); } private long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } private long timeGen() { return System.currentTimeMillis(); } @Override public String toString() { final StringBuilder sb = new StringBuilder("IdWorker{"); sb.append("workerId=").append(workerId); sb.append(", datacenterId=").append(datacenterId); sb.append(", idepoch=").append(idepoch); sb.append(", lastTimestamp=").append(lastTimestamp); sb.append(", sequence=").append(sequence); sb.append('}'); return sb.toString(); } } // idcenter/Base62.java package projecttest.idcenter; /** * A Base62 method * * @author adyliu ([email protected]) * @since 1.0 */ public class Base62 { private static final String baseDigits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final int BASE = baseDigits.length(); private static final char[] digitsChar = baseDigits.toCharArray(); private static final int FAST_SIZE = 'z'; private static final int[] digitsIndex = new int[FAST_SIZE + 1]; static { for (int i = 0; i < FAST_SIZE; i++) { digitsIndex[i] = -1; } // for (int i = 0; i < BASE; i++) { digitsIndex[digitsChar[i]] = i; } } public static long decode(String s) { long result = 0L; long multiplier = 1; for (int pos = s.length() - 1; pos >= 0; pos--) { int index = getIndex(s, pos); result += index * multiplier; multiplier *= BASE; } return result; } public static String encode(long number) { if (number < 0) throw new IllegalArgumentException("Number(Base62) must be positive: " + number); if (number == 0) return "0"; StringBuilder buf = new StringBuilder(); while (number != 0) { buf.append(digitsChar[(int) (number % BASE)]); number /= BASE; } return buf.reverse().toString(); } private static int getIndex(String s, int pos) { char c = s.charAt(pos); if (c > FAST_SIZE) { throw new IllegalArgumentException("Unknow character for Base62: " + s); } int index = digitsIndex[c]; if (index == -1) { throw new IllegalArgumentException("Unknow character for Base62: " + s); } return index; } } // idcenter/Main.java package projecttest.idcenter; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[] args) { if (args.length != 3) { System.err.println("Usage: java -jar idcenter.jar <subcommand> <num> <output>"); System.err.println("Subcommands\nidworker: Sequential ID Creation\nsidworker: Timestamp-based ID Creation"); return; } String subcommand = args[0]; int num = Integer.parseInt(args[1]); String output = args[2]; if (subcommand.equals("idworker")) { final long idepo = System.currentTimeMillis() - 3600 * 1000L; IdWorker iw = new IdWorker(1, 1, 0, idepo); IdWorker iw2 = new IdWorker(idepo); try (BufferedWriter writer = new BufferedWriter(new FileWriter(output))) { for (int i = 0; i < num; i++) { long id = iw.getId(); long idTimeStamp = iw.getIdTimestamp(id); long id2 = iw2.getId(); long idTimeStamp2 = iw2.getIdTimestamp(id2); writer.write("IdWorker1: " + id + ", timestamp: " + idTimeStamp + "\n"); writer.write("IdWorker2: " + id2 + ", timestamp: " + idTimeStamp2 + "\n"); } } catch (IOException e) { e.printStackTrace(); } } else if (subcommand.equals("sidworker")) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(output))) { for (int i = 0; i < num; i++) { long sid = SidWorker.nextSid(); writer.write("SidWorker: " + sid + "\n"); } } catch (IOException e) { e.printStackTrace(); } } else { System.err.println("Usage: java -jar idcenter.jar <subcommand> <num> <output>"); System.err.println("Subcommands\nidworker: Sequential ID Creation\nsidworker: Timestamp-based ID Creation"); } } } // idcenter/SidWorker.java package projecttest.idcenter; import java.text.SimpleDateFormat; import java.util.Date; /** * generator of 19 bits number with timestamp * * @author adyliu ([email protected]) * @since 2016-06-28 */ public class SidWorker { private static long lastTimestamp = -1L; private static int sequence = 0; private static final long MAX_SEQUENCE = 100; private static final SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS"); /** * 19 bits number with timestamp (20160628175532000002) * * @return 19 bits number with timestamp */ public static synchronized long nextSid() { long now = timeGen(); if (now == lastTimestamp) { if (sequence++ > MAX_SEQUENCE) { now = tilNextMillis(lastTimestamp); sequence = 0; } } else { sequence = 0; } lastTimestamp = now; // return 100L * Long.parseLong(format.format(new Date(now))) + sequence; } private static long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } private static long timeGen() { return System.currentTimeMillis(); } }
4
295
Java
PongGame
./ProjectTest/Java/PongGame.java
// PongGame/Score.java package projecttest.PongGame; import java.awt.*; public class Score extends Rectangle{ static int GAME_WIDTH; static int GAME_HEIGHT; int player1; int player2; Score(int GAME_WIDTH, int GAME_HEIGHT){ Score.GAME_WIDTH = GAME_WIDTH; Score.GAME_HEIGHT=GAME_HEIGHT; } public void draw(Graphics g){ g.setColor(Color.white); g.setFont(new Font("Consolas", Font.PLAIN,60)); g.drawLine(GAME_WIDTH/2,0,GAME_WIDTH/2,GAME_HEIGHT); g.drawString(String.valueOf(player1/10)+String.valueOf(player1%10), (GAME_WIDTH/2)-85, 50); g.drawString(String.valueOf(player2/10)+String.valueOf(player2%10), (GAME_WIDTH/2)+20, 50); } } // PongGame/GameFrame.java package projecttest.PongGame; import java.awt.*; import javax.swing.*; public class GameFrame extends JFrame{ GamePanel panel; GameFrame(){ panel = new GamePanel(); this.add(panel); this.setTitle("Pong Game"); this.setResizable(false); this.setBackground(Color.black); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.pack(); this.setVisible(true); this.setLocationRelativeTo(null); } } // PongGame/Paddle.java package projecttest.PongGame; import java.awt.*; import java.awt.event.*; public class Paddle extends Rectangle{ int id; int yVelocity; int speed=10; Paddle(int x, int y, int PADDLE_WIDTH, int PADDLE_HEIGHT, int id){ super(x,y,PADDLE_WIDTH,PADDLE_HEIGHT); this.id=id; } public void keyPressed(KeyEvent e){ switch (id){ case 1: if(e.getKeyCode()==KeyEvent.VK_W){ setYDirection(-speed); move(); } if(e.getKeyCode()==KeyEvent.VK_S){ setYDirection(speed); move(); } break; case 2: if(e.getKeyCode()==KeyEvent.VK_UP){ setYDirection(-speed); move(); } if(e.getKeyCode()==KeyEvent.VK_DOWN){ setYDirection(speed); move(); } break; } } public void keyReleased(KeyEvent e){ switch (id){ case 1: if(e.getKeyCode()==KeyEvent.VK_W){ setYDirection(0); move(); } if(e.getKeyCode()==KeyEvent.VK_S){ setYDirection(0); move(); } break; case 2: if(e.getKeyCode()==KeyEvent.VK_UP){ setYDirection(0); move(); } if(e.getKeyCode()==KeyEvent.VK_DOWN){ setYDirection(0); move(); } break; } } public void setYDirection(int yDirection){ yVelocity = yDirection; } public void move(){ y=y+yVelocity; } public void draw(Graphics g){ if (id==1) g.setColor(Color.BLUE); else g.setColor(Color.red); g.fillRect(x, y, width, height); } } // PongGame/PongGame.java package projecttest.PongGame; public class PongGame { public static void main(String[] args) { GameFrame frame = new GameFrame(); } } // PongGame/Ball.java package projecttest.PongGame; import java.awt.*; import java.util.*; public class Ball extends Rectangle{ Random random; int xVelocity; int yVelocity; int initialSpeed = 4 ; Ball(int x, int y, int width, int height){ super(x, y, width, height); random = new Random(); int randomXDirection = random.nextInt(2); if(randomXDirection==0) randomXDirection--; setXDirection(randomXDirection*initialSpeed); int randomYDirection = random.nextInt(2); if(randomYDirection==0) randomYDirection--; setXDirection(randomYDirection*initialSpeed); } public void setXDirection(int randomXDirection){ xVelocity = randomXDirection; } public void setYDirection(int randomYDirection){ yVelocity=randomYDirection; } public void move(){ x+=xVelocity; y+=yVelocity; } public void draw(Graphics g){ g.setColor(Color.white); g.fillOval(x, y, height, width); } } // PongGame/GamePanel.java package projecttest.PongGame; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class GamePanel extends JPanel implements Runnable{ static final int GAME_WIDTH = 1000; static final int GAME_HEIGHT = (int)(GAME_WIDTH * (0.5555)); static final Dimension SCREEN_SIZE = new Dimension(GAME_WIDTH,GAME_HEIGHT); static final int BALL_DIAMETER = 20; static final int PADDLE_WIDTH = 25; static final int PADDLE_HEIGHT = 100; Thread gameThread; Image image; Graphics graphics; Random random; Paddle paddle1; Paddle paddle2; Ball ball; Score score; GamePanel(){ newPaddles(); newBall(); score = new Score(GAME_WIDTH,GAME_HEIGHT); this.setFocusable(true); this.addKeyListener(new AL()); this.setPreferredSize(SCREEN_SIZE); gameThread = new Thread(this); gameThread.start(); } public void newBall() { random = new Random(); ball = new Ball((GAME_WIDTH/2)-(BALL_DIAMETER/2),random.nextInt(GAME_HEIGHT-BALL_DIAMETER),BALL_DIAMETER,BALL_DIAMETER); } public void newPaddles() { paddle1 = new Paddle(0,(GAME_HEIGHT/2)-(PADDLE_HEIGHT/2),PADDLE_WIDTH,PADDLE_HEIGHT,1); paddle2 = new Paddle(GAME_WIDTH-PADDLE_WIDTH,(GAME_HEIGHT/2)-(PADDLE_HEIGHT/2),PADDLE_WIDTH,PADDLE_HEIGHT,2); } public void paint(Graphics g) { image = createImage(getWidth(),getHeight()); graphics = image.getGraphics(); draw(graphics); g.drawImage(image,0,0,this); } public void draw(Graphics g) { paddle1.draw(g); paddle2.draw(g); ball.draw(g); score.draw(g); Toolkit.getDefaultToolkit().sync(); // I forgot to add this line of code in the video, it helps with the animation } public void move() { paddle1.move(); paddle2.move(); ball.move(); } public void checkCollision() { //bounce ball off top & bottom window edges if(ball.y <=0) { ball.setYDirection(-ball.yVelocity); } if(ball.y >= GAME_HEIGHT-BALL_DIAMETER) { ball.setYDirection(-ball.yVelocity); } //bounce ball off paddles if(ball.intersects(paddle1)) { ball.xVelocity = Math.abs(ball.xVelocity); ball.xVelocity++; //optional for more difficulty if(ball.yVelocity>0) ball.yVelocity++; //optional for more difficulty else ball.yVelocity--; ball.setXDirection(ball.xVelocity); ball.setYDirection(ball.yVelocity); } if(ball.intersects(paddle2)) { ball.xVelocity = Math.abs(ball.xVelocity); ball.xVelocity++; //optional for more difficulty if(ball.yVelocity>0) ball.yVelocity++; //optional for more difficulty else ball.yVelocity--; ball.setXDirection(-ball.xVelocity); ball.setYDirection(ball.yVelocity); } //stops paddles at window edges if(paddle1.y<=0) paddle1.y=0; if(paddle1.y >= (GAME_HEIGHT-PADDLE_HEIGHT)) paddle1.y = GAME_HEIGHT-PADDLE_HEIGHT; if(paddle2.y<=0) paddle2.y=0; if(paddle2.y >= (GAME_HEIGHT-PADDLE_HEIGHT)) paddle2.y = GAME_HEIGHT-PADDLE_HEIGHT; //give a player 1 point and creates new paddles & ball if(ball.x <=0) { score.player2++; newPaddles(); newBall(); System.out.println("Player 2: "+score.player2); } if(ball.x >= GAME_WIDTH-BALL_DIAMETER) { score.player1++; newPaddles(); newBall(); System.out.println("Player 1: "+score.player1); } } public void run() { //game loop long lastTime = System.nanoTime(); double amountOfTicks =60.0; double ns = 1000000000 / amountOfTicks; double delta = 0; while(true) { long now = System.nanoTime(); delta += (now -lastTime)/ns; lastTime = now; if(delta >=1) { move(); checkCollision(); repaint(); delta--; } } } public class AL extends KeyAdapter{ public void keyPressed(KeyEvent e) { paddle1.keyPressed(e); paddle2.keyPressed(e); } public void keyReleased(KeyEvent e) { paddle1.keyReleased(e); paddle2.keyReleased(e); } } }
6
321
Java
Actor_relationship_game
./ProjectTest/Java/Actor_relationship_game.java
// Actor_relationship_game/GraphCreation.java package projecttest.Actor_relationship_game; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class GraphCreation { private final TMDBApi tmdbApi; private final ActorGraph actorGraph; public GraphCreation() { this.tmdbApi = new TMDBApi(); this.actorGraph = new ActorGraph(); } public void createGraph(String fileName) throws IOException { populateGraphWithActors(); saveGraphToFile(fileName); } private void populateGraphWithActors() throws IOException { String popularActorsJson = tmdbApi.searchPopularActors(); JsonArray actorsArray = JsonParser.parseString(popularActorsJson) .getAsJsonObject().getAsJsonArray("results"); for (JsonElement actorElement : actorsArray) { processActorElement(actorElement); } } private void processActorElement(JsonElement actorElement) throws IOException { JsonObject actorObject = actorElement.getAsJsonObject(); String actorId = actorObject.get("id").getAsString(); String actorName = actorObject.get("name").getAsString(); Actor actor = new Actor(actorId, actorName); actorGraph.addActor(actor); populateGraphWithMoviesForActor(actorId); } private void populateGraphWithMoviesForActor(String actorId) throws IOException { String moviesJson = tmdbApi.getMoviesByActorId(actorId); JsonArray moviesArray = JsonParser.parseString(moviesJson) .getAsJsonObject().getAsJsonArray("cast"); for (JsonElement movieElement : moviesArray) { processMovieElement(movieElement, actorId); } } private void processMovieElement(JsonElement movieElement, String actorId) { JsonObject movieObject = movieElement.getAsJsonObject(); String movieId = movieObject.get("id").getAsString(); String movieTitle = movieObject.get("title").getAsString(); Movie movie = new Movie(movieId, movieTitle); actorGraph.addMovie(movie); actorGraph.addActorToMovie(actorId, movieId); } private void saveGraphToFile(String fileName) throws IOException { try (FileOutputStream fileOut = new FileOutputStream(fileName); ObjectOutputStream out = new ObjectOutputStream(fileOut)) { out.writeObject(actorGraph); System.out.println("Serialized data is saved in "+fileName); } } public static void main(String[] args) { try { String fileName = args[0]; new GraphCreation().createGraph(fileName); } catch (IOException e) { e.printStackTrace(); } } } // Actor_relationship_game/Actor.java package projecttest.Actor_relationship_game; import java.io.Serializable; import java.util.HashSet; import java.util.Set; public class Actor implements Serializable{ private static final long serialVersionUID=1L; private String id; private String name; private Set<String> movieIds; // Store movie IDs public Actor(String id, String name) { this.id = id; this.name = name; this.movieIds = new HashSet<>(); } // Getters and setters public Set<String> getMovieIds() { return movieIds; } public String getId() { return id; } public String getName() { return name; } public void setId(String id) { this.id = id; } public void setMovieIds(Set<String> movieIds) { this.movieIds = movieIds; } public void setName(String name) { this.name = name; } } // Actor_relationship_game/ActorGraph.java package projecttest.Actor_relationship_game; import java.io.Serializable; import java.util.*; public class ActorGraph implements Serializable { private static final long serialVersionUID=1L; private Map<String, Actor> actors; private Map<String, Movie> movies; private Map<String, String> nameToIdMap; private Map<String, String> idToNameMap; public ActorGraph() { this.actors = new HashMap<>(); this.movies = new HashMap<>(); this.nameToIdMap = new HashMap<>(); this.idToNameMap = new HashMap<>(); } // getters public Map<String, Actor> getActors() { return actors; } public Map<String, Movie> getMovies() { return movies; } public Map<String, String> getIdToNameMap() { return idToNameMap; } public Map<String, String> getNameToIdMap() { return nameToIdMap; } public static long getSerialVersionUID() { return serialVersionUID; } // Methods public void addActor(Actor actor) { actors.putIfAbsent(actor.getId(), actor); nameToIdMap.put(actor.getName(), actor.getId()); idToNameMap.put(actor.getId(), actor.getName()); } public void addMovie(Movie movie) { movies.putIfAbsent(movie.getId(), movie); } public String getActorIdByName(String name) { return nameToIdMap.get(name); } public String getActorNameById(String id) { return idToNameMap.get(id); } public List<String> getAllActorNames() { return new ArrayList<>(nameToIdMap.keySet()); } /** * This connects an actor to a movie. * It's useful for building the graph based on TMDB API data. */ public void addActorToMovie(String actorId, String movieId) { if (actors.containsKey(actorId) && movies.containsKey(movieId)) { Actor actor = actors.get(actorId); Movie movie = movies.get(movieId); actor.getMovieIds().add(movieId); movie.getActorIds().add(actorId); } } /** * Implements BFS to find the shortest path from startActorId to endActorId. * It uses a queue for BFS and a map (visited) to track the visited actors and their previous actor in the path. */ public List<Map.Entry<String, String>> findConnectionWithPath(String startActorId, String endActorId) { if (!actors.containsKey(startActorId) || !actors.containsKey(endActorId)) { return Collections.emptyList(); } Queue<String> queue = new LinkedList<>(); Map<String, String> visited = new HashMap<>(); Map<String, String> previousMovie = new HashMap<>(); queue.add(startActorId); visited.put(startActorId, null); while (!queue.isEmpty()) { String currentActorId = queue.poll(); Actor currentActor = actors.get(currentActorId); for (String movieId : currentActor.getMovieIds()) { Movie movie = movies.get(movieId); for (String coActorId : movie.getActorIds()) { if (!visited.containsKey(coActorId)) { visited.put(coActorId, currentActorId); previousMovie.put(coActorId, movieId); queue.add(coActorId); if (coActorId.equals(endActorId)) { return buildPath(visited, previousMovie, endActorId); } } } } } return Collections.emptyList(); } /** * Helper method to construct the path from the endActorId back to the startActorId using the visited map. */ private List<Map.Entry<String, String>> buildPath(Map<String, String> visited, Map<String, String> previousMovie, String endActorId) { LinkedList<Map.Entry<String, String>> path = new LinkedList<>(); String current = endActorId; while (current != null) { String movieId = previousMovie.get(current); String movieName = (movieId != null) ? movies.get(movieId).getTitle() : "Start"; path.addFirst(new AbstractMap.SimpleEntry<>(idToNameMap.get(current), movieName)); current = visited.get(current); } return path; } } // Actor_relationship_game/TMDBApi.java package projecttest.Actor_relationship_game; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; public class TMDBApi { private final OkHttpClient client; private final String apiKey = System.getenv("TMDB_API_KEY"); // get API Key from environmental variable public TMDBApi() { this.client = new OkHttpClient(); } public String getMoviesByActorId(String actorId) throws IOException { String url = "https://api.themoviedb.org/3/person/" + actorId + "/movie_credits?api_key=" + apiKey; Request request = new Request.Builder().url(url).build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } return response.body().string(); } } public String searchPopularActors() throws IOException { String url = "https://api.themoviedb.org/3/person/popular?api_key=" + apiKey; Request request = new Request.Builder().url(url).build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } return response.body().string(); } } } // Actor_relationship_game/Movie.java package projecttest.Actor_relationship_game; import java.io.Serializable; import java.util.HashSet; import java.util.Set; public class Movie implements Serializable { private static final long serialVersionUID=1L; private String id; private String title; private Set<String> actorIds; // Store actor IDs public Movie(String id, String title) { this.id = id; this.title = title; this.actorIds = new HashSet<>(); } // Getters and setters public String getId() { return id; } public Set<String> getActorIds() { return actorIds; } public String getTitle() { return title; } public void setId(String id) { this.id = id; } public void setActorIds(Set<String> actorIds) { this.actorIds = actorIds; } public void setTitle(String title) { this.title = title; } } // Actor_relationship_game/ActorGraphUtil.java package projecttest.Actor_relationship_game; import java.io.*; import java.util.List; public class ActorGraphUtil { public static void main(String[] args) { String graphPath = args[0]; String filePath = args[1]; ActorGraph actorGraph = loadGraph(graphPath); if (actorGraph != null) { List<String> actorNames = actorGraph.getAllActorNames(); writeActorsToFile(actorNames, filePath); System.out.println("Actors list has been saved to " + filePath); } else { System.out.println("Failed to load the graph."); } } protected static ActorGraph loadGraph(String graphPath) { try (FileInputStream fileIn = new FileInputStream(graphPath); ObjectInputStream in = new ObjectInputStream(fileIn)) { return (ActorGraph) in.readObject(); } catch (Exception e) { e.printStackTrace(); return null; } } protected static void writeActorsToFile(List<String> actorNames, String fileName) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) { for (String name : actorNames) { writer.write(name); writer.newLine(); } } catch (IOException e) { e.printStackTrace(); } } } // Actor_relationship_game/GameplayInterface.java package projecttest.Actor_relationship_game; import java.io.*; import java.util.*; import java.util.List; public class GameplayInterface { private ActorGraph actorGraph; public void setActorGraph(ActorGraph actorGraph) { this.actorGraph = actorGraph; } public void loadGraph(String fileName) { try (FileInputStream fileIn = new FileInputStream(fileName); ObjectInputStream in = new ObjectInputStream(fileIn)) { actorGraph = (ActorGraph) in.readObject(); System.out.println("Graph successfully loaded."); } catch (Exception e) { e.printStackTrace(); } } public void findConnections(List<String[]> actorPairs, String outputFilePath) { try (PrintWriter writer = new PrintWriter(new FileWriter(outputFilePath))) { for (String[] pair : actorPairs) { if (pair.length != 2) { System.out.println("Invalid actor pair. Skipping."); continue; } String actor1Name = pair[0]; String actor2Name = pair[1]; // Assuming getActorIdByName is a method in ActorGraph that returns the actor's ID given a name String actor1Id = actorGraph.getActorIdByName(actor1Name); String actor2Id = actorGraph.getActorIdByName(actor2Name); if (actor1Id == null || actor2Id == null) { writer.println("One or both actors not found in the graph."); continue; } List<Map.Entry<String, String>> connectionPath = actorGraph.findConnectionWithPath(actor1Id, actor2Id); if (connectionPath.isEmpty()) { writer.println("==================================================="); writer.println("No connection found between " + actor1Name + " and " + actor2Name + "."); writer.println("==================================================="); writer.println(); } else { writer.println("==================================================="); writer.println("Connection Number between " + actor1Name + " and " + actor2Name + ":" + (connectionPath.size() - 1)); writer.println("Connection path between " + actor1Name + " and " + actor2Name + ":"); for (int i = 0; i < connectionPath.size(); i++) { Map.Entry<String, String> step = connectionPath.get(i); writer.println((i + 1) + ". " + step.getKey() + ": " + step.getValue()); } writer.println("==================================================="); writer.println(); } } } catch (IOException e){ e.printStackTrace(); } } private static List<String> readActorsFromFile(String fileName) { List<String> actors = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String line; while ((line = reader.readLine()) != null) { actors.add(line.trim()); } } catch (IOException e) { e.printStackTrace(); } return actors; } private static List<String[]> generateAllActorPairs(String fileName) { List<String> actors = readActorsFromFile(fileName); List<String[]> pairs = new ArrayList<>(); for (int i = 0; i < actors.size(); i++) { for (int j = i + 1; j < actors.size(); j++) { pairs.add(new String[]{actors.get(i), actors.get(j)}); } } return pairs; } public static void main(String[] args) { String graphPath = args[0]; String actorPath = args[1]; String filePath = args[2]; GameplayInterface gameplay = new GameplayInterface(); gameplay.loadGraph(graphPath); List<String[]> actorPairs = generateAllActorPairs(actorPath); gameplay.findConnections(actorPairs,filePath); } }
7
479
Java
springreactivenonreactive
./ProjectTest/Java/springreactivenonreactive.java
// springreactivenonreactive/repository/NonReactiveRepository.java package projecttest.springreactivenonreactive.repository; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import projecttest.springreactivenonreactive.model.Message; @Repository public interface NonReactiveRepository extends MongoRepository<Message, String> { } // springreactivenonreactive/repository/ReactiveRepository.java package projecttest.springreactivenonreactive.repository; import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import org.springframework.stereotype.Repository; import projecttest.springreactivenonreactive.model.Message; @Repository public interface ReactiveRepository extends ReactiveMongoRepository<Message, String> { } // springreactivenonreactive/model/Message.java package projecttest.springreactivenonreactive.model; import java.util.Date; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Document(collection = "messages") @Getter @Setter @NoArgsConstructor @ToString public class Message { @Id private String id; @NotBlank private String content; @NotNull private Date createdAt = new Date(); } // springreactivenonreactive/controller/WebFluxController.java package projecttest.springreactivenonreactive.controller; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import projecttest.springreactivenonreactive.model.Message; import projecttest.springreactivenonreactive.repository.ReactiveRepository; import reactor.core.publisher.Mono; @RestController public class WebFluxController { @Autowired ReactiveRepository reactiveRepository; @RequestMapping("/webflux/{id}") public Mono<Message> findByIdReactive(@PathVariable(value = "id") String id) { return reactiveRepository.findById(id); } @PostMapping("/webflux") public Mono<Message> postReactive(@Valid @RequestBody Message message) { return reactiveRepository.save(message); } @DeleteMapping("/webflux") public Mono<Void> deleteAllReactive() { return reactiveRepository.deleteAll(); } } // springreactivenonreactive/controller/MVCSyncController.java package projecttest.springreactivenonreactive.controller; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import projecttest.springreactivenonreactive.model.Message; import projecttest.springreactivenonreactive.repository.NonReactiveRepository; @RestController public class MVCSyncController { @Autowired NonReactiveRepository nonReactiveRepository; @RequestMapping("/mvcsync/{id}") public Message findById(@PathVariable(value = "id") String id) { return nonReactiveRepository.findById(id).orElse(null); } @PostMapping("/mvcsync") public Message post(@Valid @RequestBody Message message) { return nonReactiveRepository.save(message); } } // springreactivenonreactive/controller/MVCAsyncController.java package projecttest.springreactivenonreactive.controller; import java.util.concurrent.CompletableFuture; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import projecttest.springreactivenonreactive.model.Message; import projecttest.springreactivenonreactive.repository.NonReactiveRepository; @RestController public class MVCAsyncController { @Autowired NonReactiveRepository nonReactiveRepository; @RequestMapping("/mvcasync/{id}") public CompletableFuture<Message> findById(@PathVariable(value = "id") String id) { return CompletableFuture.supplyAsync(() -> nonReactiveRepository.findById(id).orElse(null)); } @PostMapping("/mvcasync") public CompletableFuture<Message> post(@Valid @RequestBody Message message) { return CompletableFuture.supplyAsync(() -> nonReactiveRepository.save(message)); } } // springreactivenonreactive/SpringMvcVsWebfluxApplication.java package projecttest.springreactivenonreactive; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringMvcVsWebfluxApplication { public static void main(String[] args) { SpringApplication.run(SpringMvcVsWebfluxApplication.class, args); } }
7
170
Java
redis
./ProjectTest/Java/redis.java
// redis/RedisConfigurationBuilder.java package projecttest.redis; import org.apache.ibatis.cache.CacheException; import org.apache.ibatis.io.Resources; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.SystemMetaObject; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Map; import java.util.Properties; /** * Converter from the Config to a proper {@link RedisConfig}. * * @author Eduardo Macarron */ final class RedisConfigurationBuilder { /** * This class instance. */ private static final RedisConfigurationBuilder INSTANCE = new RedisConfigurationBuilder(); protected static final String SYSTEM_PROPERTY_REDIS_PROPERTIES_FILENAME = "redis.properties.filename"; protected static final String REDIS_RESOURCE = "redis.properties"; /** * Hidden constructor, this class can't be instantiated. */ private RedisConfigurationBuilder() { } /** * Return this class instance. * * @return this class instance. */ public static RedisConfigurationBuilder getInstance() { return INSTANCE; } /** * Parses the Config and builds a new {@link RedisConfig}. * * @return the converted {@link RedisConfig}. */ public RedisConfig parseConfiguration() { return parseConfiguration(getClass().getClassLoader()); } /** * Parses the Config and builds a new {@link RedisConfig}. * * @param the {@link ClassLoader} used to load the {@code memcached.properties} file in classpath. * @return the converted {@link RedisConfig}. */ public RedisConfig parseConfiguration(ClassLoader classLoader) { Properties config = new Properties(); String redisPropertiesFilename = System.getProperty(SYSTEM_PROPERTY_REDIS_PROPERTIES_FILENAME, REDIS_RESOURCE); try (InputStream input = classLoader.getResourceAsStream(redisPropertiesFilename)) { if (input != null) { config.load(input); } } catch (IOException e) { throw new RuntimeException( "An error occurred while reading classpath property '" + redisPropertiesFilename + "', see nested exceptions", e); } RedisConfig jedisConfig = new RedisConfig(); setConfigProperties(config, jedisConfig); return jedisConfig; } private void setConfigProperties(Properties properties, RedisConfig jedisConfig) { if (properties != null) { MetaObject metaCache = SystemMetaObject.forObject(jedisConfig); for (Map.Entry<Object, Object> entry : properties.entrySet()) { String name = (String) entry.getKey(); // All prefix of 'redis.' on property values if (name != null && name.startsWith("redis.")) { name = name.substring(6); } else { // Skip non prefixed properties continue; } String value = (String) entry.getValue(); if ("serializer".equals(name)) { if ("kryo".equalsIgnoreCase(value)) { jedisConfig.setSerializer(KryoSerializer.INSTANCE); } else if (!"jdk".equalsIgnoreCase(value)) { // Custom serializer is not supported yet. throw new CacheException("Unknown serializer: '" + value + "'"); } } else if (Arrays.asList("sslSocketFactory", "sslParameters", "hostnameVerifier").contains(name)) { setInstance(metaCache, name, value); } else if (metaCache.hasSetter(name)) { Class<?> type = metaCache.getSetterType(name); if (String.class == type) { metaCache.setValue(name, value); } else if (int.class == type || Integer.class == type) { metaCache.setValue(name, Integer.valueOf(value)); } else if (long.class == type || Long.class == type) { metaCache.setValue(name, Long.valueOf(value)); } else if (short.class == type || Short.class == type) { metaCache.setValue(name, Short.valueOf(value)); } else if (byte.class == type || Byte.class == type) { metaCache.setValue(name, Byte.valueOf(value)); } else if (float.class == type || Float.class == type) { metaCache.setValue(name, Float.valueOf(value)); } else if (boolean.class == type || Boolean.class == type) { metaCache.setValue(name, Boolean.valueOf(value)); } else if (double.class == type || Double.class == type) { metaCache.setValue(name, Double.valueOf(value)); } else { throw new CacheException("Unsupported property type: '" + name + "' of type " + type); } } } } } protected void setInstance(MetaObject metaCache, String name, String value) { if (value == null || value.isEmpty()) { return; } Object instance; try { Class<?> clazz = Resources.classForName(value); instance = clazz.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new CacheException("Could not instantiate class: '" + value + "'.", e); } metaCache.setValue(name, instance); } } // redis/KryoSerializer.java package projecttest.redis; import com.esotericsoftware.kryo.kryo5.Kryo; import com.esotericsoftware.kryo.kryo5.io.Input; import com.esotericsoftware.kryo.kryo5.io.Output; import java.util.Arrays; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * SerializeUtil with Kryo, which is faster and less space consuming. * * @author Lei Jiang([email protected]) */ public enum KryoSerializer implements Serializer { // Enum singleton, which is preferred approach since Java 1.5 INSTANCE; /** * kryo is thread-unsafe, use ThreadLocal. */ private ThreadLocal<Kryo> kryos = ThreadLocal.withInitial(Kryo::new); /** * Classes which can not resolved by default kryo serializer, which occurs very * rare(https://github.com/EsotericSoftware/kryo#using-standard-java-serialization) For these classes, we will use * fallbackSerializer(use JDKSerializer now) to resolve. */ private Set<Class<?>> unnormalClassSet; /** * Hash codes of unnormal bytes which can not resolved by default kryo serializer, which will be resolved by * fallbackSerializer */ private Set<Integer> unnormalBytesHashCodeSet; private Serializer fallbackSerializer; private KryoSerializer() { unnormalClassSet = ConcurrentHashMap.newKeySet(); unnormalBytesHashCodeSet = ConcurrentHashMap.newKeySet(); fallbackSerializer = JDKSerializer.INSTANCE;// use JDKSerializer as fallback } @Override public byte[] serialize(Object object) { if (unnormalClassSet.contains(object.getClass())) { // For unnormal class return fallbackSerializer.serialize(object); } /** * In the following cases: 1. This class occurs for the first time. 2. This class have occurred and can be resolved * by default kryo serializer */ try (Output output = new Output(200, -1)) { kryos.get().writeClassAndObject(output, object); return output.toBytes(); } catch (Exception e) { // For unnormal class occurred for the first time, exception will be thrown unnormalClassSet.add(object.getClass()); return fallbackSerializer.serialize(object);// use fallback Serializer to resolve } } @Override public Object unserialize(byte[] bytes) { if (bytes == null) { return null; } int hashCode = Arrays.hashCode(bytes); if (unnormalBytesHashCodeSet.contains(hashCode)) { // For unnormal bytes return fallbackSerializer.unserialize(bytes); } /** * In the following cases: 1. This bytes occurs for the first time. 2. This bytes have occurred and can be resolved * by default kryo serializer */ try (Input input = new Input()) { input.setBuffer(bytes); return kryos.get().readClassAndObject(input); } catch (Exception e) { // For unnormal bytes occurred for the first time, exception will be thrown unnormalBytesHashCodeSet.add(hashCode); return fallbackSerializer.unserialize(bytes);// use fallback Serializer to resolve } } } // redis/Serializer.java package projecttest.redis; public interface Serializer { /** * Serialize method * * @param object * * @return serialized bytes */ byte[] serialize(Object object); /** * Unserialize method * * @param bytes * * @return unserialized object */ Object unserialize(byte[] bytes); } // redis/Main.java package projecttest.redis; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author 11293 */ public class Main { private static final String DEFAULT_ID = "REDIS"; private static RedisCache cache = new RedisCache(DEFAULT_ID); public static void main(String[] args) throws IOException { if (args.length != 2) { System.err.println("Error: Two arguments required, the first is the path to the input file, and the second is the path to the output file."); System.exit(1); } String inputFile = args[0]; String outputFile = args[1]; List<String> lines = Files.readAllLines(Paths.get(inputFile)); Map<String, String> localCache = new HashMap<>(); for (String line : lines) { String[] parts = line.split("\\s+"); if (parts.length == 2) { String key = parts[0]; String value = parts[1]; cache.putObject(key, value); localCache.put(key, value); } } try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile))) { for (String line : lines) { String[] parts = line.split("\\s+"); if (parts.length == 2) { String key = parts[0]; String value = (String) cache.getObject(key); assert value.equals(localCache.get(key)); writer.write(key + " " + value); writer.newLine(); } } } } } // redis/JDKSerializer.java package projecttest.redis; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.apache.ibatis.cache.CacheException; public enum JDKSerializer implements Serializer { // Enum singleton, which is preferred approach since Java 1.5 INSTANCE; private JDKSerializer() { // prevent instantiation } @Override public byte[] serialize(Object object) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos)) { oos.writeObject(object); return baos.toByteArray(); } catch (Exception e) { throw new CacheException(e); } } @Override public Object unserialize(byte[] bytes) { if (bytes == null) { return null; } try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais)) { return ois.readObject(); } catch (Exception e) { throw new CacheException(e); } } } // redis/RedisCallback.java package projecttest.redis; import redis.clients.jedis.Jedis; public interface RedisCallback { Object doWithRedis(Jedis jedis); } // redis/RedisCache.java package projecttest.redis; import org.apache.ibatis.cache.Cache; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; /** * Cache adapter for Redis. * * @author Eduardo Macarron */ public final class RedisCache implements Cache { private final ReadWriteLock readWriteLock = new DummyReadWriteLock(); private String id; private static JedisPool pool; private final RedisConfig redisConfig; private Integer timeout; public RedisCache(final String id) { if (id == null) { throw new IllegalArgumentException("Cache instances require an ID"); } this.id = id; redisConfig = RedisConfigurationBuilder.getInstance().parseConfiguration(); pool = new JedisPool(redisConfig, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getConnectionTimeout(), redisConfig.getSoTimeout(), redisConfig.getPassword(), redisConfig.getDatabase(), redisConfig.getClientName(), redisConfig.isSsl(), redisConfig.getSslSocketFactory(), redisConfig.getSslParameters(), redisConfig.getHostnameVerifier()); } private Object execute(RedisCallback callback) { Jedis jedis = pool.getResource(); try { return callback.doWithRedis(jedis); } finally { jedis.close(); } } @Override public String getId() { return this.id; } @Override public int getSize() { return (Integer) execute(jedis -> { Map<byte[], byte[]> result = jedis.hgetAll(id.getBytes()); return result.size(); }); } @Override public void putObject(final Object key, final Object value) { execute(jedis -> { final byte[] idBytes = id.getBytes(); jedis.hset(idBytes, key.toString().getBytes(), redisConfig.getSerializer().serialize(value)); if (timeout != null && jedis.ttl(idBytes) == -1) { jedis.expire(idBytes, timeout); } return null; }); } @Override public Object getObject(final Object key) { return execute( jedis -> redisConfig.getSerializer().unserialize(jedis.hget(id.getBytes(), key.toString().getBytes()))); } @Override public Object removeObject(final Object key) { return execute(jedis -> jedis.hdel(id, key.toString())); } @Override public void clear() { execute(jedis -> { jedis.del(id); return null; }); } @Override public ReadWriteLock getReadWriteLock() { return readWriteLock; } @Override public String toString() { return "Redis {" + id + "}"; } public void setTimeout(Integer timeout) { this.timeout = timeout; } } // redis/DummyReadWriteLock.java package projecttest.redis; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; /** * @author Iwao AVE! */ class DummyReadWriteLock implements ReadWriteLock { private Lock lock = new DummyLock(); @Override public Lock readLock() { return lock; } @Override public Lock writeLock() { return lock; } static class DummyLock implements Lock { @Override public void lock() { // Not implemented } @Override public void lockInterruptibly() throws InterruptedException { // Not implemented } @Override public boolean tryLock() { return true; } @Override public boolean tryLock(long paramLong, TimeUnit paramTimeUnit) throws InterruptedException { return true; } @Override public void unlock() { // Not implemented } @Override public Condition newCondition() { return null; } } } // redis/RedisConfig.java package projecttest.redis; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.Protocol; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocketFactory; public class RedisConfig extends JedisPoolConfig { private String host = Protocol.DEFAULT_HOST; private int port = Protocol.DEFAULT_PORT; private int connectionTimeout = Protocol.DEFAULT_TIMEOUT; private int soTimeout = Protocol.DEFAULT_TIMEOUT; private String password; private int database = Protocol.DEFAULT_DATABASE; private String clientName; private boolean ssl; private SSLSocketFactory sslSocketFactory; private SSLParameters sslParameters; private HostnameVerifier hostnameVerifier; private Serializer serializer = JDKSerializer.INSTANCE; public boolean isSsl() { return ssl; } public void setSsl(boolean ssl) { this.ssl = ssl; } public SSLSocketFactory getSslSocketFactory() { return sslSocketFactory; } public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) { this.sslSocketFactory = sslSocketFactory; } public SSLParameters getSslParameters() { return sslParameters; } public void setSslParameters(SSLParameters sslParameters) { this.sslParameters = sslParameters; } public HostnameVerifier getHostnameVerifier() { return hostnameVerifier; } public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { this.hostnameVerifier = hostnameVerifier; } public String getHost() { return host; } public void setHost(String host) { if (host == null || host.isEmpty()) { host = Protocol.DEFAULT_HOST; } this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getPassword() { return password; } public void setPassword(String password) { if (password == null || password.isEmpty()) { password = null; } this.password = password; } public int getDatabase() { return database; } public void setDatabase(int database) { this.database = database; } public String getClientName() { return clientName; } public void setClientName(String clientName) { if (clientName == null || clientName.isEmpty()) { clientName = null; } this.clientName = clientName; } public int getConnectionTimeout() { return connectionTimeout; } public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } public int getSoTimeout() { return soTimeout; } public void setSoTimeout(int soTimeout) { this.soTimeout = soTimeout; } public Serializer getSerializer() { return serializer; } public void setSerializer(Serializer serializer) { this.serializer = serializer; } }
9
651
Java
ckmeans
./ProjectTest/JavaScript/ckmeans.js
// ckmeans/numeric_sort.js /** * Sort an array of numbers by their numeric value, ensuring that the * array is not changed in place. * * This is necessary because the default behavior of .sort * in JavaScript is to sort arrays as string values * * [1, 10, 12, 102, 20].sort() * // output * [1, 10, 102, 12, 20] * * @param {Array<number>} x input array * @return {Array<number>} sorted array * @private * @example * numericSort([3, 2, 1]) // => [1, 2, 3] */ function numericSort(x) { return ( x // ensure the array is not changed in-place .slice() // comparator function that treats input as numeric .sort(function (a, b) { return a - b; }) ); } export default numericSort; // ckmeans/ckmeans.js import makeMatrix from "./make_matrix.js"; import numericSort from "./numeric_sort.js"; import uniqueCountSorted from "./unique_count_sorted.js"; /** * Generates incrementally computed values based on the sums and sums of * squares for the data array * * @private * @param {number} j * @param {number} i * @param {Array<number>} sums * @param {Array<number>} sumsOfSquares * @return {number} * @example * ssq(0, 1, [-1, 0, 2], [1, 1, 5]); */ function ssq(j, i, sums, sumsOfSquares) { let sji; // s(j, i) if (j > 0) { const muji = (sums[i] - sums[j - 1]) / (i - j + 1); // mu(j, i) sji = sumsOfSquares[i] - sumsOfSquares[j - 1] - (i - j + 1) * muji * muji; } else { sji = sumsOfSquares[i] - (sums[i] * sums[i]) / (i + 1); } if (sji < 0) { return 0; } return sji; } /** * Function that recursively divides and conquers computations * for cluster j * * @private * @param {number} iMin Minimum index in cluster to be computed * @param {number} iMax Maximum index in cluster to be computed * @param {number} cluster Index of the cluster currently being computed * @param {Array<Array<number>>} matrix * @param {Array<Array<number>>} backtrackMatrix * @param {Array<number>} sums * @param {Array<number>} sumsOfSquares */ function fillMatrixColumn( iMin, iMax, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ) { if (iMin > iMax) { return; } // Start at midpoint between iMin and iMax const i = Math.floor((iMin + iMax) / 2); matrix[cluster][i] = matrix[cluster - 1][i - 1]; backtrackMatrix[cluster][i] = i; let jlow = cluster; // the lower end for j if (iMin > cluster) { jlow = Math.max(jlow, backtrackMatrix[cluster][iMin - 1] || 0); } jlow = Math.max(jlow, backtrackMatrix[cluster - 1][i] || 0); let jhigh = i - 1; // the upper end for j if (iMax < matrix[0].length - 1) { /* c8 ignore start */ jhigh = Math.min(jhigh, backtrackMatrix[cluster][iMax + 1] || 0); /* c8 ignore end */ } let sji; let sjlowi; let ssqjlow; let ssqj; for (let j = jhigh; j >= jlow; --j) { sji = ssq(j, i, sums, sumsOfSquares); if (sji + matrix[cluster - 1][jlow - 1] >= matrix[cluster][i]) { break; } // Examine the lower bound of the cluster border sjlowi = ssq(jlow, i, sums, sumsOfSquares); ssqjlow = sjlowi + matrix[cluster - 1][jlow - 1]; if (ssqjlow < matrix[cluster][i]) { // Shrink the lower bound matrix[cluster][i] = ssqjlow; backtrackMatrix[cluster][i] = jlow; } jlow++; ssqj = sji + matrix[cluster - 1][j - 1]; if (ssqj < matrix[cluster][i]) { matrix[cluster][i] = ssqj; backtrackMatrix[cluster][i] = j; } } fillMatrixColumn( iMin, i - 1, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ); fillMatrixColumn( i + 1, iMax, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ); } /** * Initializes the main matrices used in Ckmeans and kicks * off the divide and conquer cluster computation strategy * * @private * @param {Array<number>} data sorted array of values * @param {Array<Array<number>>} matrix * @param {Array<Array<number>>} backtrackMatrix */ function fillMatrices(data, matrix, backtrackMatrix) { const nValues = matrix[0].length; // Shift values by the median to improve numeric stability const shift = data[Math.floor(nValues / 2)]; // Cumulative sum and cumulative sum of squares for all values in data array const sums = []; const sumsOfSquares = []; // Initialize first column in matrix & backtrackMatrix for (let i = 0, shiftedValue; i < nValues; ++i) { shiftedValue = data[i] - shift; if (i === 0) { sums.push(shiftedValue); sumsOfSquares.push(shiftedValue * shiftedValue); } else { sums.push(sums[i - 1] + shiftedValue); sumsOfSquares.push( sumsOfSquares[i - 1] + shiftedValue * shiftedValue ); } // Initialize for cluster = 0 matrix[0][i] = ssq(0, i, sums, sumsOfSquares); backtrackMatrix[0][i] = 0; } // Initialize the rest of the columns let iMin; for (let cluster = 1; cluster < matrix.length; ++cluster) { if (cluster < matrix.length - 1) { iMin = cluster; } else { // No need to compute matrix[K-1][0] ... matrix[K-1][N-2] iMin = nValues - 1; } fillMatrixColumn( iMin, nValues - 1, cluster, matrix, backtrackMatrix, sums, sumsOfSquares ); } } /** * Ckmeans clustering is an improvement on heuristic-based clustering * approaches like Jenks. The algorithm was developed in * [Haizhou Wang and Mingzhou Song](http://journal.r-project.org/archive/2011-2/RJournal_2011-2_Wang+Song.pdf) * as a [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming) approach * to the problem of clustering numeric data into groups with the least * within-group sum-of-squared-deviations. * * Minimizing the difference within groups - what Wang & Song refer to as * `withinss`, or within sum-of-squares, means that groups are optimally * homogenous within and the data is split into representative groups. * This is very useful for visualization, where you may want to represent * a continuous variable in discrete color or style groups. This function * can provide groups that emphasize differences between data. * * Being a dynamic approach, this algorithm is based on two matrices that * store incrementally-computed values for squared deviations and backtracking * indexes. * * This implementation is based on Ckmeans 3.4.6, which introduced a new divide * and conquer approach that improved runtime from O(kn^2) to O(kn log(n)). * * Unlike the [original implementation](https://cran.r-project.org/web/packages/Ckmeans.1d.dp/index.html), * this implementation does not include any code to automatically determine * the optimal number of clusters: this information needs to be explicitly * provided. * * ### References * _Ckmeans.1d.dp: Optimal k-means Clustering in One Dimension by Dynamic * Programming_ Haizhou Wang and Mingzhou Song ISSN 2073-4859 * * from The R Journal Vol. 3/2, December 2011 * @param {Array<number>} x input data, as an array of number values * @param {number} nClusters number of desired classes. This cannot be * greater than the number of values in the data array. * @returns {Array<Array<number>>} clustered input * @throws {Error} if the number of requested clusters is higher than the size of the data * @example * ckmeans([-1, 2, -1, 2, 4, 5, 6, -1, 2, -1], 3); * // The input, clustered into groups of similar numbers. * //= [[-1, -1, -1, -1], [2, 2, 2], [4, 5, 6]]); */ function ckmeans(x, nClusters) { if (nClusters > x.length) { throw new Error( "cannot generate more classes than there are data values" ); } const sorted = numericSort(x); // we'll use this as the maximum number of clusters const uniqueCount = uniqueCountSorted(sorted); // if all of the input values are identical, there's one cluster // with all of the input in it. if (uniqueCount === 1) { return [sorted]; } // named 'S' originally const matrix = makeMatrix(nClusters, sorted.length); // named 'J' originally const backtrackMatrix = makeMatrix(nClusters, sorted.length); // This is a dynamic programming way to solve the problem of minimizing // within-cluster sum of squares. It's similar to linear regression // in this way, and this calculation incrementally computes the // sum of squares that are later read. fillMatrices(sorted, matrix, backtrackMatrix); // The real work of Ckmeans clustering happens in the matrix generation: // the generated matrices encode all possible clustering combinations, and // once they're generated we can solve for the best clustering groups // very quickly. const clusters = []; let clusterRight = backtrackMatrix[0].length - 1; // Backtrack the clusters from the dynamic programming matrix. This // starts at the bottom-right corner of the matrix (if the top-left is 0, 0), // and moves the cluster target with the loop. for (let cluster = backtrackMatrix.length - 1; cluster >= 0; cluster--) { const clusterLeft = backtrackMatrix[cluster][clusterRight]; // fill the cluster from the sorted input by taking a slice of the // array. the backtrack matrix makes this easy - it stores the // indexes where the cluster should start and end. clusters[cluster] = sorted.slice(clusterLeft, clusterRight + 1); if (cluster > 0) { clusterRight = clusterLeft - 1; } } return clusters; } export default ckmeans; // ckmeans/unique_count_sorted.js /** * For a sorted input, counting the number of unique values * is possible in constant time and constant memory. This is * a simple implementation of the algorithm. * * Values are compared with `===`, so objects and non-primitive objects * are not handled in any special way. * * @param {Array<*>} x an array of any kind of value * @returns {number} count of unique values * @example * uniqueCountSorted([1, 2, 3]); // => 3 * uniqueCountSorted([1, 1, 1]); // => 1 */ function uniqueCountSorted(x) { let uniqueValueCount = 0; let lastSeenValue; for (let i = 0; i < x.length; i++) { if (i === 0 || x[i] !== lastSeenValue) { lastSeenValue = x[i]; uniqueValueCount++; } } return uniqueValueCount; } export default uniqueCountSorted; // ckmeans/make_matrix.js /** * Create a new column x row matrix. * * @private * @param {number} columns * @param {number} rows * @return {Array<Array<number>>} matrix * @example * makeMatrix(10, 10); */ function makeMatrix(columns, rows) { const matrix = []; for (let i = 0; i < columns; i++) { const column = []; for (let j = 0; j < rows; j++) { column.push(0); } matrix.push(column); } return matrix; } export default makeMatrix;
4
364
JavaScript
validate
./ProjectTest/JavaScript/validate.js
// validate/map.js // We use a global `WeakMap` to store class-specific information (such as // options) instead of storing it as a symbol property on each error class to // ensure: // - This is not exposed to users or plugin authors // - This does not change how the error class is printed // We use a `WeakMap` instead of an object since the key should be the error // class, not its `name`, because classes might have duplicate names. export const classesData = new WeakMap() // The same but for error instances export const instancesData = new WeakMap() // validate/validate.js import { classesData } from './map.js' // We forbid subclasses that are not known, i.e. not passed to // `ErrorClass.subclass()` // - They would not be validated at load time // - The class would not be normalized until its first instantiation // - E.g. its `prototype.name` might be missing // - The list of `ErrorClasses` would be potentially incomplete // - E.g. `ErrorClass.parse()` would not be able to parse an error class // until its first instantiation // This usually happens if a class was: // - Not passed to the `custom` option of `*Error.subclass()` // - But was extended from a known class export const validateSubclass = (ErrorClass) => { if (classesData.has(ErrorClass)) { return } const { name } = ErrorClass const { name: parentName } = Object.getPrototypeOf(ErrorClass) throw new Error( `"new ${name}()" must not be directly called. This error class should be created like this instead: export const ${name} = ${parentName}.subclass('${name}')`, ) }
2
37
JavaScript
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
129