file_id
stringlengths
4
9
content
stringlengths
146
15.9k
repo
stringlengths
9
113
path
stringlengths
6
76
token_length
int64
34
3.46k
original_comment
stringlengths
14
2.81k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
excluded
bool
1 class
file-tokens-Qwen/Qwen2-7B
int64
30
3.35k
comment-tokens-Qwen/Qwen2-7B
int64
3
624
file-tokens-bigcode/starcoder2-7b
int64
34
3.46k
comment-tokens-bigcode/starcoder2-7b
int64
3
696
file-tokens-google/codegemma-7b
int64
36
3.76k
comment-tokens-google/codegemma-7b
int64
3
684
file-tokens-ibm-granite/granite-8b-code-base
int64
34
3.46k
comment-tokens-ibm-granite/granite-8b-code-base
int64
3
696
file-tokens-meta-llama/CodeLlama-7b-hf
int64
36
4.12k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
3
749
excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
60_1
/*Write a program to find the shortest path between vertices using bellman-ford algorithm.*/ //bellman ford algorithm for shortest distance from a source node to all the remaining nodes import java.util.*; public class BellmanFord { private static int N; private static int[][] graph; public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the number of Vertices : "); N = sc.nextInt(); System.out.println("Enter the Weight Matrix of Graph"); graph = new int[N][N]; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) graph[i][j] = sc.nextInt(); System.out.print("Enter the Source Vertex : "); int source = sc.nextInt(); bellmanFord(source - 1); } public static void bellmanFord(int src) { int[] dist = new int[N]; Arrays.fill(dist, Integer.MAX_VALUE); dist[src] = 0; for (int i = 0; i < N; i++) { for (int u = 0; u < N; u++) { for (int v = 0; v < N; v++) { if (graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) { dist[v] = dist[u] + graph[u][v]; } } } } for (int u = 0; u < N; u++) { for (int v = 0; v < N; v++) { if (graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) { System.out.println("Negative weight cycle detected."); return; } } } printSolution(dist); } public static void printSolution(int[] dist) { System.out.println("Vertex \t Distance from Source"); for (int i = 0; i < N; i++) { System.out.println((i + 1) + "\t\t" + dist[i]); } } } /*output:- Enter the number of Vertices : 5 Enter the Weight Matrix of Graph 0 6 0 7 0 0 0 5 8 -4 0 0 0 0 0 0 0 -3 0 9 2 0 0 0 0 Enter the Source Vertex : 1 Vertex Distance from Source 1 0 2 6 3 4 4 7 5 2 */ /*Enter the number of Vertices : 3 Enter the Weight Matrix of Graph 0 10 5 0 0 -8 0 0 0 Enter the Source Vertex : 1 Vertex Distance from Source 1 0 2 10 3 2 */ /* Enter the number of Vertices : 3 Enter the Weight Matrix of Graph 0 10 0 0 0 20 0 -30 0 Enter the Source Vertex : 1 Negative weight cycle detected. */
saadhussain01306/computer_net_lab
3.bellman_ford.java
777
//bellman ford algorithm for shortest distance from a source node to all the remaining nodes
line_comment
en
false
717
17
777
18
812
17
777
18
856
18
false
false
false
false
false
true
294_12
package _2017._09._assignments.projectgo.template.v2; //imports import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; //class defnition f public class Go extends Application { // private fields private BorderPane bp_layout; private GoCustomControl customControl; private GoControlPanel controlPanel; private GoGameLogic gameLogic; private GoBoard board; // overridden init method public void init() { bp_layout = new BorderPane(); // create layout board = new GoBoard(); // creates a board gameLogic = new GoGameLogic(board); // create gameLogic and pass board to gameLogic so gameLogic can call methods from board customControl = new GoCustomControl(gameLogic); // create customControl and pass gameLogic to customControl so customControl can call methods from gameLogic controlPanel = new GoControlPanel(gameLogic); // create controlPanel and pass gameLogic to controlPanel so customControl can call methods from gameLogic bp_layout.setCenter(customControl); // put the customControl in the center of the layout bp_layout.setLeft(controlPanel); // put the controlPanel in the right of the layout } // overridden start method public void start(Stage primaryStage) { // set a title, size and the stack pane as the root of the scene graph primaryStage.setTitle("Go"); primaryStage.setScene(new Scene(bp_layout, 1000, 800)); primaryStage.show(); } // overridden stop method public void stop() { System.out.println("Application closed"); } // entry point into our program for launching our javafx applicaton public static void main(String[] args) { //T1 launch(args); } }
JosephCheevers/GO
Go.java
469
// set a title, size and the stack pane as the root of the scene graph
line_comment
en
false
407
17
469
17
464
17
469
17
530
18
false
false
false
false
false
true
909_0
import java.util.Scanner; import java.text.DecimalFormat; /** * Calculate Pi * @date 19 August 2014 * @author Nefari0uss * * This program will request the approximate number of calculations to run in calculating π. * The final result will be displayed on the console. Assumption is that the user inputs an int. * * * Uses the Gottfried Leibniz formula for calculation of π: * * 1 - 1/3 + 1/5 - 1/7 + 1/9 - ... = π/4 * * Source: Wikipedia - Leibniz formula for π **/ public class Pi { public static void main(String[] args) { int n = getInput(); double piValue = calculatePi(n); printResult(piValue); } private static double calculatePi(double n) { double pi = 0; for (int i = 1; i < n; i++) { pi += Math.pow(-1,i+1) / (2*i - 1); } return 4 * pi; } private static int getInput() { int n = 0; Scanner input = new Scanner(System.in); System.out.println("How many calculations should be run for the approximation?"); try { n = Integer.parseInt(input.nextLine()); } /** Handle input greater than Java's MAX_INT. **/ catch (NumberFormatException e) { System.out.println("n is too large. Setting n to be the largest possible int value."); n = Integer.MAX_VALUE; } input.close(); return n; } private static double calculateError(double piValue) { return Math.abs(1 - piValue / Math.PI) * 100; } private static void printResult(double piValue) { DecimalFormat df = new DecimalFormat("#.##"); System.out.println("The value of pi is approximately " + piValue + "."); System.out.println("The calculated value is off by approximately " + df.format(calculateError(piValue)) + "%."); } }
Nefari0uss/calculate-pi
Pi.java
542
/** * Calculate Pi * @date 19 August 2014 * @author Nefari0uss * * This program will request the approximate number of calculations to run in calculating π. * The final result will be displayed on the console. Assumption is that the user inputs an int. * * * Uses the Gottfried Leibniz formula for calculation of π: * * 1 - 1/3 + 1/5 - 1/7 + 1/9 - ... = π/4 * * Source: Wikipedia - Leibniz formula for π **/
block_comment
en
false
459
138
542
143
535
137
542
143
602
153
false
false
false
false
false
true
1566_0
//2-Given sides of a triangle, check whether the triangle is equilateral, isosceles or scalene. Find it's area import java.util.Scanner; public class Triangle { public static void main(String[] args) { int a, b, c; double p, area; Scanner sc = new Scanner(System.in); System.out.println("Enter sides of triangle : "); a = sc.nextInt(); b = sc.nextInt(); c = sc.nextInt(); if((a < b + c) && (b < a + c) && (c < a + b)){ if((a == b) && (b == c)) System.out.println("Given Trangle is Equilateral"); else if ((a == b) || (b == c) || (c == a)) System.out.println("Given Triangle is Isoscleles"); else System.out.println("Given Triangle is Scalane"); p=(a+b+c)/2; area = Math.sqrt(p * (p - a) * (p - b) * (p - c)); System.out.println("Area of triangle is = " + area); }else{ System.out.println("Cannot form a triangle"); } } }
KadeejaSahlaPV/java
2.java
293
//2-Given sides of a triangle, check whether the triangle is equilateral, isosceles or scalene. Find it's area
line_comment
en
false
264
29
293
30
310
27
293
30
331
33
false
false
false
false
false
true
1946_5
/****************************************************************************** * Compilation: javac UF.java * Execution: java UF < input.txt * Dependencies: StdIn.java StdOut.java * Data files: http://algs4.cs.princeton.edu/15uf/tinyUF.txt * http://algs4.cs.princeton.edu/15uf/mediumUF.txt * http://algs4.cs.princeton.edu/15uf/largeUF.txt * * Weighted quick-union by rank with path compression by halving. * * % java UF < tinyUF.txt * 4 3 * 3 8 * 6 5 * 9 4 * 2 1 * 5 0 * 7 2 * 6 1 * 2 components * ******************************************************************************/ import edu.princeton.cs.algs4.MinPQ; import edu.princeton.cs.algs4.StdIn; import edu.princeton.cs.algs4.StdOut; public class UF { private int[] parent; // parent[i] = parent of i private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31) private int count; // number of components /** * Initializes an empty union–find data structure with {@code n} sites * {@code 0} through {@code n-1}. Each site is initially in its own * component. * * @param n the number of sites * @throws IllegalArgumentException if {@code n < 0} */ public UF(int n) { if (n < 0) throw new IllegalArgumentException(); count = n; parent = new int[n]; rank = new byte[n]; for (int i = 0; i < n; i++) { parent[i] = i; rank[i] = 0; } } /** * Returns the component identifier for the component containing site {@code p}. * * @param p the integer representing one site * @return the component identifier for the component containing site {@code p} * @throws IndexOutOfBoundsException unless {@code 0 <= p < n} */ public int find(int p) { validate(p); while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } /** * Returns the number of components. * * @return the number of components (between {@code 1} and {@code n}) */ public int count() { return count; } /** * Returns true if the the two sites are in the same component. * * @param p the integer representing one site * @param q the integer representing the other site * @return {@code true} if the two sites {@code p} and {@code q} are in the same component; * {@code false} otherwise * @throws IndexOutOfBoundsException unless * both {@code 0 <= p < n} and {@code 0 <= q < n} */ public boolean connected(int p, int q) { return find(p) == find(q); } /** * Merges the component containing site {@code p} with the * the component containing site {@code q}. * * @param p the integer representing one site * @param q the integer representing the other site * @throws IndexOutOfBoundsException unless * both {@code 0 <= p < n} and {@code 0 <= q < n} */ public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } // validate that p is a valid index private void validate(int p) { int n = parent.length; if (p < 0 || p >= n) { throw new IndexOutOfBoundsException("index " + p + " is not between 0 and " + (n-1)); } } /** * Reads in a an integer {@code n} and a sequence of pairs of integers * (between {@code 0} and {@code n-1}) from standard input, where each integer * in the pair represents some site; * if the sites are in different components, merge the two components * and print the pair to standard output. * * @param args the command-line arguments */ public static void main(String[] args) { int n = StdIn.readInt(); UF uf = new UF(n); while (!StdIn.isEmpty()) { int p = StdIn.readInt(); int q = StdIn.readInt(); if (uf.connected(p, q)) continue; uf.union(p, q); StdOut.println(p + " " + q); } StdOut.println(uf.count() + " components"); } }
dud3/princeton-algs4
UF.java
1,263
/** * Returns the component identifier for the component containing site {@code p}. * * @param p the integer representing one site * @return the component identifier for the component containing site {@code p} * @throws IndexOutOfBoundsException unless {@code 0 <= p < n} */
block_comment
en
false
1,188
64
1,263
63
1,367
70
1,263
63
1,445
73
false
false
false
false
false
true
5737_3
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Babies do not produce cookies for their player but instead take away * cookies from the other player. * every second. * * @author Patrick Hu * @version November 2022 */ public class Baby extends Building { private boolean isDrinkingMilk; // whether the baby was given a milk bottle private int drinkingCount, drinkingActs; private GreenfootImage drinkingSprite; /** * @param player The player who has purchased a Baby */ public Baby(Player player) { super(player); animationSize = 11; scale = 0.5; isDrinkingMilk = false; drinkingCount = 0; drinkingActs = 90; } public void act() { super.act(); if(drinkingCount == 0 && isDrinkingMilk) { player.getBuildingRows().get(Baby.class).getBuildings().remove(this); getWorld().removeObject(this); } else if (drinkingCount <= drinkingActs && isDrinkingMilk) { Effect.fade(drinkingSprite, drinkingCount, drinkingActs); } else { if (actCount == actMark) { eat(); actMark = getNextActMark(2, 3); } } if(isDrinkingMilk) { setImage(drinkingSprite); drinkingCount --; } } /** * Eats(removes) 5-10 cookies from the other player. */ public void eat() { int amountToEat; if (Building.LUCKY) { amountToEat = 10; } else { amountToEat = getRandomNumberInRange(5, 10); } CookieWorld cw = (CookieWorld)getWorld(); Player otherPlayer = cw.getOtherPlayer(player); otherPlayer.changeCookieCount(-amountToEat); } /** * Changes baby's image to it drinking a bottle of milk. This happens when the * Milk Bottles powerup is activated. */ public void drinkMilk() { drinkingSprite = new GreenfootImage("powerup-icns/baby-drinking-milk.png"); drinkingSprite.scale(50, 50); setImage(drinkingSprite); isDrinkingMilk = true; drinkingCount = 120; } }
edzhuang/cookie-clicker-simulation
Baby.java
610
/** * @param player The player who has purchased a Baby */
block_comment
en
false
541
17
610
18
605
18
610
18
688
18
false
false
false
false
false
true
5838_7
import java.util.*; /** * Implementation of the Farmer Wolf Goat Cabbage problem. * * This code was created by Joshua Bates and is his copyright. */ public class FWGC implements Problem { private boolean[] river=new boolean[4]; private int cost; /** * Constructor to create a new FWGC * Cost is set to 0. */ public FWGC() { cost=0; } //private constructor to create a new state private FWGC(boolean[] pstate, int oCost) { for(int i=0; i< 4; i++) { this.river[i]=pstate[i]; } this.cost=oCost+1; } /** * Checks to see if state is goal state. * Goal state is everything is across the river. * @return */ @Override public boolean isGoal() { for(int i=0; i<4; i++) { if(!river[i]) return false; } return true; } /** * Getter method for cost. * @return */ @Override public int getCost() { return cost; } //Private method to switch farmer and something else across the river. private void changeRiver(int i) { if(river[0]) { river[0]=false; river[i]=false; } else { river[0]=true; river[i]=true; } } //Private method to add to array, and change the position private void newState(ArrayList<FWGC> arr, int position) { FWGC state=new FWGC(river, cost); state.changeRiver(position); arr.add(state); } /** * Checks valid successors, and returns all possible successors. * @return */ @Override public ArrayList<FWGC> successors() { ArrayList<FWGC> succ=new ArrayList<FWGC>(); if(!river[0]) { if(!river[1] && !river[2] && !river[3])//everything on bank { newState(succ, 2); } else if(!river[1] && river[2] && !river[3]) //goat across river, others on bank { newState(succ, 3); newState(succ, 1); } else if(!river[1] && !river[2] && river[3]) //goat and wolf on bank, cabbage across river { newState(succ, 1); newState(succ, 2); } else if(river[1] && !river[2] && !river[3]) //goat and cabbage on bank, wolf across bank. { newState(succ, 3); newState(succ, 2); } else if(river[1] && !river[2] && river[3]) //goat on bank, everything else across { newState(succ, 2); } } else { if((!river[1] && river[2] && !river[3])||(river[1] && !river[2] && river[3])) { newState(succ, 0); } else if(!river[1] && river[2] && river[3]) { newState(succ, 2); newState(succ, 3); } else if(river[1] && !river[2] && !river[3]) { newState(succ, 2); newState(succ, 3); } } return succ; } /** * Method for printing out the state. * * @return */ @Override public String toString() { String str="===============\n"; for(int i=0; i< 4; i++) { if(river[i]==false) { str+=getPerson(i)+" |RIVER| \n"; } else { str+=" |RIVER| "+getPerson(i)+" \n"; } } return str; } // Private method used in toString to get F, W, G, or C private String getPerson(int i) { String str=""; if(0==i) { str= "F"; } else if(1==i) { str= "W"; } else if(2==i) { str= "G"; } else if(3==i) { str= "C"; } return str; } /** * Gets heuristic value, which this problem will not have, so the value is * -1 * @return */ @Override public int heuristicValue() { return -1; } /** * Setter for cost * @param value */ @Override public void setCost(int value) { cost=value; } /** * Compares two FWGC classes. If they aren't FWGC, it will return false. *If they aren't the same state, will also return false * * @param state */ @Override public boolean compare( Problem state) { boolean isSame; if(state instanceof FWGC) { FWGC comp=(FWGC) state; int i=0; isSame=true;//state instanceof FWGC; while(i<4 && isSame) { if(comp.river[i]!=this.river[i]) { isSame=false; } i++; } } else { isSame=false; } return isSame; } }
BatesJosh/Artficial-Intelligence-Problem-Assignment
FWGC.java
1,392
/** * Checks valid successors, and returns all possible successors. * @return */
block_comment
en
false
1,276
20
1,392
21
1,561
22
1,392
21
1,757
25
false
false
false
false
false
true
6881_7
import java.util.ArrayList; import java.util.List; // Basic user interface which defines the basic methods required in the system public interface User { String getuserName(); String getPassword(); String getContact(); List<Event> getBookedEvents(); List<Booking> getBookings(); boolean isAdmin(); void displayInfo(); } // implemented Admin class with admin specific entries and methods. class Admin implements User { private String userName; private String password; private String contactInfo; private boolean isAdmin = true; // constructor public Admin(String userName, String password, String contactInfo) { this.userName = userName; this.password = password; this.contactInfo = contactInfo; } public String getuserName() { return userName; } @Override public String getPassword() { return password; } public String getContact() { return contactInfo; } @Override public List<Booking> getBookings() { return null; } @Override public List<Event> getBookedEvents() { return null; } public boolean isAdmin() { return isAdmin; } // boolean method that returns whether the new event is successfully added into the system or not. public boolean addNewEvent(String eventName, String eventDate, String eventTime, String eventVenue, int avaliableSeats, String eventOrganizer, Event Events[]) { Event event = new Event(eventName, eventDate, eventTime, eventVenue, avaliableSeats, eventOrganizer); boolean creation = false; for (int i = 0; i < Events.length; i++) { if (Events[i] == null) { Events[i] = event; creation = true; int eveid = Events[i].getEventId(); System.out.println("Event Registered with ID = " + eveid); break; } else { creation = false; } } return creation; } // display method which prints all the essential user information @Override public void displayInfo() { System.out.println("User Name: " + userName); System.out.println("User Password: " + password); System.out.println("Contact information: " + contactInfo); System.out.println("is user admin: " + isAdmin + "\n"); } } // implemented NormalUser class with specific entries and methods. class NormalUser implements User { private String userName; private String password; private String contactInfo; private boolean isAdmin = false; private List<Event> bookedEvents; private List<Booking> bookings; // constructor public NormalUser(String userName, String password, String contactInfo) { this.userName = userName; this.password = password; this.contactInfo = contactInfo; bookedEvents = new ArrayList<>(); bookings = new ArrayList<>(); } @Override public String getuserName() { return userName; } @Override public String getPassword() { return password; } @Override public String getContact() { return contactInfo; } @Override public boolean isAdmin() { return isAdmin; } @Override public List<Booking> getBookings() { return bookings; } @Override public List<Event> getBookedEvents() { return bookedEvents; } // method which prints all the booking details about the bookings made by the user. public void getAllBookings() { for (Booking booking : bookings) { booking.displayBookingDetails(); } } // method which prints all the events the user booked in for. public void getAllBookedEvent() { for (Event event : bookedEvents) { event.displayEventDetails(); } } // method to add a specific event object which the user booked for. public void addBookedEvent(Event event) { bookedEvents.add(event); } // method to add the specific booking object associated with a booking public void addBooking(Booking booking) { bookings.add(booking); } // display method to print all the essential information about the user. @Override public void displayInfo() { System.out.println("User Name: " + userName); System.out.println("User Password: " + password); System.out.println("Contact information: " + contactInfo); System.out.println("is user admin: " + isAdmin + "\n"); } }
Jainil2004/LocalEventManagementAndBookingSystem
User.java
1,039
// method which prints all the booking details about the bookings made by the user.
line_comment
en
false
961
18
1,039
19
1,185
17
1,039
19
1,272
19
false
false
false
false
false
true
10415_12
package billingsystem; import java.util.ArrayList; import javafx.scene.control.Label; /** * * @author Jason Li * @version 1.0 * @since 19.12.2016 * * * * The Class Table. */ public class Table extends Label implements java.io.Serializable { /** The tbl name. */ private String tblName; /** The people. */ private String people; /** The orders. */ ArrayList<Order> orders = new ArrayList<Order>(); /** The pos X. */ private double posX; /** The pos Y. */ private double posY; /** * Gets the name. * * @return the name */ public String getName() { return tblName; } /** * Gets the orders. * * @return the orders */ public ArrayList<Order> getOrders() { return orders; } /** * Set new X and Y. * * @param x the x-position * @param y the y-position */ public void setXY(double x, double y) { this.posX = x; this.posY = y; } /** * Gets the x-position. * * @return the x */ public double getX() { return posX; } /** * Gets the y-position. * * @return the y */ public double getY() { return posY; } /** * Sets the number of people at the table. * * @param people - Number of people */ public void setPeople(String people) { this.people = people; } /** * Gets the number of people at the table. * * @return people - Number of people */ public String getPeople() { return people; } /** * Adds the order. * * @param order item the order item */ public void addOrder(Order orderItem) { orders.add(orderItem); } /** * Sets the orders. * * @param set new orders */ public void setOrders(ArrayList<Order> setOrders) { this.orders = setOrders; } /** * Clear table */ public void clear() { this.people = ""; this.orders.clear();; } /** * Instantiates a new table. * * @param tblName the table name */ public Table(String tblName) { this.tblName = tblName; } /** * Instantiates a new table. * * @param copyTable - the table to copy */ public Table(Table copyTable) { this.tblName = copyTable.tblName; this.posX = copyTable.posX; this.posY = copyTable.posY; } }
kishanrajput23/Java-Projects-Collections
Billing-system/src/billingsystem/Table.java
732
/** * Gets the number of people at the table. * * @return people - Number of people */
block_comment
en
false
615
26
732
25
775
29
732
25
837
30
false
false
false
false
false
true
10518_0
import java.util.ArrayList; public class Cube extends Traceable { /* A Cube is cube centered at the origin, extending from -1 to +1 on * each axis * * Note: there is a bug in local_intersect so it sometimes does not work * correctly, but this should not give you a problem. */ public String toString() { return "Cube \n"+this.transform; } @Override public ArrayList<Intersection> local_intersect(Ray gray) { var ray = gray.transform(transform.invert()); double[] rets = check_axis(ray.origin.t[0], ray.direction.t[0]); double xtmin = rets[0]; double xtmax = rets[1]; rets = check_axis(ray.origin.t[1], ray.direction.t[1]); if (rets[0] > xtmin) xtmin = rets[0]; if (rets[1] < xtmax) xtmax = rets[1]; rets = check_axis(ray.origin.t[2], ray.direction.t[2]); if (rets[0] > xtmin) xtmin = rets[0]; if (rets[1] < xtmax) xtmax = rets[1]; ArrayList<Intersection> ans = new ArrayList<Intersection>(); if (xtmin >= xtmax || xtmax == Double.POSITIVE_INFINITY) return ans; ans.add(new Intersection(this, xtmin)); ans.add(new Intersection(this, xtmax)); return ans; } private double[] check_axis(double origin, double direction) { double tmin_numerator = (-1 - origin); double tmax_numerator = (1 - origin); double tmin; double tmax; //Had an error where Aux could not be resolved to a variable, so I simply replaced Aux.EPSILON with its value 0.0001 if (Math.abs(direction) >= 0.0001) { tmin = tmin_numerator / direction; tmax = tmax_numerator / direction; } else { if (tmin_numerator >= 0) tmin = Double.POSITIVE_INFINITY; else if (tmin_numerator <=0) tmin = Double.NEGATIVE_INFINITY; else tmin = 0; if (tmax_numerator >= 0) tmax = Double.POSITIVE_INFINITY; else if (tmax_numerator <=0) tmax = Double.NEGATIVE_INFINITY; else tmax = 0; } if (tmin > tmax) { double temp = tmin; tmin = tmax; tmax = temp; } return new double[] {tmin, tmax}; } @Override public Vector local_normal_at(Point point, Intersection dontUse) { double[] point_vals = world_to_object(point).getT(); int pos = 0; double max = -1; for (int i = 0; i < point_vals.length - 1; i++) { if (Math.abs(point_vals[i]) > max) { max = Math.abs(point_vals[i]); pos = i; } } if (pos == 0) { return new Vector(point_vals[0],0,0); } else if (pos == 1) { return new Vector(0, point_vals[1], 0); } else { return new Vector(0, 0, point_vals[2]); } } public static void main(String[] args) { } @Override public boolean includes(Traceable object) { return this == object; } }
daviddang415/Ray_Tracer
Cube.java
964
/* A Cube is cube centered at the origin, extending from -1 to +1 on * each axis * * Note: there is a bug in local_intersect so it sometimes does not work * correctly, but this should not give you a problem. */
block_comment
en
false
825
61
964
58
964
64
964
58
1,184
66
false
false
false
false
false
true
11161_0
import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; import java.util.stream.Collectors; /** * This class represents a Graphical User Interface (GUI) for the local movie database. * Users can view, add, and manage movies in the database through this interface. * The GUI includes options for sorting and filtering movies by different criteria. * * @author Asliddin * @version 6.0 */ public class GUI extends JFrame { private Container container = getContentPane(); private JPanel contentPanel; private static ArrayList<Movie> allMovies = MovieDatabase.allMovies(); private TreeSet<String> directors = MovieDatabase.directors; /** * Constructs a new GUI window for the local movie database. * Initializes the graphical interface, sets its size and title, and adds various components. * Users can interact with the GUI to view, sort, and filter movies. */ GUI() { this.setVisible(true); this.setSize(800, 600); this.setTitle("Local Movie Database"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); contentPanel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 1; gbc.weighty = 0; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = new Insets(10, 10, 10, 10); JButton addMovie = new JButton("Add Movie"); addMovie.addActionListener((e) -> { new AddMovie(); }); /** * Inner class representing a window for adding a new movie to the database. * Users can input movie details such as title, director, release year, and runtime. */ addMovie.setPreferredSize(new Dimension(200, 75)); addMovie.setPreferredSize(new Dimension(130, 50)); JPanel addPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); addPanel.add(addMovie); JButton profile = new JButton("Profile"); profile.addActionListener((e) -> { this.dispose(); new Profile(); }); profile.setPreferredSize(new Dimension(130, 50)); addPanel.add(profile); String[] str = {"sort by: ", "Title", "Year", "Runtime"}; JComboBox<String> sortBy = new JComboBox<>(str); sortBy.addActionListener((e)->{ if(sortBy.getSelectedItem().equals("Year")){ Collections.sort(allMovies); } else if(sortBy.getSelectedItem().equals("Runtime")){ allMovies.sort((Movie m1, Movie m2)->{ return m2.getRunningTime() - m1.getRunningTime(); }); } else if(sortBy.getSelectedItem().equals("Title")){ Collections.sort(allMovies, Comparator.comparing(Movie::getTitle)); } contentPanel.revalidate(); contentPanel.repaint(); this.dispose(); new GUI(); }); Iterator<String> iter = directors.iterator(); String strr[] = new String[directors.size()+2]; strr[0]="Filter By Directors"; strr[1]="All"; int j=2; while(iter.hasNext()){ strr[j] = iter.next(); j++; } JComboBox<String> filter = new JComboBox<>(strr); filter.addActionListener((e)->{ if(filter.getSelectedItem().equals("All") || filter.getSelectedItem().equals("Filter By Directors")){ allMovies = MovieDatabase.allMovies(); directors = MovieDatabase.directors; } else{ allMovies = (ArrayList<Movie>) MovieDatabase.allMovies().stream().filter((ee)->{ return ee.getDirector().equals(filter.getSelectedItem()); }).collect(Collectors.toList()); } this.dispose(); new GUI(); }); JLabel searchL = new JLabel("search:"); JTextField searchF = new JTextField(); searchF.setPreferredSize(new Dimension(50, 20)); JButton search = new JButton("search"); search.addActionListener(e->{ String txt = searchF.getText(); if(txt.length()==0){ JOptionPane.showMessageDialog(this, "Please fill the blank!"); }else{ Movie movie = MovieDatabase.retrieveMovie(txt); if(movie==null){ JOptionPane.showMessageDialog(this, "No such movie!"); }else{ String formatted = String.format("Title: %s\n Director: %s\n Year: %d\n Runtime: %d", movie.getTitle(), movie.getDirector(), movie.getReleasedYear(), movie.getRunningTime()); JOptionPane.showMessageDialog(this, formatted); } } }); addPanel.add(sortBy); addPanel.add(filter); addPanel.add(searchL); addPanel.add(searchF); addPanel.add(search); container.add(addPanel, BorderLayout.NORTH); for (int i = 0; i < allMovies.size(); i++) { String title = allMovies.get(i).getTitle(); String director = allMovies.get(i).getDirector(); int year = allMovies.get(i).getReleasedYear(); int runtime = allMovies.get(i).getRunningTime(); Border insideBorder = BorderFactory.createTitledBorder(title); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.setBorder(insideBorder); String movieInfo = String.format( "<strong>Director:</strong> %s, <br><strong>Year:</strong> %d, <br><strong>Runtime:</strong> %d", director, year, runtime); JLabel label = new JLabel( "<html><div style='text-align: left; padding:10px;'>" + movieInfo + "</div></html>"); panel.add(label, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 5, 5)); JButton addToWatchlistButton = new JButton("Add to Watchlist"); addToWatchlistButton.addActionListener((e) -> { User user = Register.getLoggedIn(); ArrayList<Movie> watchlist = MovieDatabase.getUserDB(user); boolean exists = watchlist.stream().anyMatch((t)->t.getTitle().equals(title)); if(!exists){ try (FileWriter fw = new FileWriter(String.format("DB/UserDB/DB%s.csv", user.getUsername()), true)) { String movie = String.format("%s, %s, %d, %d\n", title, director, year, runtime); fw.append(movie); } catch (Exception ex) { ex.printStackTrace(); } }else{ JOptionPane.showMessageDialog(this, "This movie already exists in your watchlist!"); } }); buttonPanel.add(addToWatchlistButton); JButton removeButton = new JButton("Remove"); buttonPanel.add(removeButton); Movie movie = allMovies.get(i); removeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String movieTitle = movie.getTitle(); MovieDatabase.removeMovie(movieTitle); contentPanel.remove(panel); contentPanel.revalidate(); contentPanel.repaint(); } }); panel.add(buttonPanel, BorderLayout.SOUTH); contentPanel.add(panel, gbc); gbc.gridy++; } JScrollPane scrollPane = new JScrollPane(contentPanel); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); container.add(scrollPane); } class AddMovie extends JFrame implements ActionListener { JButton add = new JButton("add"); JLabel directorLabel = new JLabel("Director : "); JTextField directorField = new JTextField(); JLabel yearLabel = new JLabel("Release Year: "); JTextField yearField = new JTextField(); JLabel runtimeLabel = new JLabel("Running time: "); JTextField runtimeField = new JTextField(); JLabel titleLabel = new JLabel("Title: "); JTextField titleField = new JTextField(); Container container = getContentPane(); JLabel warning1 = new JLabel("To see the update please click the 'All'"); JLabel warning2 = new JLabel("in filter by director section!!!"); public AddMovie() { basic(); container.setLayout(null); setSize(); add.addActionListener(this); container.add(titleLabel); container.add(directorLabel); container.add(yearLabel); container.add(runtimeLabel); container.add(titleField); container.add(directorField); container.add(yearField); container.add(runtimeField); container.add(add); container.add(warning1); container.add(warning2); } /** * Performs an action when the add button is clicked in the AddMovie window. * Validates user input for the new movie and adds it to the database if input is valid. * Displays error messages for missing or invalid input. * * @param e The ActionEvent triggered by clicking the add button. */ public void basic() { this.setVisible(true); this.setBounds(450, 100, 370, 600); this.setTitle("Add New Movie"); } private void setSize() { titleLabel.setBounds(50, 90, 100, 30); directorLabel.setBounds(50, 150, 100, 30); yearLabel.setBounds(50, 220, 150, 30); runtimeLabel.setBounds(50, 290, 150, 30); titleField.setBounds(150, 90, 150, 30); directorField.setBounds(150, 150, 150, 30); yearField.setBounds(150, 220, 150, 30); runtimeField.setBounds(150, 290, 150, 30); add.setBounds(50, 370, 100, 30); warning1.setFont(new Font("Italic", Font.ITALIC, 15)); warning2.setFont(new Font("Italic", Font.ITALIC, 15)); warning1.setBounds(30, 410, 300, 20); warning2.setBounds(30, 430, 300, 20); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == add){ if(this.titleField.getText().length()==0 || this.directorField.getText().length()==0 || this.yearField.getText().length()==0 || this.runtimeField.getText().length()==0) { JOptionPane.showMessageDialog(this, "Please fill all the gaps!"); } else{ int runtime, year; try{ runtime = Integer.valueOf(this.runtimeField.getText()); year = Integer.valueOf(this.yearField.getText()); Movie movie = new Movie(this.titleField.getText(), this.directorField.getText(), year, runtime); MovieDatabase.addMovie(movie); this.dispose(); }catch(NumberFormatException ee){ JOptionPane.showMessageDialog(this, "Year and runtime should contain only digits!"); } } } } } }
asroilf/MovieDBMS
GUI.java
2,703
/** * This class represents a Graphical User Interface (GUI) for the local movie database. * Users can view, add, and manage movies in the database through this interface. * The GUI includes options for sorting and filtering movies by different criteria. * * @author Asliddin * @version 6.0 */
block_comment
en
false
2,362
68
2,703
73
2,903
71
2,703
73
3,310
76
false
false
false
false
false
true
12566_1
//check if a linkedlist is palindrome or not class LL { node head; class node { int data; node next; node(int data) { this.data = data; this.next = null; } } /* * steps: * 1. find middle of LL * 2. reverse 2nd half * 3. check 1st and 2nd half */ public void addlast(int data) { node newnode = new node(data); if (head == null) { head = newnode; } node curr = head; while (curr.next != null) { curr = curr.next; } curr.next = newnode; } public node reverse(node head) { node prev = null; node curr = head; node next = null; while (curr != null) { next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; } public node findmiddle(node head) { node hare = head; node turtle = head; while (hare.next.next != null && hare.next != null) { hare = hare.next.next; turtle = turtle.next; } return turtle; } public boolean isPalindrome(node head) { if (head == null || head.next == null) { return true; } node middle = findmiddle(head);// end of 1st half node secondstart = reverse(middle.next); node firststart = head; while (secondstart != null) { if (firststart.data != secondstart.data) { return false; } firststart = firststart.next; secondstart = secondstart.next; } return true; } } class sol{ public static void main(String[] args) { LL list = new LL(); list.addlast(1); list.addlast(2); list.addlast(2); list.addlast(1); System.out.println("is palindrome"+list.isPalindrome(list.head)); } }
GAGANDASH002/Java-DSA
q4.java
510
/* * steps: * 1. find middle of LL * 2. reverse 2nd half * 3. check 1st and 2nd half */
block_comment
en
false
461
43
510
40
568
45
510
40
601
45
false
false
false
false
false
true
13150_9
package LumberYard; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; /** * LumberYard Log class. */ public class Log{ private static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss +SSS'ms' '['z']'").withZone(ZoneId.systemDefault()); private static final String DEFAULT_DIR = System.getProperty("user.dir")+System.getProperty("file.separator")+"lumberyard"; /** * Get the default directory used when creating a log without a specified directory. * * @return the string */ public static String getDefaultDirectory(){ return DEFAULT_DIR; } /** * Convert a throwable into a structured string. * * @param e the throwable * @return the structured string */ public static String parseThrowable(Throwable e) { StringBuilder sb = new StringBuilder(); sb.append(e.getClass().getName()+(e.getMessage()!=null?": "+e.getMessage():"")); for (StackTraceElement element : e.getStackTrace()) { sb.append("\n\tat "); sb.append(element.toString()); } if(e.getCause()!=null){ sb.append("\nCaused by: "); sb.append(parseThrowable(e.getCause())); } return sb.toString(); } private static Log defaultLog = null; /** * Get the default log. * * @return the default log */ public static Log getDefault(){ if(defaultLog == null){ defaultLog = new Log(Thread.currentThread().getName()); } return defaultLog; } private String name, dir; private Path path; /** * Flag to mirror new log entries to the System.out console after the log file. */ public boolean console = true; /** * Instantiates a new unnamed Log in the default directory. */ public Log(){ this(null); } /** * Instantiates a new Log with a specified name. * * @param name the name */ public Log(String name){ this(DEFAULT_DIR, name); } /** * Instantiates a new Log with a specified name in a specified directory. * * @param dir the dir * @param name the name */ public Log(String dir, String name){ this.name = name; this.dir = dir; timestampName(); generatePath(); } private void generatePath(){ if(name == null){ timestampName(); } if(dir == null){ dir = getDefaultDirectory(); } path = Path.of(getDirectory() + System.getProperty("file.separator") + getName() + ".log"); } /** * Get the directory of the log. * * @return the directory */ public String getDirectory(){ return dir; } /** * Get the name of the log. * * @return the name */ public String getName(){ return name; } /** * Get the full path of the log. * * @return the path */ public Path getPath(){ return path; } private void timestampName(){ DateTimeFormatter stamp = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss").withZone(ZoneId.systemDefault()); name = ((name !=null) ? name + "_" : "") + stamp.format(Instant.now()); } /** * Write a categorized message to the log. * * @param category the category * @param message the message */ public void write(Category category, String message){ if(category.isEnabled()){ println(category + " | "+ message); } } /** * Write a throwable to the log. * * @param e the throwable */ public void write(Throwable e){ if(Category.ERROR.isEnabled()){ println(Category.ERROR +" | "+ parseThrowable(e)); } } /** * Write a blank line to the log. */ protected void println(){ try{ Files.write(path, "\n".getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); } catch(Exception e){ e.printStackTrace(); } if(console){ System.out.println(); } } /** * Timestamp and write multiple lines to the log. * * @param lines the lines */ protected void println(String...lines){ for(String line:lines){ println(line); } } /** * Timestamp and write a line to the log. * * @param line the message */ protected void println(String line){ line = TIMESTAMP_FORMATTER.format(Instant.now()) + " | Thread: " +Thread.currentThread().getName()+" | " + line + "\n"; try{ Files.write(path, line.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); } catch(Exception e){ e.printStackTrace(); } if(console){ System.out.print(line); } } /** * Make the log the default log. */ public void makeDefault(){ defaultLog = this; } /** * Categories of log messages. */ public enum Category{ /** * Info category. Enabled by default. */ INFO(), /** * Warning category. Enabled by default. */ WARNING(), /** * Error category. Enabled by default. */ ERROR(), /** * Debug category. Disabled by default. */ DEBUG(false), /** * Verbose category. Disabled by default. */ VERBOSE(false); private boolean enabled; Category(){ this(true); } Category(boolean enabled){ this.enabled = enabled; } /** * Enable the category. */ public void enable(){ this.enabled = true; } /** * Disable the category. */ public void disable(){ this.enabled = false; } /** * Check if the category is enabled. * * @return true if the category is enabled. */ public boolean isEnabled(){ return enabled; } } }
YoungGopher/LumberYard
Log.java
1,600
/** * Get the name of the log. * * @return the name */
block_comment
en
false
1,349
21
1,600
20
1,669
24
1,600
20
1,878
24
false
false
false
false
false
true
14639_1
/* Copyright 2010 Brian Mock * * This file is part of visint. * * visint is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * visint is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with visint. If not, see <http://www.gnu.org/licenses/>. */ import java.util.*; /** * This program controls printing debugging output (or not!). * @author Brian Mock */ public class Debug { public static boolean debug = false; private static String separator = "========================================"; public static void error (String s) { if (debug) System.err.println(s); } public static void println (String s) { if (debug) System.out.println(s); } public static void print (String s) { if (debug) System.out.print (s); } public static void printAry(Object[] ary) { println(Arrays.deepToString(ary)); } public static void printSep() { println(separator); } }
wavebeem/visint
Debug.java
356
/** * This program controls printing debugging output (or not!). * @author Brian Mock */
block_comment
en
false
317
20
356
23
360
21
356
23
403
22
false
false
false
false
false
true
16462_0
import java.util.ArrayList; import java.io.*; public class Driver { private static ArrayList<Student> studentList; private static ArrayList<String> schoolList; public ArrayList<Student> getStudentList() { return this.studentList; } public void setStudentList(ArrayList<Student> studentList) { this.studentList = studentList; } /* Reads data from the csv file and creates a Student and stores it in the list. */ public static void csvToList(File csvFile) { try { studentList = new ArrayList<Student>(); schoolList = new ArrayList<String>(); String row; BufferedReader csvReader = new BufferedReader(new FileReader(csvFile)); while ((row = csvReader.readLine()) != null) { String[] rawStudent = row.split(","); Student student = new Student(Integer.valueOf(rawStudent[0]), rawStudent[1], rawStudent[2]); studentList.add(student); if (!schoolList.contains(rawStudent[2])) { schoolList.add(rawStudent[2]); } } csvReader.close(); } catch (Exception e) { System.out.println("Error"); } } /* Creates and write to a .txt file. Tab delimited. Does this for one school. */ public static void tsvForSchool(String school) { File tsv = new File("data/" + school + ".txt"); String TAB = "\t"; String EOL = "\n"; try { FileWriter tsvWriter = new FileWriter(tsv); for (int i = 0; i < studentList.size(); i++) { StringBuilder sb = new StringBuilder(); if (studentList.get(i).getSchool().equals(school)) { sb.append(studentList.get(i).getId()); sb.append(TAB); sb.append(studentList.get(i).getName()); sb.append(TAB); sb.append(school + EOL); tsvWriter.write(sb.toString()); } } tsvWriter.close(); } catch (IOException e) { System.out.println("Error"); } } public static void main(String[] args) { File testFile = new File("testFile.csv"); csvToList(testFile); for (int i = 0; i < schoolList.size(); i++) { tsvForSchool(schoolList.get(i)); } } }
mattspahr/CSV-to-Tab
Driver.java
630
/* Reads data from the csv file and creates a Student and stores it in the list. */
block_comment
en
false
545
25
630
25
669
27
630
25
813
30
false
false
false
false
false
true
16477_5
/* Prompts a frame that asks the user for their personal information and inputs it into a list to be accessed from again at a later time. Primarily asks for their first and last name, school name, what type of school they are in, and what quarter or semester they are in currently. Depending on their answers, different choices will show. @author Nhi Ngo @version 06/15/2014 */ import javax.swing.*; import java.awt.*; import java.util.*; import java.awt.event.*; public class Asking extends Program implements ActionListener{ private JPanel questions; private JTextPane intro; private JPanel quarterHS; private int highS; private int colle; private int placeholder; private JPanel quarterC; private JPanel overallInfo; private JPanel userInfo; private JPanel schoolAsk; private JPanel empty; private JPanel overall; private int quarterNum; private JPanel info; private JTextField firstName; private JTextField lastName; private JTextField schoolName; private ArrayList<String> names; /*Intializes all instance fields*/ public Asking() { highS = 0; colle = 0; placeholder = 0; questions = new JPanel(new BorderLayout()); overallInfo = new JPanel (new BorderLayout()); userInfo = new JPanel(new GridLayout(1,6)); empty = new JPanel(); schoolAsk = new JPanel (new GridLayout(3,1)); quarterHS = new JPanel(new FlowLayout()); quarterC = new JPanel(new FlowLayout()); overall = new JPanel(new GridLayout(1,1)); info = new JPanel(new BorderLayout()); overall.add(quarterC); overall.add(quarterHS); info.add(overall, BorderLayout.NORTH); overallInfo.add(info, BorderLayout.SOUTH); names = new ArrayList<String>(); } /*Adds all components regarding asking the user into the main visual panel for the user to interact and read*/ public JPanel ask() { questions.add(empty, BorderLayout.CENTER); intro = introText(); questions.add(intro, BorderLayout.NORTH); personalInfo(); schoolAsk(); overallInfo.add(userInfo, BorderLayout.NORTH); overallInfo.add(schoolAsk, BorderLayout.CENTER); questions.add(overallInfo, BorderLayout.SOUTH); return questions; } /* *Creates and set a label *@param name the text that will display on the label */ private JLabel label(String name) { JLabel label = new JLabel(name, JLabel.CENTER); label.setPreferredSize(new Dimension(80, 15)); return label; } /*Creates and set the settings of textfield*/ private JTextField text(){ JTextField text = new JTextField(); text.setPreferredSize(new Dimension(85, 20)); return text; } /*Shows the introduction text to the user. Primarily is instructions and information to the user*/ private JTextPane introText() { JTextPane text = new JTextPane(); text.setEditable(false); text.setText(" Welcome to Personal Secretary Student Version! Before we start organizing your schedule and\n time, let's set up your profile so you can access it again. All we need is basic information. \n You can edit this information later in the settings option. If you do not wish to answer, feel\n free to leave it blank."); return text; } /*Prompts the user for personal information*/ private void personalInfo() { JLabel fName = label("First Name"); JLabel lName = label("Last Name"); JLabel sName = label("School Name"); firstName = text(); lastName = text(); schoolName = text(); userInfo.add(fName); userInfo.add(firstName); userInfo.add(lName); userInfo.add(lastName); userInfo.add(sName); userInfo.add(schoolName); } /*Asks the user about school information and different panels will display according to user's choice*/ private void schoolAsk(){ schoolAsk = new JPanel(new GridLayout(1, 3)); JLabel question = new JLabel ("What school are you in?", JLabel.CENTER); JRadioButton highSchool = radioButton ("High School"); JRadioButton college = radioButton ("College"); schoolAsk.add(question); ButtonGroup group = new ButtonGroup(); group.add(highSchool); group.add(college); schoolAsk.add(highSchool); schoolAsk.add(college); } /*If the user is in high school, choices of semesters will appear*/ private void highSchool(){ overall.remove(quarterC); overall.revalidate(); colle += 2; if (highS == 0) { JRadioButton firstSem = radioButton("1st Semester"); JRadioButton secondSem = radioButton("2nd Semester"); ButtonGroup group = new ButtonGroup(); group.add(firstSem); group.add(secondSem); quarterHS.add(firstSem); quarterHS.add(secondSem); } if(highS == 0 || highS % 2 == 0) { overall.add(quarterHS); } overall.revalidate(); } /*If user is in college, choices to choose quarters will be visible*/ private void college() { overall.remove(quarterHS); overall.revalidate(); highS += 2; if (colle <= 2) { JRadioButton fall = radioButton("Fall"); JRadioButton winter = radioButton("Winter"); JRadioButton spring = radioButton("Spring"); JRadioButton summer = radioButton("Summer"); ButtonGroup group = new ButtonGroup(); group.add(fall); group.add(winter); group.add(spring); group.add(summer); quarterC.add(fall); quarterC.add(winter); quarterC.add(spring); quarterC.add(summer); } if(colle == 0 || colle % 2 == 0) { overall.add(quarterC); } overall.revalidate(); } /*Adds a button of "next" for the user to continue*/ private void next() { JButton next = button("Continue"); info.add(next, BorderLayout.CENTER); setNames(); overall.revalidate(); } /*Add user's info onto arrayList*/ public void setNames() { names = new ArrayList<String>(); names.add(firstName.getText()); names.add(lastName.getText()); names.add(schoolName.getText()); } /* *Creates a radio button *@param name the text that labels the button */ private JRadioButton radioButton(String name){ JRadioButton box = new JRadioButton(name); box.setSelected(false); box.addActionListener(this); return box; } /* *Creates and set the settings for button *@param name the text that will appear on the button */ private JButton button(String name) { JButton button = new JButton(name); button.setText(name); button.setBackground(Color.WHITE); button.addActionListener(this); return button; } /*Depending on which button user picks, the listener will react differently*/ public void actionPerformed(ActionEvent event) { if (event.getActionCommand().equals("High School")) { highSchool(); } else if(event.getActionCommand().equals("College")) { college(); } else if (event.getActionCommand().equals("Continue")){ questions.setVisible(false); super.classInfo(names, quarterNum); } else{ if(event.getActionCommand().equals("Fall")){ quarterNum = 1; placeholder++; } else if(event.getActionCommand().equals("Winter")){ quarterNum = 2; placeholder++; } else if(event.getActionCommand().equals("Spring")) { quarterNum = 3; placeholder++; } else if(event.getActionCommand().equals("Summer")) { quarterNum = 4; placeholder++; } else if(event.getActionCommand().equals("1st Semester")) { quarterNum = 5; placeholder++; } else if(event.getActionCommand().equals("2nd Semester")) { quarterNum = 6; placeholder++; } if (placeholder == 1) { next(); } } } }
rooseveltcs/personal-secretary
Asking.java
1,925
/*Shows the introduction text to the user. Primarily is instructions and information to the user*/
block_comment
en
false
1,743
19
1,925
20
2,098
18
1,925
20
2,340
20
false
false
false
false
false
true
16947_10
import java.util.*; public class SRT { private ArrayList<Process> processes; private ArrayList<Process> queue; private Process shortest; private ArrayList<Process> completed; private static int QUANTA_MAX = 99; private static int NUMBER_OF_PROCESSES_TO_MAKE = 30; private int quanta; private double totalTurnaroundTime; private double totalWaitTime; private double totalResponseTime; private double processesFinished; private String out; public static void main(String[] args) { ArrayList<Process> processes = new ArrayList<Process>(); for (int i = 1; i <= NUMBER_OF_PROCESSES_TO_MAKE; i++) { Process process = new Process("P" + i, i); processes.add(process); } Process.sortListByArrivalTime(processes); SRT srt = new SRT(processes); String table = ""; for (Process process : srt.getProcesses()) { table += "[Process: " + String.format("%3s", process.getName()) + ", Arrival time: " + String.format("%3d", process.getArrivalTime()) + ", Run time: " + String.format("%3d", process.getGivenExecutionTime()) + ", Priority: " + process.getPriority() + ", End time: " + String.format("%3d", process.getEndTime()) + ", Time started: " + String.format("%3d", process.getStartExecutionTime()) + ", Turnaround time: " + String.format("%3d", process.calculateTurnaroundTime()) + ", Wait time: " + String.format("%3d", process.calculateWaitTime()) + ", Response time: " + String.format("%3d", process.calculateResponseTime()) + "]\n"; } //System.out.println(table); } public SRT(ArrayList<Process> processes) { this.processes = processes; this.queue = new ArrayList<Process>(); this.shortest = null; this.completed = new ArrayList<Process>(); run(); } public ArrayList<Process> getProcesses() { return this.completed; } private void run() { quanta = 0; totalTurnaroundTime = 0; totalWaitTime = 0; totalResponseTime = 0; processesFinished = 0; out = ""; while (quanta < QUANTA_MAX || !queue.isEmpty()) { // Check the current time quanta, and add processes that arrive at the current time to the queue. for (Process process : processes) { if (process.getArrivalTime() <= quanta) { queue.add(process); // processes.remove(process); } } processes.removeAll(queue); // Preemptive code block. if (!queue.isEmpty()) { // Get the process in the queue with the lowest remaining execution time. shortest = queue.get(0); for (Process process : queue) { if (process.getExecutionTimeRemaining() < shortest.getExecutionTimeRemaining()) { shortest = process; } } queue.remove(shortest); // If the current shortest process has not started yet, start it. if (shortest.getStartExecutionTime() < 0 && quanta < QUANTA_MAX) { shortest.setStartExecutionTime(quanta); } // If the process has started if (shortest.getStartExecutionTime() > -1) { // Represent it in the timeline out = out+ "[" + shortest.getName() + "]"; // Decrement the execution time remaining shortest.decrementExecutionTimeRemaining(); // Move the time splice quanta++; // If the shortest process is done (execution time remaining == 0) if (shortest.getExecutionTimeRemaining() <= 0) { // Set its end time at the current quanta shortest.setEndTime(quanta); // Add the finished process to the completed list. completed.add(shortest); processesFinished++; totalTurnaroundTime += shortest.calculateTurnaroundTime(); totalWaitTime += shortest.calculateWaitTime(); totalResponseTime += shortest.calculateResponseTime(); } else { // The process is not done, add it back into the queue. queue.add(shortest); } } } else { out = out+"[*]"; quanta++; } } } public String getAverages() { String averages = "\n" +"Averages turnaround time: " + totalTurnaroundTime / processesFinished +"\n" + "Average wait time: " + totalWaitTime / processesFinished +"\n" + "Average response time: " + totalResponseTime / processesFinished +"\n" + "Throughput: " + processesFinished / quanta + " processes completed per quanta." +"\n"; /*System.out.println("\n"); System.out.println("Average turnaround time: " + totalTurnaroundTime / processesFinished); System.out.println("Average wait time: " + totalWaitTime / processesFinished); System.out.println("Average response time: " + totalResponseTime / processesFinished); System.out.println("Throughput: " + processesFinished / quanta + " processes completed per quanta."); System.out.println();*/ return averages; } public String getOut() { out = out +"\n"; return out; } }
devstudent123/Scheduling-Algorithms
SRT.java
1,363
// If the shortest process is done (execution time remaining == 0)
line_comment
en
false
1,199
16
1,363
16
1,383
15
1,363
16
1,787
16
false
false
false
false
false
true
18261_5
public class oop { public static void main(String[] args) { Pen p1= new Pen();// create a pen obj called p1 p1.size=5; System.out.println("Pen Size: "+p1.size); p1.color="Yellow"; System.out.println("Pen Color: "+p1.color); p1.setColor("Red"); //using setter function instead of direct assignment System.out.println("New Pen Color after using Setter Function :"+p1.getcolor()); p1.setSize(8);//Using getter functions in place of accessing member variable directly System.out.println("Updated pen size:"+p1.getsize()); BankAccount myAcc= new BankAccount(); //myAcc is an object of the type "BankAccount" and it has two instance variables myAcc.usearname="Subhajyoti"; //myAcc.passwors="<PASSWORD>"; Not allowed to access the password directly from //outside of this object, hence we need a method for setting it myAcc.setpassword("<PASSWORD>"); } } //Getter and Setters //Get:to return value //Set:To change or assign or modify values //this:this keyword is used to refer to current object class BankAccount{ public String usearname; private String passwors; public void setpassword(String pwd){ passwors =pwd ; } } class Pen{ String color; int size; String getcolor(){ return this.color; } int getsize(){ return this.size; } void setColor(String newcolor){ color= newcolor; } void setSize(int newsize){ size= newsize; } } // access modifier // acc mode | with in class| outside package | outside package by sub class | outside package // private | y | n | n | n // default | y | y | n | n // protected | y | y | y | n // public | y | y | y | y
tanXnyx/java_dsa
oop.java
511
//outside of this object, hence we need a method for setting it
line_comment
en
false
468
15
511
15
541
15
511
15
579
16
false
false
false
false
false
true
19027_11
/* Copyright (C) 2004 Geoffrey Alan Washburn This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ import java.util.Iterator; /** * An abstract class for representing mazes, and the operations a {@link Client} * in the {@link Maze} may wish to perform.. * @author Geoffrey Washburn &lt;<a href="mailto:[email protected]">[email protected]</a>&gt; * @version $Id: Maze.java 343 2004-01-24 03:43:45Z geoffw $ */ public abstract class Maze { /* Maze Information ****************************************************/ /** * Obtain a {@link Point} describing the size of the {@link Maze}. * @return A {@link Point} where the method <code>getX</code> returns the maximum X * coordintate, and the method <code>getY</code> returns the maximum Y coordinate. */ public abstract Point getSize(); /** * Check whether a {@link Point} is within the bounds of the {@link Maze}. * @return <code>true</code> if the point lies within the {@link Maze}, <code>false</code> otherwise. */ public abstract boolean checkBounds(Point point); /** * Obtain the {@link Cell} corresponding to a given {@link Point} in the {@link Maze}. * @param point Location in the {@link Maze}. * @return A {@link Cell} describing that location. */ public abstract Cell getCell(Point point); /* Client functionality ************************************************/ /** * Add a {@link Client} at random location in the {@link Maze}. * @param client {@link Client} to be added to the {@link Maze}. */ public abstract void addClient(Client client); /** * Create a new {@link Projectile} from the specified {@link Client} * @param client {@link Client} that is firing. * @return <code>false</code> on failure, <code>true</code> on success. */ public abstract boolean clientFire(Client client); /** * Remove the specified {@link Client} from the {@link Maze} * @param client {@link Client} to be removed. */ public abstract void removeClient(Client client); /** * Find out where a specified {@link Client} is located * in the {@link Maze}. * @param client The {@link Client} being located. * @return A {@link Point} describing the location of the client. */ public abstract Point getClientPoint(Client client); /** * Find out the cardinal direction a {@link Client} is facing. * @param client The {@link Client} being queried. * @return The orientation of the specific {@link Client} as a {@link Direction}. */ public abstract Direction getClientOrientation(Client client); /** * Attempt to move a {@link Client} in the {@link Maze} forward. * @param client {@link Client} to move. * @return <code>true</code> if successful, <code>false</code> if failure. */ public abstract boolean moveClientForward(Client client); /** Attempt to move a {@link Client} in the {@link Maze} backward. * @param client {@link Client} to move. * @return <code>true</code> if successful, false if failure. */ public abstract boolean moveClientBackward(Client client); /** * Obtain an {@link Iterator} over all {@link Client}s in the {@link Maze} * @return {@link Iterator} over clients in the {@link Maze}. */ public abstract Iterator getClients(); /** * Add a remote client to the maze in a given location with a given orientation * @param client Client to be added to the maze * @param point The point at which the remote client will spawn * @param dir The starting orientation of the client */ public abstract void addRemoteClient(Client client, Point point, Direction dir); public abstract void addRemoteClientScore(Client client, Point point, Direction dir, int score); public abstract void missiletick(); /* Maze Listeners ******************************************************/ /** * Register an object that wishes to be notified when the maze changes * @param ml An object implementing the {@link MazeListener} interface. * */ public abstract void addMazeListener(MazeListener ml); /** Remove an object from the notification queue * @param ml An object implementing the {@link MazeListener} interface. */ public abstract void removeMazeListener(MazeListener ml); }
sangaani/Lab2
Maze.java
1,225
/** * Find out the cardinal direction a {@link Client} is facing. * @param client The {@link Client} being queried. * @return The orientation of the specific {@link Client} as a {@link Direction}. */
block_comment
en
false
1,175
51
1,228
51
1,281
55
1,225
51
1,426
57
false
false
false
false
false
true
20117_71
/* */ import javafx.event.ActionEvent; /* */ import javafx.geometry.Pos; /* */ import javafx.scene.Node; /* */ import javafx.scene.Parent; /* */ import javafx.scene.Scene; /* */ import javafx.scene.control.Button; /* */ import javafx.scene.control.Label; /* */ import javafx.scene.layout.VBox; /* */ import javafx.stage.Stage; /* */ /* */ public class score /* */ {//This class shows the final score, high score, and keeps track of the overall rounds and winning streaks /* */ public static int p1streak; /* */ public static int p2streak; /* */ public static int p1rounds; /* */ public static int p2rounds; /* */ public static int temp; /* */ public static int temp1; /* 19 */ public static int highscore = 0; /* 20 */ public static int games = 0; /* */ public static void update(int w) { //This method updates the score by tracking how many rounds each player has won, and the high score /* 22 */ games++; /* 23 */ if (games == 3) { /* 24 */ if (w == 1) { /* 25 */ p1streak++; /* 26 */ temp++; /* 27 */ if (temp > highscore) { /* 28 */ highscore = temp; /* */ } /* */ } /* 31 */ if (w == 2) { /* 32 */ p2streak++; /* 33 */ temp1++; /* 34 */ if (temp1 > highscore) { /* 35 */ highscore = temp1; /* */ } /* */ } /* 38 */ if (p1streak > p2streak) { /* 39 */ p1rounds++; /* */ } /* 41 */ if (p2streak > p1streak) { /* 42 */ p2rounds++; /* */ } /* */ /* 45 */ games = 0; /* 46 */ p1streak = 0; /* 47 */ p2streak = 0; /* */ } /* 49 */ if (w == 1) { /* 50 */ p1streak++; /* 51 */ temp++; /* 52 */ if (temp > highscore) { /* 53 */ highscore = temp; /* */ } /* 55 */ health.updateHealth(1); /* */ } /* 57 */ if (w == 2) { /* 58 */ p2streak++; /* 59 */ temp1++; /* 60 */ if (temp1 > highscore) { /* 61 */ highscore = temp1; /* */ } /* 63 */ health.updateHealth(2); /* */ } /* */ } /* */ /* */ /* */ /* */ public static void showScore() {//This class shows the final window with the overall streaks and how many rounds have been won by each player /* 70 */ Stage window = new Stage(); /* 71 */ window.setTitle("Score"); /* */ /* 73 */ Label p1score = new Label("Player one's streak: " + p1streak); /* 74 */ Label p2score = new Label("Player two's streak: " + p2streak); /* 75 */ Label p1Rounds = new Label("Player one's rounds: " + p1rounds); /* 76 */ Label p2Rounds = new Label("Player two's rounds: " + p2rounds); /* */ /* 78 */ Button exit = new Button("Exit"); /* 79 */ exit.setOnAction(e -> window.close()); /* */ /* */ /* */ /* 83 */ VBox layout = new VBox(10.0D); /* 84 */ layout.getChildren().addAll((Object[])new Node[] { (Node)p1score, (Node)p2score, (Node)p1Rounds, (Node)p2Rounds, (Node)exit }); /* 85 */ layout.setAlignment(Pos.CENTER); /* 86 */ Scene scene = new Scene((Parent)layout, 300.0D, 300.0D); /* 87 */ scene.getStylesheets().add("game.css"); /* 88 */ window.setScene(scene); /* 89 */ window.show(); /* */ } /* */ public static void showHighScore() {//THis opens a window that shows the highest score, being the largest amount of rounds won /* 92 */ Stage window = new Stage(); /* 93 */ window.setTitle("High Score"); /* */ /* 95 */ Label p1score = new Label("Highest winning streak: " + highscore); /* */ /* 97 */ Button exit = new Button("exit"); /* 98 */ exit.setOnAction(e -> window.close()); /* */ /* */ /* */ /* 102 */ VBox layout = new VBox(10.0); /* 103 */ layout.getChildren().addAll((Object[])new Node[] { (Node)p1score, (Node)exit }); /* 104 */ layout.setAlignment(Pos.CENTER); /* 105 */ Scene scene = new Scene((Parent)layout, 300.0D, 300.0D); /* 106 */ scene.getStylesheets().add("game.css"); /* 107 */ window.setScene(scene); /* 108 */ window.show(); /* */ } /* */ }
KavitaDoobay/RockPaperScissors
score.java
1,498
//This class shows the final window with the overall streaks and how many rounds have been won by each player
line_comment
en
false
1,381
22
1,498
23
1,466
21
1,498
23
1,541
23
false
false
false
false
false
true
20619_9
/** * Models a simple Car for the game Racer. * * @author Joe Finney ([email protected]) */ public class Car { public static String CAR_COLOUR = "#FF0000"; public static String WHEEL_COLOUR = "#404040"; private Rectangle[] parts = new Rectangle[7]; private double xPosition; private double yPosition; private GameArena arena; private double xSpeed; private double ySpeed; /** * Creates a new Car, at the given location. * * @param x The x position on the screen of the centre of the car. * @param y The y position on the screen of the centre of the car. * @param a The GameArena upon which to draw this car. */ public Car(double x, double y, GameArena a) { parts[0] = new Rectangle(10, 20, 10, 20, WHEEL_COLOUR); parts[1] = new Rectangle(10, 80, 10, 20, WHEEL_COLOUR); parts[2] = new Rectangle(50, 20, 10, 20, WHEEL_COLOUR); parts[3] = new Rectangle(50, 80, 10, 20, WHEEL_COLOUR); parts[4] = new Rectangle(30, 50, 40, 70, CAR_COLOUR); parts[5] = new Rectangle(15, 18, 5, 5, "WHITE"); parts[6] = new Rectangle(45, 18, 5, 5, "WHITE"); arena = a; this.setXPosition(x); this.setYPosition(y); for (int i=0; i < parts.length; i++) arena.addRectangle(parts[i]); } /** * Changes the position of this car to the given location * * @param x The new x positition of this car on the screen. */ public void setXPosition(double x) { double dx = x - xPosition; for (int i=0; i < parts.length; i++) parts[i].setXPosition(parts[i].getXPosition() + dx); xPosition = x; } /** * Changes the position of this car to the given location * * @param y The new y positition of this car on the screen. */ public void setYPosition(double y) { double dy = y - yPosition; for (int i=0; i < parts.length; i++) parts[i].setYPosition(parts[i].getYPosition() + dy); yPosition = y; } /** * Determines the position of this car on the screen * * @return The x position of the centre of this car on the screen. */ public double getXPosition() { return xPosition; } /** * Determines the position of this car on the screen * * @return The y co-ordinate of the centre of this car on the screen. */ public double getYPosition() { return yPosition; } /** * Sets the speed of this car in the X axis - i.e. the number of pixels it moves in the X axis every time move() is called. * * @param s The new speed of this car in the x axis */ public void setXSpeed(double s) { xSpeed = s; } /** * Sets the speed of this car in the Y axis - i.e. the number of pixels it moves in the Y axis every time move() is called. * * @param s The new speed of this car in the y axis */ public void setYSpeed(double s) { ySpeed = s; } /** * Updates the position of this car by a small amount, depending upon its speed. * see setXSpeed() and setYSpeed() methods. */ public void move() { this.setXPosition(xPosition + xSpeed); this.setYPosition(yPosition + ySpeed); } /** * Determines if this car is touching the given RoadSegment. * * @param s The segment of road to test against. * @return true of this car is touching the given road segment, false otherwise. */ public boolean isTouching(RoadSegment s) { Rectangle[] roadParts = s.getParts(); for (int i=0; i < parts.length; i++) for (int j=0; j < roadParts.length; j++) if(parts[i].isTouching(roadParts[j])) return true; return false; } }
finneyj/Racer
Car.java
1,126
/** * Determines if this car is touching the given RoadSegment. * * @param s The segment of road to test against. * @return true of this car is touching the given road segment, false otherwise. */
block_comment
en
false
1,061
49
1,126
51
1,199
54
1,126
51
1,305
59
false
false
false
false
false
true
21019_2
import java.util.*; public class Hotel { public static void main(String[] args) { // ["+1A", "+3E", "-1A", "+4F", "+1A", "-3E"] String[] books1 = { "+1A", "+3E", "-1A", "+4F", "+1A", "-3E" }; String[] books2 = {"+1A","+3F","+2B"}; String[] books3 = {"+1E", "-1E", "+1E", "-1E", "+1E", "-1E", "+1E", "-1E","+2A", "-2A", "+2A", "-2A", "+2A", "-2A", "+2A", "-2A","+2B", "-2B", "+2B", "-2B", "+2B", "-2B", "+2B", "-2B"}; System.out.println(solution(books1)); System.out.println(solution(books2)); System.out.println(solution(books3)); } static class Room implements Comparable<Room>{ public String no; public int book; public Room(String no) { this.no = no; } @Override // The compareTo method is a little bit differet from my orignal solution. // I use all the time to figure why my code give a null pointer exception. // Hence, I don't have time to check the result of my compareTo. // The compareTo method in my solution will give an opposite result of this one. public int compareTo(Room o) { if (this.book < o.book) { return -1; } else if (this.book > o.book) { return 1; } else { return -this.no.compareTo(o.no); } } } private static String solution(String[] A) { Room[] res = new Room[260]; for(int i = 0 ; i < res.length; i++) { char[] ch = new char[2]; char f = (char)(i/26 + '0'); char n = (char)(i%26 + 'A'); ch[0] = f; ch[1] = n; res[i] = new Room(new String(ch)); } for(String str : A) { if(str.charAt(0) == '+') { int floor = str.charAt(1) - '0'; int cell = (str.charAt(2) - 'A'); int id = floor * 26 + cell; res[id].book += 1; // This line give a nullPointerException } } Arrays.sort(res); return res[res.length - 1].no; } }
ruoyangqiu/Leetcode
Hotel.java
701
// I use all the time to figure why my code give a null pointer exception.
line_comment
en
false
615
17
701
17
703
17
701
17
828
17
false
false
false
false
false
true
22558_12
package posix; /** Read and write memory reachable through a C ptr. Memory access is bounds checked to keep it within the size of region addressed by the C ptr. Only classes within the posix package can create CPtr objects, and the use of this class is completely safe at present. This is because we know the size of, for instance, shared memory segments or memory allocated with C malloc. At some future date, we may need the ability to dereference arbitrary C pointers - those dereferences will be unsafe. <p> We have not yet implemented the floating and 64-bit types for get/set due to a lack of need. @author <a href="mailto:[email protected]">Stuart D. Gathman</a> Copyright (C) 1998 Business Management Systems, Inc. <br> <p> This code is distributed under the <a href="http://www.gnu.org/copyleft/lgpl.html"> GNU Library General Public License </a> <p> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. <p> This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. <p> You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ public class CPtr { long addr; int size; /** A null CPtr value. */ static final long NULL = getNULL(); CPtr() { } CPtr(long addr,int size) { this.addr = addr; this.size = size; } private static final long getNULL() { System.loadLibrary("posix"); return init(); } private static native long init(); /** Type codes for <code>alignOf()</code> and <code>sizeOf()</code>. */ public static final int CBYTE_TYPE = 0, CSHORT_TYPE = 1, CINT_TYPE = 2, CLONG_TYPE = 3, CFLT_TYPE = 4, CDBL_TYPE = 5, CPTR_TYPE = 6; /** Get the alignment of a C type. Can be used to compute C struct offsets in a mostly system independent manner. */ public static native int alignOf(int type); /** Get the size of a C type. Can be used to compute C struct offsets in a mostly system independent manner. */ public static native int sizeOf(int type); /** Compute the offsets of a C struct one member at a time. This is supposed to reflect what a C compiler would do. I can't think of a better way to track C data structs with code that doesn't get recompiled. A config file could do it, but would be even more work. Some C compilers will do surprising things - like padding structs that contain only 'char' members. They do this to avoid cache misses at the beginning of the struct - or to make struct pointers uniform on word addressable machines (e.g. PDP20). You can work around this for now with the <code>addMember</code> method - provided you can figure out <u>when</u> to do so. Please report any problems you encounter - we can add additional native methods, e.g. 'structAlign' to return minimum struct alignment. */ public static class Struct { private int offset = 0; private int align = 0; // maximum alignment in struct /** Initialize with the offset (within a CPtr) of the C struct. */ public Struct(int offset) { this.offset = offset; } /** Return the offset of the next member. */ public final int offsetOf(int type) { return offsetOf(type,1); } /** Return the offset of the next array member. */ public final int offsetOf(int type,int len) { return addMember(len * sizeOf(type),alignOf(type) - 1); } /** Add a member by size and alignment mask. Return the member offset. */ public final int addMember(int size,int mask) { int pos = (offset + mask) & ~mask; // align for this member offset = pos + size; if (mask > align) align = mask; return pos; } /** Return the offset of a nested struct. The members must have already been added to the nested struct so that it will have the proper size and alignment. */ public final int offsetOf(Struct s,int cnt) { return addMember(cnt * s.size(),s.align); } /** Return total struct size including padding to reflect maximum alignment. */ public final int size() { return (offset + align) & ~align; } } /** Copy bytes out of C memory into a Java byte array. */ public native void copyOut(int off,byte[] ba,int pos,int cnt); /** Copy a Java byte array into C memory. */ public native void copyIn(int off,byte[] ba,int pos,int cnt); public native byte getByte(int off); public native void setByte(int off,byte val); public native short getShort(int off); public native void setShort(int off,short val); public native int getInt(int off); public native void setInt(int off,int val); public native short getCShort(int off,int idx); public native void setCShort(int off,int idx,short val); public native int getCInt(int off,int idx); public native void setCInt(int off,int idx,int val); public short getCShort(int off) { return getCShort(off,0); } public void setCShort(int off,short val ) { setCShort(off,0,val); } public int getCInt(int off) { return getCInt(off,0); } public void setCInt(int off,int val) { setCInt(off,0,val); } }
delonnewman/java-posix
CPtr.java
1,503
/** Return the offset of a nested struct. The members must have already been added to the nested struct so that it will have the proper size and alignment. */
block_comment
en
false
1,414
36
1,503
37
1,592
38
1,503
37
1,698
39
false
false
false
false
false
true
24100_9
/** * @author Alena Fisher */ import java.util.ArrayList; public class Coach { // Creating instance variables private String name; private String title; private String department; private String officeLocation; private String phoneNumber; private String email; public Coach(String name, String title, String department, String officeLocation, String phoneNumber, String email) { /** * This method receives 'name', 'title', 'department', 'officeLocation', 'phoneNumber', and 'email' as explicit parameters and assigns them to the instance variables */ this.name = name; this.title = title; this.department = department; this.officeLocation = officeLocation; this.phoneNumber = phoneNumber; this.email = email; } public String getCoachName() { /** * This method returns the coach's name */ return name; } public String getOfficeLocation() { /** * This method returns the coach's office location */ return officeLocation; } public String getTitle() { /** * This method returns the coach's title */ return title; } public String getDepartment() { /** * This method returns the coach's department */ return department; } public String getPhoneNumber() { /** * This method returns the coach's phone number */ return phoneNumber; } public String getEmail() { /** * This method returns the coach's email address */ return email; } public void setCoachName(String name) { /** * This method receives 'name' as an explicit parameter and assigns it to the instance variable */ this.name = name; } public void setOfficeLocation(String officeLocation) { /** * This method receives 'officeLocation' as an explicit parameter and assigns it to the instance variable */ this.officeLocation = officeLocation; } public void setTitle(String title) { /** * This method receives 'title' as an explicit parameter and assigns it to the instance variable */ this.title = title; } public void setDepartment(String department) { /** * This method receives 'department' as an explicit parameter and assigns it to the instance variable */ this.department = department; } public void setPhoneNumber(String phoneNumber) { /** * This method receives 'phoneNumber' as an explicit parameter and assigns it to the instance variable */ this.phoneNumber = phoneNumber; } public void setEmail(String email) { /** * This method receives 'email' as an explicit parameter and assigns it to the instance variable */ this.email = email; } }
AlenaFisher/CS234
S3/Coach.java
606
/** * This method receives 'name' as an explicit parameter and assigns it to the instance variable */
block_comment
en
false
576
23
606
22
727
25
606
22
777
27
false
false
false
false
false
true
24927_5
// 1 dist, 1 exe build in the package ReleaseTemplate.release("community") { distribution("standard").from { exe = Launch4jExeTemplate.exe { from = "/release/standard/exe" } companionFiles = "/release/standard/companion" } } // or could we do dist ? ReleaseTemplate.release("community") { dist { exe = Launch4jExeTemplate.exe { from = "/release/standard/exe" } companionFiles = "/release/standard/companion" } } // or with a distribution template, could be shortened still more ReleaseTemplate.release("community") { distribution("standard").from { template = Launch4jDistributionTemplate.dist { resourcesDir = "/release/standard" } } } // or better yet? ReleaseTemplate.release("community") { dist(Launch4jDistributionTemplate){ resourcesDir = "/release/community/gui" } } // or better yet? // we can translate the release name from either camel case or snake case. // The distribution will assume we are using the default distribution (for this release name) if none // is provided we can either create or retrieve it as necessary. task communityRelease { dist(Launch4jDistributionTemplate){ resourcesDir = "/release/community/gui" } } // accessors releases.community.distributions.community.resourcesDir releases.community.distributions.community.exeTask releases.community.distributions.community.distributionBuildTask releases.community.distributions.community.distributionAssembleTask // 1 dist, 2 exe builds in the package // N.B. would require that the names of the outputs from the exe tasks MUST be different! ReleaseTemplate.release("community") { dist { template = Launch4jDistributionTemplate.dist { exe("gui") { resourcesDir = "/release/community/gui" custom { headerType = "gui" } } exe("console") { resourcesDir = "/release/community/console" custom { headerType = "console" } } } } } // or this! We could define some kind of an interface // that would require either a no-args constructor // or a constructor(Project). ReleaseTemplate.release("community") { dist(Launch4jDistributionTemplate){ exe("gui") { resourcesDir = "/release/community/gui" config { headerType = "gui" } } exe("console") { resourcesDir = "/release/community/console" config { headerType = "console" } } } } // or, considering launch4j.properties... task communityRelease(type: ReleaseTemplateTask) { dist(Launch4jDistributionTemplate){ exe("gui") { resourcesDir = "/release/community/shared" config("/release/shared/launch4j.properties") { myCustomProperty = "someCustomValue" dependsOn someCustomJarTask copyConfigurable = someCustomJarTask.outputs.files } } exe("console") { resourcesDir = "/release/community/shared" } } } // 2 dist, 1 exe in each package ReleaseTemplate.release("allEditions") { distribution("community").from { template = Launch4jDistributionTemplate.dist { resourcesDir = "/editions/community" } } distribution("ultimate").from { template = Launch4jDistributionTemplate.dist { resourcesDir = "/editions/ultimate" } } } // 2 dist, 2 exe builds in each package ReleaseTemplate.release("community") { dist("community", Launch4jDistributionTemplate){ exe("gui") { resourcesDir = "/release/community/gui" // copies exe build info and companions custom { headerType = "gui" } } exe("console") { resourcesDir = "/release/community/console" custom { headerType = "console" } } } dist("ultimate", Launch4jDistributionTemplate){ exe("gui") { resourcesDir = "/release/ultimate/gui" custom { headerType = "gui" } } exe("console") { resourcesDir = "/release/ultimate/console" custom { headerType = "console" } } } } // and considering breaking the whole thing down into more manageable pieces task communityDistribution(type: Launch4jDistributionTemplateTask) { exe("gui", Launch4jExeTemplate) { resourcesDir = "/release/community/shared" config("/release/shared/launch4j.properties") { myCustomProperty = "someCustomValue" dependsOn someCustomJarTask copyConfigurable = someCustomJarTask.outputs.files } } exe("console", Launch4jExeTemplate) { resourcesDir = "/release/community/shared" } } // and breaking the exe build out of the distribution... task communityDisributionGuiExe(type: Launch4jExeTemplateTask) { resourcesDir = "/release/community/shared" config { myCustomProperty = "someCustomValue" dependsOn someCustomJarTask copyConfigurable = someCustomJarTask.outputs.files } }
alessandroscarlatti/launch4j-gradle-plugin
syntax-demo.java
1,337
// we can translate the release name from either camel case or snake case.
line_comment
en
false
1,167
15
1,337
15
1,312
15
1,337
15
1,569
17
false
false
false
false
false
true
25044_13
import java.util.Random; /** * A Deck of 52 Cards which can be dealt and shuffled * * Some functions could be made much faster with some extra memory. * I invite anyone to do so ;-) * * <P>Source Code: <A HREF="http://www.cs.ualberta.ca/~davidson/poker/src/poker/Deck.java">Deck.java</A><P> * * @author Aaron Davidson * @version 1.0.1 */ public class Deck { public static final int NUM_CARDS = 52; private Card[] gCards = new Card[NUM_CARDS]; private char position; private Random r = new Random(); /** * Constructor. */ public Deck() { position = 0; for (int i=0;i<NUM_CARDS;i++) { gCards[i] = new Card(i); } } /** * Constructor w/ shuffle seed. * @param seed the seed to use in randomly shuffling the deck. */ public Deck(long seed) { this(); if (seed == 0) seed = System.currentTimeMillis(); r.setSeed(seed); } /** * Places all cards back into the deck. * Note: Does not sort the deck. */ public void reset() { position = 0; } /** * Shuffles the cards in the deck. */ public void shuffle() { Card tempCard; int i,j; for (i=0; i<NUM_CARDS; i++) { j = i + randInt(NUM_CARDS-i); tempCard = gCards[j]; gCards[j] = gCards[i]; gCards[i] = tempCard; } position = 0; } /** * Obtain the next card in the deck. * If no cards remain, a null card is returned * @return the card dealt */ public Card deal() { return (position < NUM_CARDS ? gCards[position++] : null); } /** * Find position of Card in Deck. */ public int findCard(Card c) { int i = position; int n = c.getIndex(); while (i < NUM_CARDS && n != gCards[i].getIndex()) i++; return (i < NUM_CARDS ? i : -1); } private int findDiscard(Card c) { int i = 0; int n = c.getIndex(); while (i < position && n != gCards[i].getIndex()) i++; return (n == gCards[i].getIndex() ? i : -1); } /** * Remove all cards in the given hand from the Deck. */ public void extractHand(Hand h) { for (int i=1;i<=h.size();i++) this.extractCard(h.getCard(i)); } /** * Remove a card from within the deck. * @param c the card to remove. */ public void extractCard(Card c) { int i = findCard(c); if (i != -1) { Card t = gCards[i]; gCards[i] = gCards[position]; gCards[position] = t; position++; } else { System.err.println("*** ERROR: could not find card " + c); } } /** * Remove and return a randomly selected card from within the deck. */ public Card extractRandomCard() { int pos = position+randInt(NUM_CARDS-position); Card c = gCards[pos]; gCards[pos] = gCards[position]; gCards[position] = c; position++; return c; } /** * Return a randomly selected card from within the deck without removing it. */ public Card pickRandomCard() { return gCards[position+randInt(NUM_CARDS-position)]; } /** * Place a card back into the deck. * @param c the card to insert. */ public void replaceCard(Card c) { int i = findDiscard(c); if (i != -1) { position--; Card t = gCards[i]; gCards[i] = gCards[position]; gCards[position] = t; } } /** * Obtain the position of the top card. * (the number of cards dealt from the deck) * @return the top card index */ public int getTopCardIndex() { return position; } /** * Obtain the number of cards left in the deck */ public int cardsLeft() { return NUM_CARDS-position; } /** * Obtain the card at a specific index in the deck. * Does not matter if card has been dealt or not. * If i < topCardIndex it has been dealt. * @param i the index into the deck (0..51) * @return the card at position i */ public Card getCard(int i) { return gCards[i]; } public String toString() { StringBuffer s = new StringBuffer(); s.append("* "); for (int i=0;i<position;i++) s.append(gCards[i].toString()+" "); s.append("\n* "); for (int i=position;i<NUM_CARDS;i++) s.append(gCards[i].toString()+" "); return s.toString(); } private int randInt(int range) { return (int)(r.nextDouble()*range); } }
lukassaul/kelly-poker
Deck.java
1,429
/** * Obtain the number of cards left in the deck */
block_comment
en
false
1,190
15
1,433
15
1,510
17
1,429
14
1,725
19
false
false
false
false
false
true
25245_0
//write a program to calculate the area of square & rectangle overloading the area method. class p6 { void area(int l) { System.out.println("Area of square=> "+(l*l)); } void area(int l,int b) { System.out.println("Area of Rectangle=> "+(l*b)); } public static void main(String []args) { p6 one=new p6(); one.area(6); one.area(8,8); } }
Rutvik5o/Practice-Programming
p6.java
128
//write a program to calculate the area of square & rectangle overloading the area method.
line_comment
en
false
109
19
128
19
151
17
128
19
155
18
false
false
false
false
false
true
25670_6
/* * class Customer defines a registered customer. It keeps track of the customer's name and address. * A unique id is generated when when a new customer is created. * * Implement the Comparable interface and compare two customers based on name */ public class Customer implements Comparable<Customer> { private String id; private String name; private String shippingAddress; Cart cart; /** Main constructor that creates a customer with their specified id, name and address. * * @param id - is the string id of the customer. * @param name - is the string name of the customer. * @param address - is the address of the customer in a string. */ public Customer(String id, String name, String address) { this.id = id; this.name = name; this.shippingAddress = address; cart = new Cart(id); } /** Constructor for customer. * @param id - is the assigned id to a customer. */ public Customer(String id) { this.id = id; this.name = ""; this.shippingAddress = ""; } /** Constructor that creates a customer with their specified id, name, address and cart. * * @param id - is the string id of the customer. * @param name - is the string name of the customer. * @param address - is the address of the customer in a string. * @param cart - is the cart assigned to the customer */ public Customer(String id, String name, String address, Cart cart) { this.id = id; this.name = name; this.shippingAddress = address; this.cart = cart; } /** Gets the id of the customer. * @return the id of the customer. */ public String getId() { return id; } /* * Set the id for the customer. */ public void setId(String id) { this.id = id; } /** Gets the name of the customer. * @return the name of the customer. */ public String getName() { return name; } /* * Set the name of the customer. */ public void setName(String name) { this.name = name; } /** Gets the shipping address of the customer. * @return the shipping address of the customer. */ public String getShippingAddress() { return shippingAddress; } /* * Set the shipping address of the customer. */ public void setShippingAddress(String shippingAddress) { this.shippingAddress = shippingAddress; } /** Gets the cart that belongs to the customer. * @return the customer's cart. */ public Cart getCustCart() { return cart; } /* * Gives a string representation of the customer object. * Prints the name, id and shipping address of the customer as a formatted string. */ public void print() { System.out.printf("\nName: %-20s ID: %3s Address: %-35s", name, id, shippingAddress); } /* * Two customers are equal if they have the same product Id. * This method is inherited from superclass Object and overridden here */ public boolean equals(Object other) { Customer otherC = (Customer) other; return this.id.equals(otherC.id); } //compareTo method (comparable interface) for SORTCUSTS action public int compareTo(Customer otherCust) { return this.getName().compareTo(otherCust.getName()); } }
jenniferchung14/E-Commerce-System-Simulator
Customer.java
912
/** Gets the name of the customer. * @return the name of the customer. */
block_comment
en
false
785
20
912
22
980
22
912
22
1,059
23
false
false
false
false
false
true
26033_2
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.temporal.TemporalField; import java.util.concurrent.Exchanger; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; public class ForumDB { private Connection connection; private int id = 0; /* * Constructor for the ForumDB class * * @return a new forumdb object */ public ForumDB() { try { Class.forName("org.sqlite.JDBC"); connection = DriverManager.getConnection("JDBC:sqlite:forum.db"); } catch (Exception e) { e.printStackTrace(); } } /* * Prints all the users from the database */ public void printUsers() { try { var s = connection.createStatement(); System.out.println("Current users:"); var rs = s.executeQuery("select name from Users;"); while (rs.next()) { System.out.println(rs.getString("name")); } s.close(); } catch (Exception e) { e.printStackTrace(); } } /* * Adds a new subforum to the forum * * @param name the name of the subforum to be added */ public void addSubforum(String name) { try { var ps = connection.prepareStatement("INSERT INTO Subforum (name) VALUES (?);"); ps.setString(1, name); ps.executeUpdate(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } /* * Adds a new post to the subforum * * @param subforum_id id of the subforum where post is to be added * @param post_title heading of the post to be added * @param post_body body, the text of the forum post to be added * @param post_date the purported date when the post was posted * @param userid the id of the user who posted the post */ public void addPostToSubforum(int subforum_id, String post_title, String post_body, String post_date, int userid) { try { String post_text = post_title.toUpperCase() + "\n\n" + post_body; var ps = connection.prepareStatement("INSERT INTO Posts (userid, subforumid, time, text) VALUES (?, ?, ?, ?);"); ps.setInt(1, userid); ps.setInt(2, subforum_id); ps.setString(3, post_date); ps.setString(4, post_text); ps.executeUpdate(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } /* * Censors a subforum post based on id * * @param postID the id of the post to be censored. */ public void censorPost (int postID) { try { var ps = connection.prepareStatement("UPDATE Posts SET body = '[CENSORED]' WHERE id = ?;"); ps.setInt(1, postID); ps.executeUpdate(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } /* * Sets the body of the post to a specified string. * * @param postID id of the post to be altered * @param body the text string that the body of the post is going to be replaced with */ public void setPostBody (int postID, String body) { try { var ps = connection.prepareStatement("UPDATE Posts SET text = ? WHERE id = ?;"); ps.setString(1, body); ps.setInt(2, postID); ps.executeUpdate(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } /* * Adds a user to the list of moderators based on the id * * @param userID id of the user to be promoted to the moderator status */ public void appointModerator(int userID) { try { var ps = connection.prepareStatement("INSERT INTO ModeratorList (userid) SELECT Users.id FROM Users WHERE Users.id = ?;"); ps.setInt(1, userID); ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } } /* * Gets the name of the user with the specified id * * @param userid id of the user to get the username of * @return the name of the user */ public String getUserName(int userid) { try { var ps = connection.prepareStatement("select name from Users where id = ?;"); ps.setInt(1, userid); var rs = ps.executeQuery(); rs.next(); System.out.println(rs.getString("name")); String name = rs.getString("name"); ps.close(); return name; } catch (Exception e) { e.printStackTrace(); return e.getStackTrace().toString(); } } /* * set */ public void setUserName(int userid, String name) { try { var ps = connection.prepareStatement("UPDATE Users SET name=? where id = ?;"); ps.setString(1, name); ps.setInt(2, userid); ps.executeUpdate(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } public Post createPost(String title, String body, Date date, int authorId) { int postID = -1; //is supposed to be a post containing [ERROR] try { var ps = connection.prepareStatement("INSERT INTO Posts (title, body, userid, date) VALUES (?, ?, ?, ?) RETURNING id ;"); ps.setString(1, title); ps.setString(2, body); ps.setInt(3, authorId); ps.setString(4, new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())); var rs = ps.executeQuery(); postID = rs.getInt("id"); rs.close(); ps.close(); return new Post(postID, this); } catch (Exception e) { e.printStackTrace(); return new Post(postID, this); } } public String getPostTitle(int id) { try { var ps = connection.prepareStatement("SELECT title FROM Posts WHERE id = ?;"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); String title = rs.getString("title"); ps.close(); rs.close(); return title; } catch (Exception e) { e.printStackTrace(); return "[ERROR]" + e.getStackTrace(); } } public String getPostBody(int postId) { try { var ps = connection.prepareStatement("SELECT body FROM Posts WHERE id = ?;"); ps.setInt(1, postId); ResultSet rs = ps.executeQuery(); String body = rs.getString("body"); ps.close(); rs.close(); return body; } catch (Exception e) { e.printStackTrace(); return "[ERROR]" + e.getStackTrace(); } } public String getPostDate(int id) { try { var ps = connection.prepareStatement("SELECT date FROM Posts WHERE id = ?;"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); String date = rs.getString("date"); ps.close(); rs.close(); return date; } catch (Exception e) { e.printStackTrace(); return new Date().toString(); } } public String getPostAuthor(int postId) { try { var ps = connection.prepareStatement("SELECT name FROM Users, Posts WHERE Posts.userid = Users.id AND Posts.id = ?;"); ps.setInt(1, postId); ResultSet rs = ps.executeQuery(); String name = rs.getString("name"); ps.close(); rs.close(); return name; } catch (Exception e) { e.printStackTrace(); return "[ERROR]"; } } public Subforum[] getSubforums() { List<Subforum> subforums = new ArrayList<Subforum>(); try { var s = connection.createStatement(); var rs = s.executeQuery("SELECT id FROM Subforum;"); while (rs.next()) { subforums.add(new Subforum(rs.getInt("id"), this)); } s.close(); rs.close(); } catch (Exception e) { e.printStackTrace(); } return subforums.toArray(new Subforum[0]); } public String getSubforumTitle(int id) { try { var ps = connection.prepareStatement("SELECT name FROM Subforum WHERE id = ?;"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); String title = rs.getString("name"); ps.close(); rs.close(); return title; } catch (Exception e) { e.printStackTrace(); return "[ERROR]" + e.getStackTrace(); } } public Post[] getSubforumPosts(int subforum_id) { List<Post> posts = new ArrayList<Post>(); try { var ps = connection.prepareStatement("SELECT id FROM Posts WHERE subforumid = ?;"); ps.setInt(1, subforum_id); var rs = ps.executeQuery(); while (rs.next()) { posts.add(new Post(rs.getInt("id"), this)); } ps.close(); rs.close(); } catch (Exception e) { e.printStackTrace(); } return posts.toArray(new Post[0]); } public void postPostToSubforum(int subforum_id, int post_id) { try { var ps = connection.prepareStatement("UPDATE Posts SET subforumid = ? WHERE id = ?;"); ps.setInt(1, subforum_id); ps.setInt(2, post_id); ps.executeUpdate(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } public void removePostFromSubforum(int post_id) { try { var ps = connection.prepareStatement("UPDATE Posts SET subforumid = NULL WHERE id = ?;"); ps.setInt(1, post_id); ps.executeUpdate(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } private boolean isUserAdmin(int userid) { boolean result = false; try { var ps = connection.prepareStatement("SELECT * FROM AdminList WHERE userid = ?;"); ps.setInt(1, userid); ResultSet rs = ps.executeQuery(); if(rs.isBeforeFirst()) { // it returned something result = true; } ps.close(); rs.close(); } catch (Exception e) { e.printStackTrace(); } return result; } private boolean isUserModerator(int userid) { boolean result = false; try { var ps = connection.prepareStatement("SELECT * FROM ModeratorList WHERE userid = ?;"); ps.setInt(1, userid); ResultSet rs = ps.executeQuery(); if(rs.isBeforeFirst()) { // it returned something result = true; } ps.close(); rs.close(); } catch (Exception e) { e.printStackTrace(); } return result; } public User getUser(int userid) { try { if(getUserName(userid).equals("null")) { return null; } else if (isUserAdmin(userid)) { return new Admin(userid, this); } else if (isUserModerator(userid)) { return new Moderator(userid, this); } else { return new User(userid, this); } } catch (Exception e) { e.printStackTrace(); return null; } } }
c00291296/java-forum
ForumDB.java
2,715
/* * Adds a new subforum to the forum * * @param name the name of the subforum to be added */
block_comment
en
false
2,458
32
2,715
29
3,029
34
2,715
29
3,268
35
false
false
false
false
false
true
27718_2
// https://www.hackerearth.com/practice/data-structures/disjoint-data-strutures/basics-of-disjoint-data-structures/practice-problems/algorithm/marriage-problem/editorial/ /* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Ideone { int parent[], women[], men[], size[]; public void union(int a, int b) { int u = find(a); int v = find(b); if (u == v) return; if (size[u] > size[v]) { parent[v] = u; women[u] += women[v]; men[u] += men[v]; size[u] += size[v]; } else { parent[u] = v; women[v] += women[u]; men[v] += men[u]; size[v] += size[u]; } } public int find(int a) { while (parent[a] != a) { a = parent[a]; } return a; } public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); int x = sc.nextInt(), y = sc.nextInt(), q1 = sc.nextInt(); parent = new int[x+y]; men = new int[x+y]; women = new int[x+y]; size = new int[x+y]; for (int i = 0; i < x+y; i++) { parent[i] = i; size[i] = 1; women[i] = 0; men[i] = 0; if (i < x) men[i] = 1; else women[i] = 1; } while(q1--) { a = sc.nextInt(); b = sc.nextInt(); union(a, b); } int q2 = sc.nextInt(); while(q2--) { a = sc.nextInt()+x; b = sc.nextInt()+x; union(a, b); } int q3 = sc.nextInt(); while(q3--) { a = sc.nextInt(); b = sc.nextInt()+x; union(a, b); } HashMap<Integer, LinkedList<Integer>> cc = new HashMap<Integer, LinkedList<Integer>>(); int ans = 0; for (for int i = 0; i < x; i++) { ans += (y - women[find(i)]); } System.out.println(ans); } }
maiquynhtruong/algorithms-and-problems
marriage-problem.java
699
/* Name of the class has to be "Main" only if the class is public. */
block_comment
en
false
561
19
699
19
692
19
699
19
807
19
false
false
false
false
false
true
29683_0
public class House implements Cloneable, Comparable<House> { private int id; private double area; private java.util.Date whenBuilt; public House(int id, double area) { this.id = id; this.area = area; whenBuilt = new java.util.Date(); } public int getId() { return id; } public double getArea() { return area; } public java.util.Date getWhenBuilt() { return whenBuilt; } @Override /** Override the protected clone method defined in the Object class, and strengthen its accessibility */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException ex) { return null; } } @Override // Implement the compareTo method defined in Comparable public int compareTo(House o) { if (area > o.area) return 1; else if (area < o.area) return -1; else return 0; } }
rdejong/LiangJava
House.java
234
/** Override the protected clone method defined in the Object class, and strengthen its accessibility */
block_comment
en
false
223
19
234
20
276
20
234
20
297
23
false
false
false
false
false
true
36167_11
/** * Represents a job for an elevator, containing information about the destination floor, pickup floor, timestamp, button pressed, and any faults. * @authors Sami Mnif, Muaadh Ali, Jalal Mourad, Jordan Bayne */ import java.io.Serializable; public class Job implements Serializable { private String timeStamp; private int destinationFloor, pickupFloor; public int capacity; private String button; private int fault; /** * Constructs a new job with the specified parameters. * * @param timeStamp the timestamp of the job * @param destinationFloor the destination floor of the job * @param pickupFloor the pickup floor of the job * @param button the button pressed for the job * @param fault the fault status of the job */ public Job(String timeStamp, int destinationFloor, int pickupFloor, String button, int fault) { capacity = 1; this.timeStamp = timeStamp; this.destinationFloor = destinationFloor; this.pickupFloor = pickupFloor; this.button = button; this.fault = fault; } /** * Gets the timestamp of the job. * * @return the timestamp */ public String getTimeStamp() { return timeStamp; } /** * Gets the destination floor of the job. * * @return the destination floor */ public int getDestinationFloor() { return destinationFloor; } /** * Gets the pickup floor of the job. * * @return the pickup floor */ public int getPickupFloor() { return pickupFloor; } /** * Gets the button pressed for the job. * * @return the button pressed */ public String getButton() { return button; } /** * Sets the timestamp of the job. * * @param timeStamp the new timestamp */ public void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } /** * Sets the destination floor of the job. * * @param destinationFloor the new destination floor */ public void setDestinationFloor(int destinationFloor) { this.destinationFloor = destinationFloor; } /** * Sets the pickup floor of the job. * * @param pickupFloor the new pickup floor */ public void setPickupFloor(int pickupFloor) { this.pickupFloor = pickupFloor; } /** * Sets the button pressed for the job. * * @param button the new button pressed */ public void setButton(String button) { this.button = button; } /** * Sets the fault status of the job. * * @param fault the new fault status */ public void setFault(int fault) { this.fault = fault; } /** * Gets the fault status of the job. * * @return the fault status */ public int getFault() { return fault; } }
Samimnif/SYSC3303-Elevator-Sim
Job.java
677
/** * Gets the fault status of the job. * * @return the fault status */
block_comment
en
false
644
23
677
22
734
26
677
22
842
27
false
false
false
false
false
true
37469_36
/** * Represents time - hours:minutes. * @author Michal Danishevsky * @vertion 20.04.2020 */ public class Time1{ private int _hour; private int _minute; final int MAXIMUM_MINUTES=60; final int MINIMUM_MINUTES=0; final int MAXIMUM_HOURS=24; final int MINIMUM_HOURS=0; /** * Constructs a Time1 object * @param h Time's hour * @param m Time's minute */ public Time1(int h,int m){ /* _hour get the given hour if given hour in the * range of hour and get the value 0 if not */ if(h < MAXIMUM_HOURS && h > MINIMUM_HOURS) _hour=h; else _hour=0; /* _minute get the given minute if given minute in the * range of minute and get 0 if not */ if(m < MAXIMUM_MINUTES && m > MINIMUM_MINUTES) _minute=m; else _minute=0; }//end of Time1 /** * Copy the hour and minutes from other time to this time * @param other The time object from which to construct the new time */ public Time1(Time1 other){ _hour=other._hour; _minute=other._minute; }//end of Time1 /** * Return the time's hour * @return Time's hour */ public int getHour(){ return _hour; }//end of getHour /** * Return the time's minute * @return Time's minute */ public int getMinute(){ return _minute; }//end of getMinute /** * Sets the time's hour to new given hour if the new given hour * in the range of hour if not the hour stay the same hour * @param num New hour */ public void setHour(int num){ if(num < MAXIMUM_HOURS && num > MINIMUM_HOURS) _hour = num; }//end of setHour /** * Sets the time's minute to new given minute if the new given minute * in the range of minute if not the minute stay the same minute * @param num New minute */ public void setMinute(int num){ if(num < MAXIMUM_MINUTES && num > MINIMUM_MINUTES) _minute = num; }//end of setMinute /** * Returns a string representation of this time ("hh:mm") * @return This time in pattern hh:mm */ public String toString(){ if(_hour < 10 && _minute < 10) return "0" + _hour + ":" + 0 + _minute; //the minute and the hour are smaller than ten else if(_hour < 10) return "0" + _hour + ":" + _minute; //only the minute is bigger than ten else if(_minute < 10) return _hour + ":" + 0 + _minute; //only the hour is bigger than ten else return _hour + ":" + _minute; //the minute and the hour are bigger than ten }//end of toString /** * Return how much minutes passed from the midnight (00:00) * @return The minutes from midnight */ public int minFromMidnight(){ return (_hour * MAXIMUM_MINUTES + _minute); }//end of minFromMidnight /** * Checks if the received time is equal to this time * @param other The time to be compared with this time * @return True if they are the same time and * false if they are differents times */ public boolean equals(Time1 other){ if(_minute == other._minute && _hour == other._hour) return true;//there is the same time else return false;//they are differents times }//end of equals /** * Check if this time before the other time * @param other The time to be compared with this time * @return True if this time before the other time else it is return false */ public boolean before(Time1 other){ if(_hour == other._hour) if(_minute < other._minute) return true;//this time before the other time if(_hour < other._hour) return true;//this time before the other time else return false;/* they are the same time or the other time before this time */ }//end of before /** * Check if this time after the other time * @param other The time to be compared with this time * @return True if this time before the other time else it is return false */ public boolean after(Time1 other){ if(other.before(this)) return true;/*other time is before this time so this time after the other time*/ else return false;/*the times are equals or other time is after this time*/ }//end of after /** * Calculates the difference (in minutes) between two times. * Assumption: this time is after other time * @param other The time to check the difference * @return The difference in minute */ public int difference(Time1 other){ int totalMinuteDifference; int minuteDifference = _minute - other._minute;//minutes difference int hourDifference = _hour - other._hour;//hour difference /*minutes can't to be negetive so if it happend need convert hour to minutes*/ if(minuteDifference < MINIMUM_MINUTES){ hourDifference--; minuteDifference = minuteDifference + MAXIMUM_MINUTES; }//end of if //total the difference in minutes totalMinuteDifference = minuteDifference + MAXIMUM_MINUTES * hourDifference; return totalMinuteDifference; }//end of difference /** * Add minutes to this time to make new time * @param num Minutes to add * @return The new time */ public Time1 addMinutes(int num){ Time1 newTime = new Time1(this);//make new time newTime._minute += num;//add the minutes num = newTime._minute / MAXIMUM_MINUTES;//only hours stay to add newTime._minute %= MAXIMUM_MINUTES;//they are only 60 minuts in hour newTime._hour += num;//add the hours newTime._hour %= MAXIMUM_HOURS;//they are only 24 hours in day /*minutes can't to be negetive so if it happend need convert hour to minutes*/ if(newTime._minute < MINIMUM_MINUTES){ newTime._hour--; newTime._minute += MAXIMUM_MINUTES; }//end of if /*hours can't to be negetive so if it happend need convert day to hours*/ if(newTime._hour < MINIMUM_HOURS) newTime._hour += MAXIMUM_HOURS; return new Time1(newTime); }//end of addMinutes }//end of class
mich153/Railway-Station
Time1.java
1,583
/** * Calculates the difference (in minutes) between two times. * Assumption: this time is after other time * @param other The time to check the difference * @return The difference in minute */
block_comment
en
false
1,606
49
1,583
46
1,724
51
1,583
46
1,985
52
false
false
false
false
false
true
41189_2
package main; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import utilities.DBConnection; import java.sql.*; import java.util.Locale; /** This is the Main class of my application. * * <p><b> * * The javadocs folder is located in the Project primary folder. * * </b></p> * * @author Todd Rasband*/ public class Main extends Application { /** This method sets up the initial JavaFX application stage. * * @param primaryStage The primary stage to be set. * @throws Exception The exception thrown. */ @Override public void start(Stage primaryStage) throws Exception{ Parent root = FXMLLoader.load(getClass().getResource("../view/Login.fxml")); primaryStage.setTitle("SCHEDULING SYSTEM"); primaryStage.setScene(new Scene(root)); primaryStage.show(); } /** <b> * The javadocs folder is located in the Project primary folder. * </b> * * <p> * This method calls for and establishes the database connection. * </p> * @param args The arguments. * @throws SQLException The exception that will be thrown in an error. */ public static void main(String[] args) throws SQLException { // The following two lines were used for testing purposes //Locale.setDefault(new Locale("fr")); //System.setProperty("user.timezone", "America/New_York"); DBConnection.startConnection(); launch(args); DBConnection.endConnection(); } }
Rasbandit/wgu-c195
src/main/Main.java
393
/** <b> * The javadocs folder is located in the Project primary folder. * </b> * * <p> * This method calls for and establishes the database connection. * </p> * @param args The arguments. * @throws SQLException The exception that will be thrown in an error. */
block_comment
en
false
330
73
393
73
403
80
393
73
459
85
false
false
false
false
false
true
41375_3
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Deck { private List<Card> deck = new ArrayList<>(); private final String WILD = Main.getWildCard(); private final String WILD_PLUS_4 = Main.getWildPlus4(); private String[] colorsAssortment = {"blue", "green", "red", "yellow"}; // display cards in deck public void displayCards() { for(Card card : this.deck) { System.out.print(card.getCardName() + " "); } } // add a card to the deck public final void addCard(Card card) { this.deck.add(card); } // remove card from deck public final Card removeCard() { Card topCard = deck.get(this.deck.size() - 1); this.deck.remove(topCard); return topCard; } /* remove the bottom card before starting the game this will be the first card in the discard pile */ public final Card removeBottomCard() { Card bottomCard = deck.get(0); this.deck.remove(bottomCard); return bottomCard; } // get number of cards public final int numberOfCards() { return this.deck.size(); } // return the cards as a list public final List<Card> getDeck() { return this.deck; } // shuffle cards public final void shuffleCards() { Collections.shuffle(this.deck); } // create a new deck of cards public final void createNewDeck(List<Card> stackOfCards) { for(Card card : stackOfCards) { for(int i = 0; i < this.colorsAssortment.length; i++) { // reset wild cards if(card.getCardName().equals(colorSymbol(i) + "_" + WILD)) { card.setCardName(WILD); card.setCardColor(""); } // reset wild +4 cards if(card.getCardName().equals(colorSymbol(i) + "_" + WILD_PLUS_4)) { card.setCardName(WILD_PLUS_4); card.setCardColor(""); } } // add cards to new deck this.deck.add(card); } } // get wild card protected final String getWildCard() { return WILD; } // get wild +4 card protected final String getWildPlus4() { return WILD_PLUS_4; } // get assortment of colors protected final String[] getAssortment() { return this.colorsAssortment; } // get a color in the assortment public final String getColor(int index) { return this.colorsAssortment[index]; } // get the number of colors in the assortment public final int getNumberOfColors() { return this.colorsAssortment.length; } // returns color symbol to be checked public final char colorSymbol(int index) { return (this.colorsAssortment[index].toUpperCase()).charAt(0); } }
CoderJ01/uno-card-game
Deck.java
727
/* remove the bottom card before starting the game this will be the first card in the discard pile */
block_comment
en
false
659
24
727
22
782
24
727
22
868
26
false
false
false
false
false
true
41546_1
import java.text.DecimalFormat; public class bmi{ public static void main (String[] args) { float weight, height; double bmi; try { weight = Float.parseFloat(args[0]); height = Float.parseFloat(args[1]); } catch (Exception e) { System.out.println("You must provide your weight in kilos and your hight in meters as commandline arguments"); return; } //If the user likely have entered its height in cm instead of in meters if (height >= 100) { System.out.println("Did you provide your hight in cm? Or are you really " + height + "m. It is now convertet to meters. "); height = height/100; } //If the user likely have entered the wronge height in meters since he is taller then 3 meters if (height < 100 && height > 3) { System.out.println( "Are you really " + height + "m? " ); System.out.println("You should first provide your weight in kilos and then your hight in meters as commandline arguments. "); return; } //If the user likely have changed the order of the commandline arguments if (height > weight && weight < 3) { System.out.println("It is likely that you have passed your hight as the first commandline argument and weight as the second. "); System.out.println("You should first provide your weight in kilos and then your hight in meters"); return; } //If the user passes negative values if (height < 0 || weight < 0) { System.out.println("You have provided a negative value for your height or your weight, that is not physically possible. "); System.out.println("Please try again. "); System.out.println("You should first provide your weight in kilos and then your hight in meters as commandline arguments. "); return; } bmi = weight / (height*height); if (bmi < 18.5) { System.out.println( "The bmi calculator states that you are underweight, with a bmi of " + new DecimalFormat("#.00").format(bmi) ); } else if (bmi >= 18.5 && bmi <=24.9 ) { System.out.println( "The bmi calculator states that you have a normal weight, with a bmi of " + new DecimalFormat("#.00").format(bmi) ); } else if (bmi > 24.9 && bmi < 30) { System.out.println( "The bmi calculator states that you are overweight, with a bmi of " + new DecimalFormat("#.00").format(bmi) ); } else { System.out.println( "The bmi calculater states that you are obese, with a bmi of " + new DecimalFormat("#.00").format(bmi) ); } } }
Trudelutten/Task-Day-2
bmi.java
702
//If the user likely have entered the wronge height in meters since he is taller then 3 meters
line_comment
en
false
645
23
702
24
738
24
702
24
791
25
false
false
false
false
false
true
42579_2
/** * Properties and methods for moons. */ public class Moon extends SolarObject { private double dist_offset; private Planet planet; /** * Setting up the moon object. * * @param ss the solar system the planet will be added to * @param dist distance between the moon and the planet (in million km) * @param dist_offset the distance offset (due to different scaling ratio between distance and diameter of solar objects, * a moon can be rendered inside a planet, thus this offset value) (in pixels) * @param dia diameter of the moon (in million km) * @param col color of the moon * @param ang angle to add per move * @param planet the planet the moon is revolving around */ public Moon(SolarSystem ss, double dist, double dist_offset, double dia, String col, double ang, Planet planet) { this.ss = ss; this.dist = calc_display_dist(dist) + dist_offset; this.dist_offset = dist_offset; this.dia = calc_display_dia(dia); this.col = col; this.current_ang = 90; this.ang = ang; this.planet = planet; } /** * Triggers the moon to move 1 step foward */ public void move() { current_ang = calc_new_ang(current_ang, ang); ss.drawSolarObjectAbout(dist, current_ang, dia, col, planet.get_dist(), planet.get_ang()); } }
gabrielchl/java-solar-system-model
Moon.java
376
/** * Triggers the moon to move 1 step foward */
block_comment
en
false
337
17
376
17
395
17
376
17
406
20
false
false
false
false
false
true
43191_3
import java.util.*; public class ifelse { public static void main(String[]argu){ Scanner sc = new Scanner(System.in); // Question to check weather the he is adult or under age System.out.print("Age: "); int ag= sc.nextInt(); if (ag>18){ System.out.println("You are an Adult"); } else{ System.out.println("You are under age"); } System.out.println("\n"); //Question to check weather the he is odd or even System.out.println("To cheek Weather the number is odd or eve"); System.out.print("Number: "); int numb=sc.nextInt(); if(numb % 2 ==0) { System.out.println("Even"); } else{ System.out.println("Odd"); System.out.println("\n"); //Question to check weather the the number equal or greater or lesser System.out.print("a="); int a1 = sc.nextInt(); System.out.print("b="); int b1= sc.nextInt(); if (a1==b1){ System.out.println("Equal"); } else{ // insted of writing lots of if else or nested if else we use else if if (a1>b1){ System.out.println("a is greater"); } else { System.out.println("a is lesser"); } } } //ok System.out.println("Next number: "); int v = sc.nextInt(); if( v <=10){ System.out.println("kid"); System.out.println("sjn"); } else{ if ((v>10)&&(v<=20)){ System.out.println("Teen");} else if((v>20)&&(v<=40)){ System.out.println("adult"); } else{ System.out.println("40+"); } } sc.close(); } }
RiteshSharmaop/Java
ifelse.java
480
// insted of writing lots of if else or nested if else we use else if
line_comment
en
false
414
17
480
17
521
17
480
17
556
17
false
false
false
false
false
true
43653_24
/** * This is the Craps Game main file in this class. Responsible for most game functions. * * @author TJ Zimmerman * @version 1.01 */ public class Craps { /**Makes objects for each of the two dice. */ public GVdie d1, d2; /**Initializes and sets the return point of the game to * negative one. */ public int point; /**Initializes and sets the games credits to 10.*/ public int credits; /**Sets the inital welcome message to the game.*/ public String message; /**Sets the boolean up that controls which portion of * the game you're on. */ public boolean comeoutlegal; /** * Constructer sets the variables to paramters. */ public Craps () { d1 = new GVdie(); d2 = new GVdie(); point = -1; credits = 10; message = "Hello! Welcome to Craps! Press 'Come Out' to begin!"; comeoutlegal = true; } /** * Returns credits for each game. * @return credits */ public int getCredits() { return credits; } /** * Returns current point for each game. * @return point */ public int getPoint() { return point; } /** * Returns message for each game. * @return message */ public String getMessage() { return message; } /** * This sets the credits to amount of amount is greater than * inital credits. */ public void setCredits (int amount) { if (amount >= 0) { credits = amount; } } /** * This is the primary method that the come out function of the * game uses. A nested if then statement incorporates logic into * the game and makes it behave properly. */ public void comeOut() { int r1 = 0; int r2 = 0; /** * This loop sets your credit score modifiers and what * portion of the game you will continue to. */ if (comeoutlegal && credits >= 1) { d1.roll(); d2.roll(); r1 = d1.getValue(); r2 = d2.getValue(); int dt = r1+r2; if (dt == 7) { credits++; message = "Rolled 7: +1 credit! Come out, again!"; //Continue to Come out. } else if (dt == 11) { credits++; message = "Rolled 11: +1 credit! Come out, again!"; //Continue to Come out. } else if (dt == 2) { credits--; message = "Rolled 2: -1 credit. Come out again!"; //Continue to Come out. } else if (dt == 3) { credits--; message = "Rolled 3: -1 credit. Come out again!"; //Continue to Come out. } else if (dt == 12) { credits--; message = "Rolled 12: -1 credit. Come out again!"; //Continue to Come out. } else { point = dt; comeoutlegal = false; message = "You rolled a(n) " + dt + ". Roll out, now!"; //Move to Roll out. } } else { message = "You're out of credits! Press Reset Game to" + "play again!"; } } /** * This is the primary method that the roll function of the game * uses. A nested if then statement incorporates logic into the * game and makes it behave properly. */ public void roll () { int r1 = 0; int r2 = 0; /** * This loop sets your credit score modifiers and what * portion of the game you will continue to. */ if (!comeoutlegal) { d1.roll(); d2.roll(); r1 = d1.getValue(); r2 = d2.getValue(); int dt = r1+r2; if (dt == 7) { credits--; point = -1; message = "Rolled 7: -1 credit. Come out now!"; comeoutlegal = true; //Move to Come out. } else if (dt == point) { credits++; point = -1; message = "Rolled point. +1 credit. Come out now!"; comeoutlegal = true; //Move to Come out. } else { message = "Rolled a(n) " + dt + ". Not a 7 or " + point + ". Roll again!"; //Continue to Roll. } } else { message = "ERROR, See Roll method to debug!!"; } } /** * While it wasn't required, I felt like adding a reset method * anyway as it would be very simple and would certainly * enhance the game. */ public void reset() { point = -1; credits = 10; message = "Hello! Welcome to Craps! Press 'Come Out' to begin!"; comeoutlegal = true; } /** * While it wasn't required, I felt like adding an exit method * anyway as it would be very simple and would certainly * enhance the game. */ public void exit() { System.exit(0); } /** * This method decides whether the roll option should be used or not. */ public boolean okToRoll() { if (comeoutlegal == false) { return true; } else if (comeoutlegal == true) { return false; } return comeoutlegal; } /** * This method instantiates the die objects and supplies them with * a value. */ public GVdie getDie (int num) { { if(num == 1) { return d1; } else { return d2; } } } /** * Main Method is used to test the principal logic of the game. */ public static void main (String[] args) { Craps crapsgame = new Craps(); crapsgame.getMessage(); crapsgame.comeOut(); crapsgame.getMessage(); /** *This loop continues to roll the dice until it is time to move *on to comeoutlegal part. */ while (crapsgame.okToRoll()) { crapsgame.roll(); System.out.println (crapsgame.getMessage()); } System.out.println ( "Total Credits: " + crapsgame.getCredits()); } }
zimmertr/Craps
Craps.java
1,579
/** * While it wasn't required, I felt like adding a reset method * anyway as it would be very simple and would certainly * enhance the game. */
block_comment
en
false
1,545
38
1,579
36
1,817
43
1,579
36
1,937
44
false
false
false
false
false
true
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
43
Edit dataset card