file_id
stringlengths
4
9
content
stringlengths
41
35k
repo
stringlengths
7
113
path
stringlengths
5
90
token_length
int64
15
4.07k
original_comment
stringlengths
3
9.88k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
excluded
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
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
625_0
public final class i { public static boolean a; public static final int[] b = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, -10, -11, -13, -12, -20, -21, -1, -2, -3, -4, -6, -7, -5, 42, 35 }; private static final int[][] c = { { 0 }, { 1 }, { 2, 10 }, { 3 }, { 4, 12 }, { 5, 14 }, { 6, 13 }, { 7 }, { 8, 11 }, { 9 }, { 10, 20 }, { 11, 21 }, { 12, 19 }, { 13 }, { 15 }, { 16 }, { 10, 20 }, { 11, 21 }, { 12, 19 }, { 13 }, { 15 }, { 16 }, { 14 }, { 17 }, { 18, 14 } }; public static boolean[] d = new boolean[22]; private static int e = 0; private static int f = 0; private static int[] g = new int[20]; private static int[] d(int paramInt) { for (int i = 0; i < b.length; i++) if (paramInt == b[i]) return c[i]; return null; } public static void a(int paramInt) { int[] arrayOfInt = d(paramInt); if (arrayOfInt != null) for (int i = 0; i < arrayOfInt.length; i++) { int j = arrayOfInt[i]; e(j); d[j] = true; } a = true; } private static void e(int paramInt) { g[(f++)] = paramInt; if (f >= 20) f = 0; if (f == e) { e += 1; if (e >= 20) e = 0; } } public static void b(int paramInt) { a = false; int[] arrayOfInt = d(paramInt); if (arrayOfInt == null) return; for (int i = 0; i < arrayOfInt.length; i++) { int j = arrayOfInt[i]; if (d[j] != false) d[j] = false; } } public static boolean c(int paramInt) { return d[paramInt]; } public static int a() { if (e == f) return -66; int i = g[(e++)]; if (e >= 20) e = 0; return i; } public static void b() { int i = 22; do { i--; d[i] = false; } while (i > 0); a = false; } } /* Location: /Users/ilya/4fun/Biplanes/Bluetooth_Biplanes.jar * Qualified Name: i * JD-Core Version: 0.6.2 */
TheRealPinkie/BT_Biplanes_src
i.java
786
/* Location: /Users/ilya/4fun/Biplanes/Bluetooth_Biplanes.jar * Qualified Name: i * JD-Core Version: 0.6.2 */
block_comment
en
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
953_1
import java.io.*; import java_cup.runtime.*; /** * Main program to test the parser. * * There should be 2 command-line arguments: * 1. the file to be parsed * 2. the output file into which the AST built by the parser should be * unparsed * The program opens the two files, creates a scanner and a parser, and * calls the parser. If the parse is successful, the AST is unparsed. */ public class P5 { FileReader inFile; private PrintWriter outFile; private static PrintStream outStream = System.err; public static final int RESULT_CORRECT = 0; public static final int RESULT_SYNTAX_ERROR = 1; public static final int RESULT_TYPE_ERROR = 2; public static final int RESULT_OTHER_ERROR = -1; /** * P5 constructor for client programs and testers. Note that * users MUST invoke {@link setInfile} and {@link setOutfile} */ public P5(){ } /** * If we are directly invoking P5 from the command line, this * is the command line to use. It shouldn't be invoked from * outside the class (hence the private constructor) because * it * @param args command line args array for [<infile> <outfile>] */ private P5(String[] args){ //Parse arguments if (args.length < 2) { String msg = "please supply name of file to be parsed" + "and name of file for unparsed version."; pukeAndDie(msg); } try{ setInfile(args[0]); setOutfile(args[1]); } catch(BadInfileException e){ pukeAndDie(e.getMessage()); } catch(BadOutfileException e){ pukeAndDie(e.getMessage()); } } /** * Source code file path * @param filename path to source file */ public void setInfile(String filename) throws BadInfileException{ try { inFile = new FileReader(filename); } catch (FileNotFoundException ex) { throw new BadInfileException(ex, filename); } } /** * Text file output * @param filename path to destination file */ public void setOutfile(String filename) throws BadOutfileException{ try { outFile = new PrintWriter(filename); } catch (FileNotFoundException ex) { throw new BadOutfileException(ex, filename); } } /** * Perform cleanup at the end of parsing. This should be called * after both good and bad input so that the files are all in a * consistent state */ public void cleanup(){ if (inFile != null){ try { inFile.close(); } catch (IOException e) { //At this point, users already know they screwed // up. No need to rub it in. } } if (outFile != null){ //If there is any output that needs to be // written to the stream, force it out. outFile.flush(); outFile.close(); } } /** * Private error handling method. Convenience method for * @link pukeAndDie(String, int) with a default error code * @param error message to print on exit */ private void pukeAndDie(String error){ pukeAndDie(error, -1); } /** * Private error handling method. Prints an error message * @link pukeAndDie(String, int) with a default error code * @param error message to print on exit */ private void pukeAndDie(String error, int retCode){ outStream.println(error); cleanup(); System.exit(-1); } /** the parser will return a Symbol whose value * field is the translation of the root nonterminal * (i.e., of the nonterminal "program") * @return root of the CFG */ private Symbol parseCFG(){ try { parser P = new parser(new Yylex(inFile)); return P.parse(); } catch (Exception e){ return null; } } public int process(){ Symbol cfgRoot = parseCFG(); ProgramNode astRoot = (ProgramNode)cfgRoot.value; if (ErrMsg.getErr()) { return P5.RESULT_SYNTAX_ERROR; } astRoot.nameAnalysis(); // perform name analysis if(ErrMsg.getErr()) { return P5.RESULT_SYNTAX_ERROR; } astRoot.typeCheck(); if(ErrMsg.getErr()) { return P5.RESULT_TYPE_ERROR; } astRoot.unparse(outFile, 0); return P5.RESULT_CORRECT; } public void run(){ int resultCode = process(); if (resultCode == RESULT_CORRECT){ cleanup(); return; } switch(resultCode){ case RESULT_SYNTAX_ERROR: pukeAndDie("Syntax error", resultCode); case RESULT_TYPE_ERROR: pukeAndDie("Type checking error", resultCode); default: pukeAndDie("Type checking error", RESULT_OTHER_ERROR); } } private class BadInfileException extends Exception{ private static final long serialVersionUID = 1L; private String message; public BadInfileException(Exception cause, String filename) { super(cause); this.message = "Could not open " + filename + " for reading"; } @Override public String getMessage(){ return message; } } private class BadOutfileException extends Exception{ private static final long serialVersionUID = 1L; private String message; public BadOutfileException(Exception cause, String filename) { super(cause); this.message = "Could not open " + filename + " for reading"; } @Override public String getMessage(){ return message; } } public static void main(String[] args){ P5 instance = new P5(args); instance.run(); } }
jkoritzinsky/Moo-Type-Analysis
P5.java
1,503
/** * P5 constructor for client programs and testers. Note that * users MUST invoke {@link setInfile} and {@link setOutfile} */
block_comment
en
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
1570_1
package Myinterface; //@FunctionalInterface public class B implements A { // when we are only one method pass inside class then // interface show. otherwise more than one method it show error @Override public void test1() { System.out.println(50000); } @Override public void test() { System.out.println(900); } public static void main(String[] args) { B b1 = new B(); b1.test(); b1.test1(); } }
Ashutosh-62044/Interface-in-java
B.java
141
// when we are only one method pass inside class then
line_comment
en
true
1614_4
package advanced.gestureSound; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import de.sciss.jcollider.Group; import de.sciss.jcollider.JCollider; import de.sciss.jcollider.NodeWatcher; import de.sciss.jcollider.Server; import de.sciss.jcollider.ServerOptions; import de.sciss.jcollider.Synth; import de.sciss.jcollider.SynthDef; import de.sciss.jcollider.UGenInfo; public class SC { public final String fs = File.separator; public java.util.List defTables; public Server server = null; public ServerOptions serveropts = null; public NodeWatcher nw = null; public Group grpAll; public void setupSupercollider() { try { System.out.println("Testing server...."); //server = new Server("localhost"); serveropts= new ServerOptions(); setServerOptions(serveropts); server = new Server("localhost",new InetSocketAddress("127.0.0.1",57110),serveropts); File f = findFile(JCollider.isWindows ? "scsynth.exe" : "scsynth", new String[] { fs + "Applications" + fs + "SuperCollider_f", fs + "Applications" + fs + "SC3", fs + "usr" + fs + "local" + fs + "bin", fs + "usr" + fs + "bin", "C:\\Program Files\\SC3", "C:\\Program Files (x86)\\SuperCollider" }); if (f != null) { System.out.println("Trying to start program at: " + f); Server.setProgram(f.getAbsolutePath()); } else { System.out.println("CANNOT FIND PROGRAM"); } try { server.start(); server.startAliveThread(); initServer(); //while(!server.isRunning()) {} try { Thread.sleep(2); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (IOException e1) { System.out.println("Ughhh server won't start"); } // if( server.isRunning() ) initServer(); } catch (IOException e1) { System.out.println("OOPS SOMETHIGN went wrong, server wont start!"); } sendDefs(); } public static File findFile(String fileName, String[] folders) { File f; for (int i = 0; i < folders.length; i++) { f = new File(folders[i], fileName); if (f.exists()) return f; } return null; } /** * this is a useful function if you're using jcollider's synthdefs. * however I have not. */ public void sendDefs() { File dir = new File(System.getProperty("user.dir")+"/data/synthdefs/"); for (File syn : dir.listFiles()) { try { //System.out.println("trying to load "+syn+"..."); if (syn.getName().startsWith(".")) { System.out.println("Ignoring this file ("+syn.getName()+")"); } else { SynthDef.readDefFile(syn)[0].send(server); } } catch (IOException e) { System.out.println(syn+" is an invalid synthdef! trying to continue without it! if you notice funny behavior, chances are its because of this."); e.printStackTrace(); } } } /** * passes a whole bunch of options found in the config file to supercollider * @param s */ public void setServerOptions(ServerOptions s) { } /** * this is a useful function if you're using jcollider's synthdefs. * however I have not. */ public void createDefs() { try { // UGenInfo.readDefinitions(); UGenInfo.readBinaryDefinitions(); // defTables = DemoDefs.create(); // defTables[ 1 ].addDefs( collDefs ); // defTables[ 0 ].addDefs( collDefs ); } catch (IOException e1) { e1.printStackTrace(); // reportError( e1 ); } } public void initServer() throws IOException { // sendDefs(); if (!server.didWeBootTheServer()) { server.initTree(); server.notify(true); } // if( nw != null ) nw.dispose(); nw = NodeWatcher.newFrom(server); grpAll = Group.basicNew(server); nw.register(server.getDefaultGroup()); nw.register(grpAll); server.sendMsg(grpAll.newMsg()); } public void testSupercollider() { try { Synth s = new Synth("stereosine", new String[] {"out", "freq"}, new float[] { 0, 1213f }, grpAll); Synth a = new Synth("stereosine", new String[] {"out", "freq"}, new float[] { 1, 1213f }, grpAll); System.out.println("Made synth!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
acm-uiuc/Tacchi
SC.java
1,358
/** * this is a useful function if you're using jcollider's synthdefs. * however I have not. */
block_comment
en
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
3634_3
class Solution { public boolean isValidBST(TreeNode root) { return isValidBSTWithRange(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } boolean isValidBSTWithRange(TreeNode root, int min, int max){ // 判断root是否为二叉搜索树,并且所有节点需要在min -> max 闭范围 if (root == null) { return true; } if (root.val < min || root.val > max) { return false; } // 如果root恰好为Integer.MIN_VALUE或Integer.MAX_VALUE,那么就需要特殊处理 if (root.val == Integer.MIN_VALUE && root.left != null) { // 如果root已经为最小值,且还有左树,那一定不满足条件 return false; } if (root.val == Integer.MAX_VALUE && root.right != null) { // 如果root已经为最大值,且还有右树,那一定不满足条件 return false; } // 判断左右子树 if(!isValidBSTWithRange(root.left, min, root.val - 1)) { return false; } if(!isValidBSTWithRange(root.right, root.val + 1, max)) { return false; } return true; } }
ninehills/leetcode
98.java
301
// 如果root已经为最大值,且还有右树,那一定不满足条件
line_comment
en
true
4844_6
/** * Provides basic game state handling. */ public abstract class Bot extends AbstractSystemInputParser { protected Game game; protected AntMap map; protected int ROWS; protected int COLS; /** * {@inheritDoc} */ @Override public void setup(int loadTime, int turnTime, int rows, int cols, int turns, int viewRadius2, int attackRadius2, int spawnRadius2) { Game g = new Game(loadTime, turnTime, rows, cols, turns, viewRadius2, attackRadius2, spawnRadius2); setGame(g); ROWS = game.getRows(); COLS = game.getCols(); setMap(new AntMap(g)); } /** * Returns game state information. * * @return game state information */ public Game getGame() { return game; } /** * Sets game state information. * * @param game game state information to be set */ protected void setGame(Game game) { this.game = game; } public AntMap getMap() { return map; } protected void setMap(AntMap map) { this.map = map; } /** * {@inheritDoc} */ @Override public void beforeUpdate() { map.log("Bot.beforeUpdate"); map.log("Setting start time"); game.setTurnStartTime(System.currentTimeMillis()); map.log("Clearing orders"); game.getOrders().clear(); map.log("Incrementing turn"); game.incrementTurn(); map.log("map.beforeUpdate (called from Bot)"); map.beforeUpdate(); } /** * {@inheritDoc} */ @Override public void addWater(int row, int col) { map.processWater(row, col); } /** * {@inheritDoc} */ @Override public void addAnt(int row, int col, int owner) { map.processLiveAnt(row, col, owner); // map.update(owner > 0 ? Ilk.ENEMY_ANT : Ilk.MY_ANT, new Tile(row, col)); } /** * {@inheritDoc} */ @Override public void addFood(int row, int col) { map.processFood(row, col); } /** * {@inheritDoc} */ @Override public void removeAnt(int row, int col, int owner) { map.processDeadAnt(row, col, owner); } /** * {@inheritDoc} */ @Override public void addHill(int row, int col, int owner) { map.processHill(row, col, owner); } /** * {@inheritDoc} */ @Override public void afterUpdate() { map.afterUpdate(); } }
goldcaddy77/Ants-AI-Challenge
Bot.java
665
/** * {@inheritDoc} */
block_comment
en
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
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
6427_0
import org.patricbrc.Workspace.*; import java.util.Arrays; import java.util.List; import java.util.Map; public class ex { public static void main(String args[]) { try { String token = "un=olson|tokenid=2A8BCAFA-ACBA-11E4-A91B-68C642A49C03|expiry=1454623630|client_id=olson|token_type=Bearer|SigningSubject=http://rast.nmpdr.org/goauth/keys/E087E220-F8B1-11E3-9175-BD9D42A49C03|this_is_globus=globus_style_token|sig=03a3cfae05a8dbaaaf57e34eb4800bc8b3c8046beb18620a8d605867490228302651f050578a7dd30181366b1cf7170dedc89a45a6b41a3ce6ebd96069834be090281c2bf4f3917a005a63f5ac78799843d33b690cfc76f7d59ef846fe7a23d5d623d830584d23adad60293cb56d250ed8c1c3169e8fdaf89bfc7c3f50bdaf9d"; Workspace w = new Workspace("http://p3.theseed.org/services/Workspace", token); get_params getpar = new get_params(); getpar.objects = Arrays.asList("/olson/olson/prefs.json"); getpar.metadata_only = 0; getpar.adminmode = 0; List<Workspace_tuple_2> getres = w.get(getpar); System.out.println(getres.get(0).e_2); Map<String, List<ObjectMeta>> res; list_params lp = new list_params(); lp.paths = Arrays.asList("/olson/olson"); res = w.ls(lp); System.out.println(res.entrySet()); get_params gp = new get_params(); gp.objects = Arrays.asList("/olson/olson/Makefile3"); gp.metadata_only = 0; gp.adminmode = 0; List<Workspace_tuple_2> r = w.get(gp); System.out.println(r.get(0).e_2); } catch (Exception e) { System.out.println("Failure: " + e); } } }
BV-BRC/Workspace
ex.java
706
//rast.nmpdr.org/goauth/keys/E087E220-F8B1-11E3-9175-BD9D42A49C03|this_is_globus=globus_style_token|sig=03a3cfae05a8dbaaaf57e34eb4800bc8b3c8046beb18620a8d605867490228302651f050578a7dd30181366b1cf7170dedc89a45a6b41a3ce6ebd96069834be090281c2bf4f3917a005a63f5ac78799843d33b690cfc76f7d59ef846fe7a23d5d623d830584d23adad60293cb56d250ed8c1c3169e8fdaf89bfc7c3f50bdaf9d";
line_comment
en
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
7028_2
/* Copyright (c) 2014, Christoph Stahl All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import lejos.hardware.Button; import lejos.hardware.lcd.LCD; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import com.kitfox.svg.SVGException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; //import lejos.robotics.RegulatedMotorListener; /* Notes * Button.LEDPattern(3); //off 0, static: green 1, red 2, yellow 3, rhythmic: green 7, red 8, yellow 9 * Drawing Rectangle in mm from origin: * * upper: 270 * left: -105 right: 125 * bottom: 115 * * Drawing rectangle size: 155x230 */ public class TRAC3R { private TRAC3RsArm arm; public TRAC3R() { System.out.println("Setting up TRAC3R..."); LCD.clear(); System.out.println("Setting up TRAC3RsArm..."); arm = new TRAC3RsArm(); } public void start() throws InterruptedException { arm.initialize(); arm.calibrateHand(); //arm.testHandPosCodeFreely(); //generate interpolated paths from file List<Path> paths = null; try { paths = SVGHandler.pathsInSVGFile(new URI("file:///tmp/job.svg")); } catch (SVGException | URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (paths != null) { //calculate inverse kinematics and draw as soon as first path is calculated BlockingQueue<List<double[]>> queue = new ArrayBlockingQueue<List<double[]>>(1); Thread producer = new Thread(new MovementDataProducer(arm, queue, paths)); Thread consumer = new Thread(new MovementController(arm, queue)); producer.setDaemon(true); consumer.setDaemon(true); producer.start(); consumer.start(); producer.join(); consumer.join(); System.out.println("Finished all."); } Button.LEDPattern(0); } public static void main(String[] args) throws InterruptedException { TRAC3R robot = new TRAC3R(); robot.start(); } }
stahlfabrik/TRAC3R
TRAC3R.java
916
/* Notes * Button.LEDPattern(3); //off 0, static: green 1, red 2, yellow 3, rhythmic: green 7, red 8, yellow 9 * Drawing Rectangle in mm from origin: * * upper: 270 * left: -105 right: 125 * bottom: 115 * * Drawing rectangle size: 155x230 */
block_comment
en
true
7083_0
///usr/bin/env jbang "$0" "$@" ; exit $? //REPOS mavencentral,jitpack //DEPS com.github.adriens:excuses-sdk:v0.12 //DEPS info.picocli:picocli:4.5.0 import com.github.adriens.excuses.sdk.Excuses; import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Parameters; import java.util.concurrent.Callable; @Command(name = "nope", mixinStandardHelpOptions = true, version = "nope 0.1", description = "nope made with jbang") class nope implements Callable<Integer> { //TODO ajouter valeur par défaut @CommandLine.Option( names = {"-c", "--category"}, description = "La catégorie d'excuse (boulot,sport,apero)", required = true) private String category; public static void main(String... args) { int exitCode = new CommandLine(new nope()).execute(args); System.exit(exitCode); } @Override public Integer call() throws Exception { // your business logic goes here... Excuses excuses = new Excuses(); System.out.println(excuses.pickRandomly(category)); return 0; } }
adriens/excuses-sdk
nope.java
322
///usr/bin/env jbang "$0" "$@" ; exit $?
line_comment
en
true
7856_3
package app; import java.awt.Desktop; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.StringJoiner; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.SwingWorker; /** * * @author Ben Hannel */ public class GUI extends javax.swing.JFrame { private double lat; private double lon; private int vid; private ArrayList<Point2D.Double> points = new ArrayList<>(); private int pointIndex = 0; private int numPoints = 0; /** Creates new form GUI */ public GUI() { initComponents(); } public void setSpeed(int speed) { this.speed.setText(speed + " mph"); } public void setRange(double range) { this.range.setText(range + " miles"); } public void setLatLon(double lat, double lon) { points.add(new Point2D.Double(lat, lon)); if (points.size() > 20) points.remove(0); this.lat = lat; this.lon = lon; this.coords.setText(lat + ", " + lon); numPoints++; numPointsLabel.setText("" + numPoints); if (numPoints == 1) { viewLocationActionPerformed(null); } } public void setLastUpdate(Date date) { lastUpdate.setValue(date); } public void setVid(int vid) { this.vid = vid; vidLabel.setText("" + vid); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { javax.swing.JPanel jPanel2 = new javax.swing.JPanel(); mapLabel = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); javax.swing.JLabel jLabel1 = new javax.swing.JLabel(); speed = new javax.swing.JLabel(); javax.swing.JLabel jLabel4 = new javax.swing.JLabel(); range = new javax.swing.JLabel(); javax.swing.JLabel jLabel5 = new javax.swing.JLabel(); coords = new javax.swing.JLabel(); javax.swing.JLabel jLabel6 = new javax.swing.JLabel(); lastUpdate = new javax.swing.JFormattedTextField(); javax.swing.JLabel jLabel7 = new javax.swing.JLabel(); vidLabel = new javax.swing.JLabel(); javax.swing.JLabel jLabel8 = new javax.swing.JLabel(); numPointsLabel = new javax.swing.JLabel(); viewLocation = new javax.swing.JButton(); aboutButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMinimumSize(new java.awt.Dimension(250, 350)); setPreferredSize(new java.awt.Dimension(500, 700)); jPanel2.setMinimumSize(new java.awt.Dimension(200, 200)); jPanel2.setPreferredSize(new java.awt.Dimension(300, 300)); jPanel2.setLayout(new java.awt.BorderLayout()); jPanel2.add(mapLabel, java.awt.BorderLayout.CENTER); jPanel1.setLayout(new java.awt.GridLayout(0, 2)); jLabel1.setText("Speed"); jPanel1.add(jLabel1); speed.setText("NA"); jPanel1.add(speed); jLabel4.setText("Range"); jPanel1.add(jLabel4); range.setText("NA"); jPanel1.add(range); jLabel5.setText("Latitude, Longitude"); jPanel1.add(jLabel5); coords.setText("NA"); jPanel1.add(coords); jLabel6.setText("Last Update Time"); jPanel1.add(jLabel6); lastUpdate.setBackground(new java.awt.Color(238, 238, 238)); lastUpdate.setBorder(null); lastUpdate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getTimeInstance()))); lastUpdate.setFocusable(false); jPanel1.add(lastUpdate); jLabel7.setText("Vehicle ID"); jPanel1.add(jLabel7); vidLabel.setText("NA"); jPanel1.add(vidLabel); jLabel8.setText("Data Points Recorded"); jPanel1.add(jLabel8); numPointsLabel.setText("NA"); jPanel1.add(numPointsLabel); viewLocation.setText("View Location"); viewLocation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { viewLocationActionPerformed(evt); } }); jPanel1.add(viewLocation); aboutButton.setText("About"); aboutButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aboutButtonActionPerformed(evt); } }); jPanel1.add(aboutButton); jPanel2.add(jPanel1, java.awt.BorderLayout.PAGE_START); getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents private void viewLocationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewLocationActionPerformed StringJoiner pathStr = new StringJoiner("|"); for (Point2D point : points) { pathStr.add(point.getX() + "," + point.getY()); } try { String urlStr = "http://maps.googleapis.com/maps/api/staticmap?sensor=false" + "&size=" + mapLabel.getWidth() + "x" + mapLabel.getHeight() + "&markers=" + lat + "," + lon + "&path=color:0x0000ff|weight:5" + pathStr.toString(); URL url = new URL(urlStr); BufferedImage img = ImageIO.read(url); final ImageIcon icon = new ImageIcon(img); new SwingWorker() { @Override protected Object doInBackground() throws Exception { mapLabel.setIcon(icon); return null; } }.execute(); } catch (IOException ex) { ex.printStackTrace(); Main.logError(ex, "Static map update failed"); } }//GEN-LAST:event_viewLocationActionPerformed private void aboutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutButtonActionPerformed try { Desktop.getDesktop().browse( new URI("http://evtripplanner.com/planner/tracker/tracker_about.php")); } catch (URISyntaxException | IOException ex) { ex.printStackTrace(); Main.logError(ex); } }//GEN-LAST:event_aboutButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton aboutButton; private javax.swing.JLabel coords; private javax.swing.JPanel jPanel1; private javax.swing.JFormattedTextField lastUpdate; private javax.swing.JLabel mapLabel; private javax.swing.JLabel numPointsLabel; private javax.swing.JLabel range; private javax.swing.JLabel speed; private javax.swing.JLabel vidLabel; private javax.swing.JButton viewLocation; // End of variables declaration//GEN-END:variables }
benhannel/TeslaTracker
GUI.java
1,784
// </editor-fold>//GEN-END:initComponents
line_comment
en
true
7866_0
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new ArrayList<>(); if(root==null) return result; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while(!queue.isEmpty()){ int size = queue.size(); for(int i=0;i<size;i++){ TreeNode temp = queue.poll(); if(i==size-1) result.add(temp.val); if(temp.left!=null) queue.offer(temp.left); if(temp.right!=null) queue.offer(temp.right); } } return result; } }
fztfztfztfzt/leetcode
199.java
208
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
block_comment
en
true
9004_1
package profile; import java.net.InetAddress; import java.net.URI; import java.nio.file.Paths; import java.util.Map; import java.util.Vector; import java.util.regex.Pattern; import javax.swing.JOptionPane; import core.data.InterfaceData; import core.exec.PasswordExec; import core.iface.IUnit; import core.model.InterfaceModel; import core.model.NetworkModel; import core.model.ServerModel; import core.profile.AStructuredProfile; import core.unit.SimpleUnit; import core.unit.fs.DirUnit; import core.unit.fs.FileChecksumUnit; import core.unit.fs.FileDownloadUnit; import core.unit.pkg.InstalledUnit; public class Metal extends AStructuredProfile { private Virtualisation hypervisor; private HypervisorScripts backups; private Vector<ServerModel> services; private ServerModel me; public Metal(ServerModel me, NetworkModel networkModel) { super("metal", me, networkModel); this.me = me; this.hypervisor = new Virtualisation(me, networkModel); this.backups = new HypervisorScripts(me, networkModel); this.services = new Vector<ServerModel>(); } public Vector<ServerModel> getServices() { return services; } protected Vector<IUnit> getInstalled() { Vector<IUnit> units = new Vector<IUnit>(); units.addAll(hypervisor.getInstalled()); units.addAll(backups.getInstalled()); units.addElement(new DirUnit("media_dir", "proceed", networkModel.getData().getHypervisorThornsecBase(me.getLabel()))); units.addElement(new InstalledUnit("whois", "proceed", "whois")); units.addElement(new InstalledUnit("tmux", "proceed", "tmux")); units.addElement(new InstalledUnit("socat", "proceed", "socat")); return units; } protected Vector<IUnit> getPersistentConfig() { Vector<IUnit> units = new Vector<IUnit>(); String fuse = ""; fuse += "#user_allow_other"; units.addElement(((ServerModel)me).getConfigsModel().addConfigFile("fuse", "proceed", fuse, "/etc/fuse.conf")); units.addAll(backups.getPersistentConfig()); return units; } public Vector<IUnit> getNetworking() { Vector<IUnit> units = new Vector<IUnit>(); InterfaceModel im = me.getInterfaceModel(); me.setFirstOctet(10); me.setSecondOctet(networkModel.getMetalServers().indexOf(me) + 1); me.setThirdOctet(0); int i = 0; //Add this machine's interfaces for (Map.Entry<String, String> lanIface : networkModel.getData().getLanIfaces(me.getLabel()).entrySet() ) { if (me.isRouter() || networkModel.getData().getWanIfaces(me.getLabel()).containsKey(lanIface.getKey())) { //Try not to duplicate ifaces if we're a Router/Metal continue; } InetAddress subnet = networkModel.stringToIP(me.getFirstOctet() + "." + me.getSecondOctet() + "." + me.getThirdOctet() + "." + (i * 4)); InetAddress router = networkModel.stringToIP(me.getFirstOctet() + "." + me.getSecondOctet() + "." + me.getThirdOctet() + "." + ((i * 4) + 1)); InetAddress address = networkModel.stringToIP(me.getFirstOctet() + "." + me.getSecondOctet() + "." + me.getThirdOctet() + "." + ((i * 4) + 2)); InetAddress broadcast = networkModel.stringToIP(me.getFirstOctet() + "." + me.getSecondOctet() + "." + me.getThirdOctet() + "." + ((i * 4) + 3)); InetAddress netmask = networkModel.getData().getNetmask(); im.addIface(new InterfaceData(me.getLabel(), lanIface.getKey(), lanIface.getValue(), "static", null, subnet, address, netmask, broadcast, router, "comment goes here") ); } me.addRequiredEgress("gensho.ftp.acc.umu.se"); me.addRequiredEgress("github.com"); return units; } protected Vector<IUnit> getLiveConfig() { Vector<IUnit> units = new Vector<IUnit>(); Vector<String> urls = new Vector<String>(); for (ServerModel service : me.getServices()) { String newURL = networkModel.getData().getDebianIsoUrl(service.getLabel()); if (urls.contains(newURL)) { continue; } else { urls.add(newURL); } } for (String url : urls) { String filename = null; String cleanedFilename = null; try { filename = Paths.get(new URI(url).getPath()).getFileName().toString(); cleanedFilename = filename.replaceAll("[^A-Za-z0-9]", "_"); } catch (Exception e) { JOptionPane.showMessageDialog(null, "It doesn't appear that " + url + " is a valid link to a Debian ISO.\n\nPlease fix this in your JSON"); System.exit(1); } units.addElement(new FileDownloadUnit("debian_netinst_iso_" + cleanedFilename, "metal_genisoimage_installed", url, networkModel.getData().getHypervisorThornsecBase(me.getLabel()) + "/" + filename, "The Debian net install ISO couldn't be downloaded. Please check the URI in your config.")); units.addElement(new FileChecksumUnit("debian_netinst_iso", "debian_netinst_iso_" + cleanedFilename + "_downloaded", networkModel.getData().getHypervisorThornsecBase(me.getLabel()) + "/" + filename, networkModel.getData().getDebianIsoSha512(me.getLabel()), "The sha512 sum of the Debian net install in your config doesn't match what has been downloaded. This could mean your connection is man-in-the-middle'd, or it could just be that the file has been updated on the server. " + "Please check http://cdimage.debian.org/debian-cd/current/amd64/iso-cd/SHA512SUMS (64 bit) or http://cdimage.debian.org/debian-cd/current/i386/iso-cd/SHA512SUMS (32 bit) for the correct checksum.")); } for (ServerModel service : me.getServices()) { String password = ""; String serviceLabel = service.getLabel(); Boolean expirePasswords = false; PasswordExec pass = new PasswordExec(serviceLabel, networkModel); if (pass.init()) { password = pass.getPassword(); password = Pattern.quote(password); //Turn special characters into literal so they don't get parsed out password = password.substring(2, password.length()-2).trim(); //Remove '\Q' and '\E' from beginning/end since we're not using this as a regex password = password.replace("\"", "\\\""); //Also, make sure quote marks are properly escaped! } if (pass.isDefaultPassword()) { expirePasswords = true; } units.addElement(new SimpleUnit(serviceLabel + "_password", "proceed", serviceLabel.toUpperCase() + "_PASSWORD=`printf \"" + password + "\" | mkpasswd -s -m md5`", "echo $" + serviceLabel.toUpperCase() + "_PASSWORD", "", "fail", "Couldn't set the passphrase for " + serviceLabel + ". You won't be able to configure this service.")); String bridge = networkModel.getData().getMetalIface(serviceLabel); if (bridge == null || bridge.equals("")) { bridge = me.getNetworkData().getLanIfaces(me.getLabel()).getOrDefault(0, "vm" + service.getThirdOctet()); } units.addAll(hypervisor.buildIso(service.getLabel(), hypervisor.preseed(service.getLabel(), expirePasswords))); units.addAll(hypervisor.buildServiceVm(service.getLabel(), bridge)); String bootDiskDir = networkModel.getData().getHypervisorThornsecBase(me.getLabel()) + "/disks/boot/" + serviceLabel + "/"; String dataDiskDir = networkModel.getData().getHypervisorThornsecBase(me.getLabel()) + "/disks/data/" + serviceLabel + "/"; units.addElement(new SimpleUnit(serviceLabel + "_boot_disk_formatted", "proceed", "", "sudo bash -c 'export LIBGUESTFS_BACKEND_SETTINGS=force_tcg;" + "virt-filesystems -a " + bootDiskDir + serviceLabel + "_boot.v*'", "", "fail", "Boot disk is unformatted (therefore has no OS on it), please configure the service and try mounting again.")); //For now, do this as root. We probably want to move to another user, idk units.addElement(new SimpleUnit(serviceLabel + "_boot_disk_loopback_mounted", serviceLabel + "_boot_disk_formatted", "sudo bash -c '" + " export LIBGUESTFS_BACKEND_SETTINGS=force_tcg;" + " guestmount -a " + bootDiskDir + serviceLabel + "_boot.v*" + " -i" //Inspect the disk for the relevant partition + " -o direct_io" //All read operations must be done against live, not cache + " --ro" //_MOUNT THE DISK READ ONLY_ + " " + bootDiskDir + "live/" +"'", "sudo mount | grep " + bootDiskDir, "", "fail", "I was unable to loopback mount the boot disk for " + serviceLabel + " in " + getLabel() + ".")); units.addElement(new SimpleUnit(serviceLabel + "_data_disk_formatted", "proceed", "", "sudo bash -c 'export LIBGUESTFS_BACKEND_SETTINGS=force_tcg;" + "virt-filesystems -a " + dataDiskDir + serviceLabel + "_data.v*'", "", "fail", "Data disk is unformatted (therefore hasn't been configured), please configure the service and try mounting again.")); units.addElement(new SimpleUnit(serviceLabel + "_data_disk_loopback_mounted", serviceLabel + "_data_disk_formatted", "sudo bash -c '" + " export LIBGUESTFS_BACKEND_SETTINGS=force_tcg;" + " guestmount -a " + dataDiskDir + serviceLabel + "_data.v*" + " -m /dev/sda1" //Mount the first partition + " -o direct_io" //All read operations must be done against live, not cache + " --ro" //_MOUNT THE DISK READ ONLY_ + " " + dataDiskDir + "live/" +"'", "sudo mount | grep " + dataDiskDir, "", "fail", "I was unable to loopback mount the data disk for " + serviceLabel + " in " + getLabel() + ". Backups will not work.")); } return units; } }
privacyint/ThornSec
src/profile/Metal.java
2,772
//Try not to duplicate ifaces if we're a Router/Metal
line_comment
en
true
9587_0
package assignment7; /** * Project 7 Chat Room * EE 422C submission by * Aditya Kharosekar amk3587 * Rahul Jain rj8656 * Fall 2016 * Slip days used - 1 (on this project) (overall - 2) * This is the second slip day that we have used this semester */ import java.util.HashMap; import java.util.Set; /** * This Map is just like a global variable. * It will store the username-password combinations of all users */ public class Map { public static HashMap<String, String> UsernamePasswordMap = new HashMap<>(); public static HashMap<String, Integer> nameID = new HashMap<>(); static int id = 0; public static void addOrChange(String username, String password) { UsernamePasswordMap.put(username, password); nameID.put(username, id); id++; } public static int size(){ return UsernamePasswordMap.size(); } public static Set getUsernames(){ return nameID.keySet(); } public static HashMap<String, Integer> getId(){ return nameID; } }
RahulJain28/Project7
Map.java
286
/** * Project 7 Chat Room * EE 422C submission by * Aditya Kharosekar amk3587 * Rahul Jain rj8656 * Fall 2016 * Slip days used - 1 (on this project) (overall - 2) * This is the second slip day that we have used this semester */
block_comment
en
true
9818_3
package io.Lorenzo; import java.util.Objects; /** * A class to represent a MAC address. * A MAC address is a 48-bit number, usually represented as a 12-digit hexadecimal number. * The hexadecimal number is usually split into 6 groups of 2 digits, separated by colons. * For example, the MAC address 00:0a:95:9d:68:16 is a valid MAC address. * This class represents a MAC address as a String, and provides methods to convert it to an int, and to compare it to other MAC addresses. * @see <a href="https://en.wikipedia.org/wiki/MAC_address">MAC address</a> * @see <a href="https://en.wikipedia.org/wiki/Hexadecimal">Hexadecimal</a> * @author Lorenzo * @version 1.0 */ public class MAC { /** * The MAC address, represented as a String. * The MAC address must be 17 characters long, and must be in the format XX:XX:XX:XX:XX:XX, where X is a hexadecimal digit. */ private final String mac; /** * The length of a MAC address, in characters. * A MAC address must be 17 characters long, including the colons. */ final int length = 17; /** * @param mac The MAC address, represented as a String. * The MAC address must be 17 characters long, and must be in the format XX:XX:XX:XX:XX:XX, where X is a hexadecimal digit. * For example, 00:0a:95:9d:68:16 is a valid MAC address. * The MAC address cannot be null. * @throws IllegalArgumentException if the MAC address is null, or is not 17 characters long, or is not in the format XX:XX:XX:XX:XX:XX, where X is a hexadecimal digit. * */ public MAC(String mac) { if(mac == null) throw new IllegalArgumentException("MAC cannot be null"); if(mac.length() != length) throw new IllegalArgumentException("MAC must be 17 characters long"); if(!mac.matches("^[A-Fa-f0-9]{2}(:[A-Fa-f0-9]{2}){5}$")) throw new IllegalArgumentException("MAC must be in the format XX:XX:XX:XX:XX:XX"); this.mac = mac; } /** * @return The MAC address, represented as a String, without colons. * For example, 00:0a:95:9d:68:16 would be returned as 000a959d6816. * @see #getMacAsLong() * */ public String getMacNoColons() { return mac.replaceAll(":", ""); } /** * @return The MAC address, represented as an int. * For example, 00:0a:95:9d:68:16 would be returned as 1077955622. * @see #getMacNoColons() */ public long getMacAsLong() { return Long.parseLong(getMacNoColons(), 16); } /** * @param mac The MAC address to compare this MAC address to. * @throws IllegalArgumentException if the MAC address is null. * @return true if this MAC address is greater than the MAC address passed as a parameter, false otherwise. */ public boolean isSmallerThan(MAC mac){ if(mac == null) throw new IllegalArgumentException("MAC cannot be null"); return getMacAsLong() < mac.getMacAsLong(); } /** * @param o The object to compare this MAC address to. * @return true if the object is a MAC address, and has the same MAC address as this MAC address, false otherwise. */ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MAC m)) return false; return Objects.equals(mac, m.mac); } /** * @return The hash code of this MAC address. * The hash code is calculated using the MAC address. */ @Override public int hashCode() { return Objects.hash(mac); } /** * @return The MAC address, represented as a String. */ @Override public String toString() { return mac; } }
Her0-GitHub/Java
MAC.java
1,048
/** * @param mac The MAC address, represented as a String. * The MAC address must be 17 characters long, and must be in the format XX:XX:XX:XX:XX:XX, where X is a hexadecimal digit. * For example, 00:0a:95:9d:68:16 is a valid MAC address. * The MAC address cannot be null. * @throws IllegalArgumentException if the MAC address is null, or is not 17 characters long, or is not in the format XX:XX:XX:XX:XX:XX, where X is a hexadecimal digit. * */
block_comment
en
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
10513_0
/** * Created by eugenevendensky on 1/17/17. */ public class Bank { private String accountType; private String accountNumer; private int balance; private String accountHoldersName; private float intRate; private String status = "Open"; private boolean overDraftProtection = true; private int transactionCounter; public int getAccountBalance() { System.out.println(balance); return balance; } public int creditAccount(int x) { balance += x; transactionCounter++; System.out.println("Your balance is now " + balance); return balance; } public int debitAccount(int x) { if (status.equalsIgnoreCase("Closed") || status.equalsIgnoreCase("Ofac freeze")) { System.out.println("The account is unavailable for withdrawal"); return balance; } else { if (overDraftProtection) { if (balance - x <= 0) { System.out.println("This transaction will result in an overdraft"); return balance; } else { int newBalance; newBalance = balance - x; balance = newBalance; System.out.println("Your balance is now " + balance); transactionCounter++; return balance; } } else { int newBalance; newBalance = balance - x; balance = newBalance; System.out.println("your balance is now " + balance); transactionCounter++; return balance; } } } public int getTransactions(){ System.out.println("Your account has had " + transactionCounter + " transactions"); return transactionCounter; } }
ggenya132/Access_Control_Lab
Bank.java
376
/** * Created by eugenevendensky on 1/17/17. */
block_comment
en
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
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
11425_2
package phoneBook189kk; /** * * @author Kristen Kellerman * KK: Class Main used for Binary Tree and Hash Table. */ public class Main { /** * KK: Used in the Binary Tree. */ String fullname; String email; String pnum; Main entry; /** * KK: Used in the Binary Tree to Find and Delete entries. * @param fullname concatenated first name and last name. * @param entry The entry in the Binary Tree Node. */ public Main(String fullname, Main entry) { this.fullname = fullname; this.entry = entry; } /** * KK: The constructor for the Binary Tree. * @param fname first name. * @param lname last name. * @param email email. * @param pnum phone number. */ Main(String fname, String lname, String email, String pnum) { this.fullname = (fname + " " + lname).toUpperCase(); this.email = email; this.pnum = pnum; } /** * KK: Begins the execution of the program. * @param args */ public static void main(String[] args) { /** * KK: Begins the Binary Tree test execution. */ Tree tree = new Tree(); tree.addEntry("Bob", "Smith", "[email protected]", "555-235-1111"); tree.addEntry("Jane", "Williams", "[email protected]", "555-235-1112"); tree.addEntry("Mohammed", "al-Salam", "[email protected]", "555-235-1113"); tree.addEntry("Pat", "Jones", "[email protected]", "555-235-1114"); tree.addEntry("Billy", "Kidd", "[email protected]", "555-235-1115"); tree.addEntry("H.", "Houdini", "[email protected]", "555-235-1116"); tree.addEntry("Jack", "Jones" , "[email protected]", "555-235-1117"); tree.addEntry("Jill", "Jones", "[email protected]", "555-235-1118"); tree.addEntry("John", "Doe", "[email protected]", "555-235-1119"); tree.addEntry("Jane", "Doe", "[email protected]", "555-235-1120"); tree.findEntry("Pat", "Jones"); tree.findEntry("Billy", "Kidd"); tree.deleteEntry("John", "Doe"); tree.addEntry("Test", "Case", "[email protected]", "555-235-1121"); tree.addEntry("Nadezhda", "Kanachekhovskaya", "[email protected]", "555-235-1122"); tree.addEntry("Jo", "Wu", "[email protected]", "555-235-1123"); tree.addEntry("Millard", "Fillmore", "[email protected]", "555-235-1124"); tree.addEntry("Bob", "vanDyke", "[email protected]", "555-235-1125"); tree.addEntry("Upside", "Down", "[email protected]", "555-235-1126"); tree.findEntry("Jack", "Jones"); tree.findEntry("Nadezhda", "Kanachekhovskaya"); tree.deleteEntry("Jill", "Jones"); tree.deleteEntry("John", "Doe"); tree.findEntry("Jill", "Jones"); tree.findEntry("John", "Doe"); /** * KK: Begins the Hash Table test execution. */ Table hashtable = new Table(13); hashtable.addEntry("Bob", "Smith", "[email protected]", "555-235-1111"); hashtable.addEntry("Jane", "Williams", "[email protected]", "555-235-1112"); hashtable.addEntry("Mohammed", "al-Salam", "[email protected]", "555-235-1113"); hashtable.addEntry("Pat", "Jones", "[email protected]", "555-235-1114"); hashtable.addEntry("Billy", "Kidd", "[email protected]", "555-235-1115"); hashtable.addEntry("H.", "Houdini", "[email protected]", "555-235-1116"); hashtable.addEntry("Jack", "Jones" , "[email protected]", "555-235-1117"); hashtable.addEntry("Jill", "Jones", "[email protected]", "555-235-1118"); hashtable.addEntry("John", "Doe", "[email protected]", "555-235-1119"); hashtable.addEntry("Jane", "Doe", "[email protected]", "555-235-1120"); hashtable.findEntry("Pat", "Jones"); hashtable.findEntry("Billy", "Kidd"); hashtable.deleteEntry("John", "Doe"); hashtable.addEntry("Test", "Case", "[email protected]", "555-235-1121"); hashtable.addEntry("Nadezhda", "Kanachekhovskaya", "[email protected]", "555-235-1122"); hashtable.addEntry("Jo", "Wu", "[email protected]", "555-235-1123"); hashtable.addEntry("Millard", "Fillmore", "[email protected]", "555-235-1124"); hashtable.addEntry("Bob", "vanDyke", "[email protected]", "555-235-1125"); hashtable.addEntry("Upside", "Down", "[email protected]", "555-235-1126"); hashtable.findEntry("Jack", "Jones"); hashtable.findEntry("Nadezhda", "Kanachekhovskaya"); hashtable.deleteEntry("Jill", "Jones"); hashtable.deleteEntry("John", "Doe"); hashtable.findEntry("Jill", "Jones"); hashtable.findEntry("John", "Doe"); } }
DaeData/Java_Data_Structures
Main.java
1,900
/** * KK: Used in the Binary Tree to Find and Delete entries. * @param fullname concatenated first name and last name. * @param entry The entry in the Binary Tree Node. */
block_comment
en
true
11454_1
package com.selenium.s1; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import io.github.bonigarcia.wdm.WebDriverManager; public class d41 { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub WebDriverManager.chromedriver().setup(); ChromeOptions co=new ChromeOptions(); co.addArguments("--remote-allow-origins=*"); WebDriver driver=new ChromeDriver(co); driver.get("https://demo.opencart.com/index.php?route=account/register&language=en-gb"); driver.manage().window().maximize(); Thread.sleep(3000); JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("window.scrollBy(0,2000)"); WebElement fn=driver.findElement(By.id("input-firstname")); fn.sendKeys("Maha"); WebElement ln=driver.findElement(By.id("input-lastname")); ln.sendKeys("jamindar"); WebElement em=driver.findElement(By.id("input-email")); em.sendKeys("[email protected]"); WebElement pw=driver.findElement(By.id("input-password")); pw.sendKeys("jamin@03"); WebElement sub=driver.findElement(By.id("input-newsletter-yes")); sub.click(); } }
Naveenm03/selenium1
d41.java
414
//demo.opencart.com/index.php?route=account/register&language=en-gb");
line_comment
en
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
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
13299_0
/*Write a program to input 10 integer elements in an array and sort them in ascending order using the bubble sort technique*/ import java.io.*; class YT6 { public static void main(String[] args)throws IOException { int a[]= new int[10]; int t=0; InputStreamReader I = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(I); System.out.println("Enter the array: "); for(int i=0; i<10; i++) { a[i]=Integer.parseInt(br.readLine()); } System.out.println("Original Array"); for(int i=0; i<10; i++) { System.out.print(a[i]+ " "); } for(int i=0; i<9; i++) { for(int j=0; j<9-i; j++) { if(a[j]>a[j+1]) { t=a[j]; a[j]=a[j+1]; a[j+1]=t; } } } System.out.println(); System.out.println("Sorted Array"); for(int i=0; i<10; i++) { System.out.print(a[i]+ " "); } } }
iankitnegi/CodeJava
YT6.java
316
/*Write a program to input 10 integer elements in an array and sort them in ascending order using the bubble sort technique*/
block_comment
en
true
13354_0
/*Design and implement a data structure for a compressed string iterator. It should support the following operations: next and hasNext. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string. next() - if the original string still has uncompressed characters, return the next letter; Otherwise return a white space. hasNext() - Judge whether there is any letter needs to be uncompressed. Note: Please remember to RESET your class variables declared in StringIterator, as static/class variables are persisted across multiple test cases. Please see here for more details. Example: StringIterator iterator = new StringIterator("L1e2t1C1o1d1e1"); iterator.next(); // return 'L' iterator.next(); // return 'e' iterator.next(); // return 'e' iterator.next(); // return 't' iterator.next(); // return 'C' iterator.next(); // return 'o' iterator.next(); // return 'd' iterator.hasNext(); // return true iterator.next(); // return 'e' iterator.hasNext(); // return false iterator.next(); // return ' ' */
wxping715/LeetCode
604.java
275
/*Design and implement a data structure for a compressed string iterator. It should support the following operations: next and hasNext. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string. next() - if the original string still has uncompressed characters, return the next letter; Otherwise return a white space. hasNext() - Judge whether there is any letter needs to be uncompressed. Note: Please remember to RESET your class variables declared in StringIterator, as static/class variables are persisted across multiple test cases. Please see here for more details. Example: StringIterator iterator = new StringIterator("L1e2t1C1o1d1e1"); iterator.next(); // return 'L' iterator.next(); // return 'e' iterator.next(); // return 'e' iterator.next(); // return 't' iterator.next(); // return 'C' iterator.next(); // return 'o' iterator.next(); // return 'd' iterator.hasNext(); // return true iterator.next(); // return 'e' iterator.hasNext(); // return false iterator.next(); // return ' ' */
block_comment
en
true
14391_1
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class BSTIterator { private List<Integer> nodes; private int counter; public BSTIterator(TreeNode root) { this.nodes = new ArrayList(); this.counter = 0; this.inorderTraverse(root); } private void inorderTraverse(TreeNode root){ if(root == null) return; this.inorderTraverse(root.left); this.nodes.add(root.val); this.inorderTraverse(root.right); } public int next() { return this.nodes.get(this.counter++); } public boolean hasNext() { return this.counter < this.nodes.size(); } } /** * Your BSTIterator object will be instantiated and called as such: * BSTIterator obj = new BSTIterator(root); * int param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */
iamtanbirahmed/100DaysOfLC
173.java
320
/** * Your BSTIterator object will be instantiated and called as such: * BSTIterator obj = new BSTIterator(root); * int param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */
block_comment
en
true
14627_0
/* 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 javax.media.opengl.GL; /** * This class draws the x, y, and z axes. * @author Brian Mock */ public class Axes { private Line xAxis; private Line yAxis; private Line zAxis; private float length = 1000; private float[] xEnd = {length, 0, 0 }; private float[] yEnd = {0, length, 0 }; private float[] zEnd = {0, 0, length}; private float[] origin = {0, 0, 0}; private float[] xColor = Colors.RED; private float[] yColor = Colors.GREEN; private float[] zColor = Colors.BLUE; public Axes() { xAxis = new Line(origin, xEnd, xColor); yAxis = new Line(origin, yEnd, yColor); zAxis = new Line(origin, zEnd, zColor); } public void draw(GL gl) { xAxis.draw(gl); yAxis.draw(gl); zAxis.draw(gl); } }
wavebeem/visint
Axes.java
451
/* 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/>. */
block_comment
en
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
15357_1
import java.text.ParseException; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.text.MaskFormatter; /** * Exemplos CPF válidos: * <p> * 123.456.789-09 (12345678909)<br> * 123.123.123-87 (12312312387)<br> * 111.222.333-96 (11122233396) */ public class Cpf { public static final String MASCARA = "###.###.###-##"; public static final int TAMANHO_APENAS_NUMEROS = 11; public static boolean validaCpf(String cpf) { if (cpf == null || cpf.isEmpty()) return false; Pattern pattern = Pattern .compile("(\\d)(\\d)(\\d)\\.?(\\d)(\\d)(\\d)\\.?(\\d)(\\d)(\\d)-?(\\d)(\\d)"); Matcher matcher = pattern.matcher(cpf); if (!matcher.matches()) return false; int[] digitos = new int[11]; for (int i = 0; i < digitos.length; i++) { digitos[i] = Integer.parseInt(matcher.group(i + 1)); } int resul1 = 0; int resul2 = 0; for (int i = 0; i < 9; i++) resul1 = (10 - i) * digitos[i] + resul1; resul1 = resul1 % 11; if (resul1 == 0 || resul1 == 1) resul1 = 0; else resul1 = 11 - resul1; if (resul1 == digitos[9]) { for (int i = 0; i < 10; i++) resul2 = (11 - i) * digitos[i] + resul2; resul2 = resul2 % 11; if (resul2 == 0 || resul2 == 1) resul2 = 0; else resul2 = 11 - resul2; if (resul2 == digitos[10]) return true; } return false; } /** * @return um CPF aleatório e válido. * @since Jan 15, 2015 * @author Ulisses */ public static String gerarCpf() { int digito1 = 0, digito2 = 0, resto = 0; String nDigResult; String numerosContatenados; String numeroGerado; Random numeroAleatorio = new Random(); // números gerados int n1 = numeroAleatorio.nextInt(10); int n2 = numeroAleatorio.nextInt(10); int n3 = numeroAleatorio.nextInt(10); int n4 = numeroAleatorio.nextInt(10); int n5 = numeroAleatorio.nextInt(10); int n6 = numeroAleatorio.nextInt(10); int n7 = numeroAleatorio.nextInt(10); int n8 = numeroAleatorio.nextInt(10); int n9 = numeroAleatorio.nextInt(10); int soma = n9 * 2 + n8 * 3 + n7 * 4 + n6 * 5 + n5 * 6 + n4 * 7 + n3 * 8 + n2 * 9 + n1 * 10; int valor = (soma / 11) * 11; digito1 = soma - valor; // Primeiro resto da divisão por 11. resto = (digito1 % 11); if (digito1 < 2) { digito1 = 0; } else { digito1 = 11 - resto; } int soma2 = digito1 * 2 + n9 * 3 + n8 * 4 + n7 * 5 + n6 * 6 + n5 * 7 + n4 * 8 + n3 * 9 + n2 * 10 + n1 * 11; int valor2 = (soma2 / 11) * 11; digito2 = soma2 - valor2; // Primeiro resto da divisão por 11. resto = (digito2 % 11); if (digito2 < 2) { digito2 = 0; } else { digito2 = 11 - resto; } // Concatenando os números numerosContatenados = String.valueOf(n1) + String.valueOf(n2) + String.valueOf(n3) + String.valueOf(n4) + String.valueOf(n5) + String.valueOf(n6) + String.valueOf(n7) + String.valueOf(n8) + String.valueOf(n9); // Concatenando o primeiro resto com o segundo. nDigResult = String.valueOf(digito1) + String.valueOf(digito2); numeroGerado = numerosContatenados + nDigResult; return numeroGerado; } /** * @param cpf * @return o cpf com máscara. * @since Aug 29, 2013 * @author Ulisses */ public static String aplicarMascara(String cpf) { if (cpf == null) return null; MaskFormatter mf; try { mf = new MaskFormatter(MASCARA); mf.setValueContainsLiteralCharacters(false); return mf.valueToString(cpf); } catch (ParseException e) { return cpf; } } /** * @param cpf * @return o cpf sem a máscara (apenas números) * @since Aug 29, 2013 * @author Ulisses */ public static String removerMascara(String cpf) { if (cpf == null) return null; return cpf.replaceAll("\\D", ""); } public static void main(String[] args) { for (int i = 0; i < 10; i++) { String cpf = gerarCpf(); boolean valido = validaCpf(cpf); System.out.println(cpf + " - " + valido); } } }
ulisseslima/bash-utils
Cpf.java
1,708
/** * @return um CPF aleatório e válido. * @since Jan 15, 2015 * @author Ulisses */
block_comment
en
true
16414_1
import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author 21cse095 */ public class school { public static void main(String[] args){ person obj = new student(); System.out.print("STUDENT DETAILS : "); obj.getdata(); obj.display(); person obj1 = new faculty(); System.out.print("FACULTY DETAILS : "); obj1.getdata(); obj1.display(); } } abstract class person{ abstract void getdata(); abstract void display(); } class student extends person{ String name; int aadhar; int n, total = 0, avg; void getdata(){ Scanner s = new Scanner(System.in); System.out.print("Enter Name:"); name = s.next(); System.out.print("Enter aadhar number:"); aadhar = s.nextInt(); System.out.print("Enter no. of subject:"); n = s.nextInt(); int marks[] = new int[n]; System.out.println("Enter marks out of 100:"); for(int i = 0; i < n; i++) { marks[i] = s.nextInt(); total = total + marks[i]; } avg = total / n; } void display() { System.out.println("....DETAILS...."); System.out.println("Name:"+name); System.out.println("aadharno:"+aadhar); System.out.println("total:"+total); System.out.println("average:"+avg); } } class faculty extends person{ String name; int aadhar; int id; String dept; int Salary; void getdata() { Scanner s = new Scanner(System.in); System.out.print("Enter Name:"); name = s.next(); System.out.print("Enter aadhar number:"); aadhar = s.nextInt(); System.out.print("Enter ID:"); id = s.nextInt(); System.out.print("Enter department:"); dept = s.next(); System.out.print("Enter Salary:"); Salary = s.nextInt(); } void display() { System.out.println("....DETAILS...."); System.out.println("Name:"+name); System.out.println("aadharno:"+aadhar); System.out.println("id:"+id); System.out.print("department:"+dept); System.out.println("salary:"+Salary); } }
21cse095/javacode
ex4/ex.java
652
/** * * @author 21cse095 */
block_comment
en
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
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
16795_0
// https://www.hackerrank.com/challenges/java-1d-array-introduction/problem import java.util.*; public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] a = new int[n]; for(int j=0;j<n;j++) { a[j] = scan.nextInt(); } scan.close(); // Prints each sequential element in array a for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } }
haytastan/Hackerrank_Java
19.java
154
// https://www.hackerrank.com/challenges/java-1d-array-introduction/problem
line_comment
en
true
16890_0
/** * Klasse Greifarm. * * @author [email protected] * * @version v4.0 (2018-08-7) */ public class Greifarm { private ea.edu.Dreieck stativ; private ea.edu.Kreis drehpunkt; private ea.edu.Rechteck arm; private Kugel gegriffeneKugel; private int winkel; private java.util.LinkedList<Kugel> kugeln; private boolean hatKugel; private Eimer rechts; private Eimer links; /** * Konstruktor der Klasse Greifarm */ public Greifarm() { this.stativ = new ea.edu.Dreieck( -50,-300 , 50,-300 , 0,-100 ); this.stativ.setzeFarbe( "grau" ); this.stativ.getActor().setLayer( 5 ); this.drehpunkt = new ea.edu.Kreis( 15 ); this.drehpunkt.setzeFarbe( "grau" ); this.drehpunkt.setzeMittelpunkt( 0 , -100 ); this.drehpunkt.getActor().setLayer( 5 ); this.arm = new ea.edu.Rechteck( 300 , 10 ); this.arm.setzeFarbe( "grau" ); this.arm.setzeMittelpunkt( 150 , -100 ); this.gegriffeneKugel = new Kugel( 0, 0 ); this.gegriffeneKugel.setzeSichtbar( false ); this.gegriffeneKugel.macheNeutral(); this.winkel = 0; this.hatKugel = false; } /** * Dreht den Greifarm um den angegebenen Winkel. * Gegen den Uhrzeigersinn = positive Winkel ; Mit dem Uhrzeigersinn = negativer Winkel * * @param winkel Der Winkel, um den gedreht werden soll */ public void drehenUm( int winkel ) { this.winkel += winkel; this.winkel %= 360; this.arm.drehen( (float)Math.toRadians(winkel) ); //////// this.arm.setzeMittelpunkt( (float)(150*Math.cos(Math.toRadians(this.winkel))) , (float)(150*Math.sin(Math.toRadians(this.winkel))-100) ); if ( this.hatKugel ) { this.gegriffeneKugel.setzeMittelpunkt( (float)(315*Math.cos(Math.toRadians(this.winkel))) , (float)(315*Math.sin(Math.toRadians(this.winkel))-100) ); } } public void greifen() { if ( !this.hatKugel ) { if ( this.arm.schneidet( this.kugeln.peekFirst() ) ) { this.gegriffeneKugel = this.kugeln.removeFirst(); this.gegriffeneKugel.macheNeutral(); this.gegriffeneKugel.setzeMittelpunkt( (float)(315*Math.cos(Math.toRadians(this.winkel))) , (float)(315*Math.sin(Math.toRadians(this.winkel))-100) ); this.kugeln.addLast( new Kugel( -380 , 380 ) ); } } this.hatKugel = true; } /** * Lässt die gegriffene Kugel los. * Tut nichts, wenn gerade keine Kugel gegriffen wird. * */ public void loslassen() { if ( this.hatKugel ) { this.gegriffeneKugel.macheAktiv(); } this.hatKugel = false; } /** * Nennt die Farbe der aktuell gegriffenen Kugel. * Wird gerade keine Kugel gegriffen, so wird "keine Kugel" gemeldet. * * @return Die Farbe der aktuell gegriffenen Kugel */ public String nenneFarbe() { String farbe = "keine Kugel"; if ( this.gegriffeneKugel != null ) { farbe = this.gegriffeneKugel.nenneFarbe(); } return farbe; } /** * Nennt den aktuellen Drehwinkel des Greifarms. * * @return Der aktuelle Drehwinkel des Greifarms */ public int nenneWinkel() { return this.winkel; } /** * Mit dieser Methode kann der Greifarm eine Referenz auf die Kugeln erhalten. * * @param kugeln Referenz auf die LinkedList von Kugeln der Klasse Greifi */ public void nimmReferenzAufKugeln( java.util.LinkedList<Kugel> kugeln ) { this.kugeln = kugeln; } /** * Mit dier Methode kann der Greifarm eine Referenz auf seine Eimer erhalten. * * @param links Referenz auf linken Eimer * @param rechts Referenz auf rechen Eimer */ public void nimmReferenzAufEimer( Eimer links , Eimer rechts ) { this.links = links; this.rechts = rechts; } /** * Gibt an, ob der Greifarm gerade eine Kugel hat oder leer ist. * * @return 'true' = hat Kugel ; 'false' = ist leer */ public boolean hatKugel() { return this.hatKugel; } // Ticker, der in Greifi angemeldet wurde public void tick() { if ( this.gegriffeneKugel != null ) { if ( this.gegriffeneKugel.nenneMy() < -250 ) { if ( this.gegriffeneKugel.nenneMx() > 222 && this.gegriffeneKugel.nenneMx() < 333 ) { this.gegriffeneKugel.setzeMittelpunkt( 2000 , 2000 ); this.rechts.erhoeheNummer(); } else if ( this.gegriffeneKugel.nenneMx() < -222 && this.gegriffeneKugel.nenneMx() > -333 ) { this.gegriffeneKugel.setzeMittelpunkt( 2000 , 2000 ); this.links.erhoeheNummer(); } } } } }
engine-alpha/bluej-greifroboter
Greifarm.java
1,758
/** * Klasse Greifarm. * * @author [email protected] * * @version v4.0 (2018-08-7) */
block_comment
en
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
17021_0
/** * * I declare that this code was written by me, 21011805. * I will not copy or allow others to copy my code. * I understand that copying code is considered as plagiarism. * * Student Name: Leticia Linus Jeraled * Student ID: 21011805 * Class: E63D * Date created: 2023-Jan-20 12:37:47 pm * */ package FYP; import java.util.List; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * @author 21011805 * */ @Entity public class Member { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @NotNull @NotEmpty(message = "Backend: member name cannot be empty") @Size(min = 3, max = 50, message = "Name length must be between 3 and 50 characters!") private String name; @NotNull @NotEmpty(message = "Backend: member username cannot be empty") @Size(min = 3, max = 50, message = "Username length must be between 3 and 50 characters!") private String username; @NotNull @NotEmpty(message = "Backend: member password cannot be empty") @Size(min = 5, max = 100, message = "Password length must be between 5 and 100 characters!") private String password; @NotNull @NotEmpty(message = "Backend: member email cannot be empty") @Size(min = 5, max = 50, message = "Email length must be between 5 and 50 characters!") private String email; private String role; private int banCount; private boolean isBanned; private double totalSpending = 0.0; @OneToMany(mappedBy = "member") private List<OrderItem> orderItems; @OneToMany(mappedBy = "member") private Set<Item> items; @OneToMany(mappedBy = "member") // Refers to the "member" property in the Review class private List<Review> reviews; // This represents the reviews written by the member private String imgName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public int getBanCount() { return banCount; } public void setBanCount(int banCount) { this.banCount = banCount; } public boolean isBanned() { return isBanned; } public void setBanned(boolean isBanned) { this.isBanned = isBanned; } public double getTotalSpending() { return totalSpending; } public void setTotalSpending(double totalSpending) { this.totalSpending = totalSpending; } public List<OrderItem> getOrderItems() { return orderItems; } public void setOrderItems(List<OrderItem> orderItems) { this.orderItems = orderItems; } public Set<Item> getItems() { return items; } public void setItems(Set<Item> items) { this.items = items; } public List<Review> getReviews() { return reviews; } public void setReviews(List<Review> reviews) { this.reviews = reviews; } public String getImgName() { return imgName; } public void setImgName(String imgName) { this.imgName = imgName; } }
21011805-LeticiaLinusJeraled/FYP
Member.java
1,181
/** * * I declare that this code was written by me, 21011805. * I will not copy or allow others to copy my code. * I understand that copying code is considered as plagiarism. * * Student Name: Leticia Linus Jeraled * Student ID: 21011805 * Class: E63D * Date created: 2023-Jan-20 12:37:47 pm * */
block_comment
en
true
17979_0
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ /** * * @author User */ class br { static String readLine() { throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody } static void close() { throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody } }
l0vnurul/100days
br.java
149
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */
block_comment
en
true
18110_0
/*Study the Human class carefully. Correct the class so that only one initialize method initializes all the Human class's instance variables. Requirements: The Human class must have 5 variables. The class must have one initialize method. The initialize method must have five parameters. */ /* Initializing objects */ public class Human { String name; char sex; int money; int weight; double size; public void initialize(String name, int money, char sex,int weight,double size) { this.name = name; this.money = money; this.sex = sex; this.weight = weight; this.size = size; } public static void main(String[] args) { } }
samira-nooreen/JavaPracticeProblems
Q40.java
168
/*Study the Human class carefully. Correct the class so that only one initialize method initializes all the Human class's instance variables. Requirements: The Human class must have 5 variables. The class must have one initialize method. The initialize method must have five parameters. */
block_comment
en
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
18527_3
// Created by Shawn O'Grady on 12/7/17. // Copyright © 2017 Shawn O'Grady. All rights reserved. // /* This code is a practice Java interview question from testdome.com https://www.testdome.com/questions/java/two-sum/10284?visibility=1&skillId=4 Problem statement: Write a function that, given a list and a target sum, returns zero-based indices of any two distinct elements whose sum is equal to the target sum. If there are no such elements, the function should return null. +passes 3/4 tests -code takes too long to answer when array has large # of elements */ package TwoSum; public class TwoSum { public static int[] findTwoSum(int[] list, int sum) { int listLength=list.length; int[] match=new int[2]; for(int i=0; i<listLength; i++){ for(int j=i+1; j<listLength; j++){ if(list[i]+list[j]==sum){ match[0]=i; match[1]=j; return match; } } } return null; //yes this results in an exception, but it's what specification said to do } public static void main(String[] args) { int[] indices = findTwoSum(new int[] { 1, 3, 5, 7, 9 }, 10); System.out.println(indices[0] + " " + indices[1]); } }
ShawnROGrady/TestdomeJava
TwoSum.java
386
/* This code is a practice Java interview question from testdome.com https://www.testdome.com/questions/java/two-sum/10284?visibility=1&skillId=4 Problem statement: Write a function that, given a list and a target sum, returns zero-based indices of any two distinct elements whose sum is equal to the target sum. If there are no such elements, the function should return null. +passes 3/4 tests -code takes too long to answer when array has large # of elements */
block_comment
en
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
19214_6
class Student { int coll_id; String University; static int University_Code; // Constructor public Student() { coll_id = 56; University = "OU"; University_Code = 45896; } // Here The Static block Execute only once becouse there a class loader and object initialization ,the class load only once so the static block is executed only once but object is initialized multiple times // Static Block static { University_Code = 0100; System.out.println("Static Block "+University_Code); } // Non-Static Method public void aa1() { System.out.println( coll_id + "," + University + "," + University_Code + " Non Static Method" ); } // Static Method public static void bb1(Student s3) { // The Static Method will not take the non-static Variables it will take only static Varibles System.out.println( s3.coll_id + "," + s3.University + "," + University_Code + " Static Method" ); } } class Static_Block { // If we don't keep static keyword in main then we need to use the object of Static BLock to over come this we use static keyword public static void main(String[] args) { Student s0=new Student(); s0.aa1(); Student s1 = new Student(); Student s2 = new Student(); s1.coll_id = 99; s1.University = "Jntu"; Student.University_Code = 123456; s1.aa1(); s2.aa1(); Student s3 = new Student(); // Here we are giving object itself so the we can run non-static varibles in static method s3.bb1(s3); } }
NishanthRathod09/JAVA
tut27.java
429
// If we don't keep static keyword in main then we need to use the object of Static BLock to over come this we use static keyword
line_comment
en
true
19263_0
/* * Copyright © 2012 Bart Massey and the Fall 2012 Portland State University CS 441/541 class * [This program is licensed under the "MIT License"] * Please see the file COPYING in the source * distribution of this software for license terms. */ class Block { Coord pos; // coordinates of upper-left corner char color; Coord[] squares; // array of relative positions Block(char color, Coord[] squares, int r, int c) { this.pos = new Coord(r, c); this.color = color; this.squares = squares; } Block(Block b) { pos = new Coord(b.pos); color = b.color; squares = b.squares; } boolean squareAt(Coord pos) { for (int i = 0; i < squares.length; i++) if (this.pos.offset(squares[i]).equals(pos)) return true; return false; } boolean squareAt(int r, int c) { return squareAt(new Coord(r, c)); } boolean intersects(Block b) { for (int i = 0; i < squares.length; i++) if (b.squareAt(pos.offset(squares[i]))) return true; return false; } boolean clipped() { for (int i = 0; i < squares.length; i++) { Coord s = pos.offset(squares[i]); if (s.clipped()) return true; } return false; } boolean isAt(int r, int c) { return pos.equals(r, c); } public boolean equals(Object o) { Block b = (Block)o; return b.color == color && b.pos.equals(pos); } public int hashCode() { return (pos.hashCode() << 8) | color; } }
BartMassey/simplicity-solver
Block.java
454
/* * Copyright © 2012 Bart Massey and the Fall 2012 Portland State University CS 441/541 class * [This program is licensed under the "MIT License"] * Please see the file COPYING in the source * distribution of this software for license terms. */
block_comment
en
true
19383_0
/** * @author Etherstrings * @create 2022-05-30 19:48 PACKAGE_NAME - the name of the target package where the new class or interface will be created. Algorithm - the name of the current project. null.java - the name of the PHP file that will be created. L944 - the name of the new file which you specify in the New File dialog box during the file creation. ps - the login name of the current user. 2022/5/30 - the current system date. 19:48 - the current system time. 2022 - the current year. 05 - the current month. 30 - the current day of the month. 19 - the current hour. 48 - the current minute. IntelliJ IDEA - the name of the IDE in which the file will be created. 5月 - the first 3 letters of the month name. Example: Jan, Feb, etc. 五月 - full name of a month. Example: January, February, etc */ public class L944 { public int minDeletionSize(String[] strs) { int index=strs[0].length(); int answer=0; for(int i=0;i<index;i++){ for(int j=1;j<strs.length;j++){ if(strs[j-1].charAt(i)>strs[j].charAt(i)){ answer++; break; } } } return answer; } }
Etherstrings/Algorithm
src/L944.java
354
/** * @author Etherstrings * @create 2022-05-30 19:48 PACKAGE_NAME - the name of the target package where the new class or interface will be created. Algorithm - the name of the current project. null.java - the name of the PHP file that will be created. L944 - the name of the new file which you specify in the New File dialog box during the file creation. ps - the login name of the current user. 2022/5/30 - the current system date. 19:48 - the current system time. 2022 - the current year. 05 - the current month. 30 - the current day of the month. 19 - the current hour. 48 - the current minute. IntelliJ IDEA - the name of the IDE in which the file will be created. 5月 - the first 3 letters of the month name. Example: Jan, Feb, etc. 五月 - full name of a month. Example: January, February, etc */
block_comment
en
true
19625_0
/** * GeekBrains. Java. Level 1. Lesson 4. Homework * * @author Andrey Klopov * @version dated 19 may 2017 *1. Полностью разобраться с кодом, попробовать переписать с нуля, стараясь не подглядывать в методичку; *2. Переделать проверку победы, чтобы она не была реализована просто набором условий, например, с использованием циклов. *3. * Попробовать переписать логику проверки победы, чтобы она работала для поля 5х5 и количества фишек 4. Очень желательно не делать это просто набором условий для каждой из возможных ситуаций; *4. *** Доработать искусственный интеллект, чтобы он мог блокировать ходы игрока. */ import java.util.Random; import java.util.Scanner; class DZ4 { final int SIZE = 5; final char DOT_X = 'x'; final char DOT_O = 'o'; final char DOT_EMPTY = '.'; char[][] map = new char [SIZE][SIZE]; Scanner sc = new Scanner(System.in); Random rand = new Random(); public static void main(String[] args) { new DZ4().go(); } void go(){ initMap(); while (true){ humanTurn(); printMap(); if(checkWin(DOT_X)){ System.out.println("YOU WON!"); break; } if (isMapFull()){ System.out.println("Sorry, DRAW"); break; } aiTurn(); printMap(); if(checkWin(DOT_O)){ System.out.println("AI WON"); break; } } System.out.println("GAME OVER."); } void printMap() { for(int y = 0; y < 5; ++y) { System.out.print((y + 1) + " "); for(int x = 0; x < 5; ++x) { System.out.print(map[y][x] + " "); } System.out.println(); } System.out.println(); } void initMap() { map = new char[SIZE][SIZE]; for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { map[i][j] = DOT_EMPTY; } } } void humanTurn() { int x; int y; while (true) { System.out.print("Введи Х_Y: "); if (sc.hasNextInt()) { y = sc.nextInt() - 1; } else { System.out.println("Ты ошибся. Повтори:"); continue; } if (sc.hasNextInt()) { x = sc.nextInt() - 1; } else { System.out.println("Ты ошибся. Повтори:"); continue; } if (isCellValid(y, x) && isCellEmpty(y, x)) { map[y][x] = DOT_X; break; } System.out.println("Ты ошибся. Повтори:"); } } void aiTurn() { int y; int x; while (true) { y = rand.nextInt(5); x = rand.nextInt(5); if (isCellEmpty(y,x)) { System.out.println("Ход компьютера X_Y: " + (y + 1) + " " + (x + 1)); map[y][x] = DOT_O; break; } } } boolean isCellValid(int y, int x) { return y >= 0 && y <= 4 && x >= 0 && y <= 4; } boolean isCellEmpty(int y, int x) { return map[y][x] == DOT_EMPTY; } boolean isMapFull() { for (int y = 0; y < 5; y++) { for (int x = 0; x < 5; x++) { if(map[y][x] == DOT_EMPTY) { return false; } } } return true; } boolean checkWin(char symb) { int strafeX; int y; for (strafeX = 0; strafeX < 2; ++strafeX) { for (y = 0; y < 5; ++y) { if (map[y][0 + strafeX] == symb && map[y][1 + strafeX] == symb && map[y][2 + strafeX] == symb && map[y][3 + strafeX] == symb) { return true; } } } for (strafeX = 0; strafeX < 2; ++strafeX) { for (y = 0; y < 5; ++y) { if (map[0 + strafeX][y] == symb && map[1 + strafeX][y] == symb && map[2 + strafeX][y] == symb && map[3 + strafeX][y] == symb) { return true; } } } for (strafeX = 0; strafeX < 2; ++strafeX) { for (y = 0; y < 2; ++y) { if (map[0 + strafeX][0 + y] == symb && map[1 + strafeX][1 + y] == symb && map[2 + strafeX][2 + y] == symb && map[3 + strafeX][3 + y] == symb) { return true; } if (map[4 - strafeX][0 + y] == symb && map[3 - strafeX][1 + y] == symb && map[2 - strafeX][2 + y] == symb && map[1 - strafeX][3 + y] == symb) { return true; } } } return false; } }
13Fox13/Java1
DZ4.java
1,581
/** * GeekBrains. Java. Level 1. Lesson 4. Homework * * @author Andrey Klopov * @version dated 19 may 2017 *1. Полностью разобраться с кодом, попробовать переписать с нуля, стараясь не подглядывать в методичку; *2. Переделать проверку победы, чтобы она не была реализована просто набором условий, например, с использованием циклов. *3. * Попробовать переписать логику проверки победы, чтобы она работала для поля 5х5 и количества фишек 4. Очень желательно не делать это просто набором условий для каждой из возможных ситуаций; *4. *** Доработать искусственный интеллект, чтобы он мог блокировать ходы игрока. */
block_comment
en
true
20020_5
package com.example.myfirstapp; // What's up JDP? Here is a little work I did on the Event and Date classes. We'll discuss all changes on Sunday? // I'm going to try to do some more work this weekend, but I will mostly just try to learn how to work with the SDK. public class Date { private int numberOfEvents; Event[] todaysEvents = new Event[50]; //50 events to begin with public void getListOfEvents(){ // I don't know what we want here } public void addEvent(){ todaysEvents[numberOfEvents] = new Event(); numberOfEvents++; } public void deleteEvent(int location){ todaysEvents[location] = null; } public Event getEvent(int location){ return todaysEvents[location]; } public void displayListOfEvents(){ for (int i = 0; i < numberOfEvents; i++){ todaysEvents[i].getName(); } } // public void displayEvents(){ // Same as displayListOFEvents()? // } }
david10p/JDP
Date.java
271
// Same as displayListOFEvents()?
line_comment
en
true
20060_0
/* * Copyright (c) The League of Amazing Programmers 2013-2017 * Level 1 */ public class Cat { private String name; private int lives = 9; Cat(String name) { this.name = name; } void meow() { System.out.println("meeeeeooooooooooowwwwwwwww!!"); } public void printName() { if (name == null) System.out.println("i don't know my own name!"); else System.out.println("my name is " + name); } void kill() { lives--; if (lives > 0) System.out.println("nice try, but I still have " + lives + " lives left"); else if (lives < 0) System.out.println("that's overkill yo!"); else System.out.println("DEAD CAT :("); } public static void main(String[] args) { /* Do the following things without changing the Cat class */ // 1. Make the Cat meow Cat Kayla = new Cat("Kayla"); Kayla.meow(); // 2. Get the Cat to print it's name Kayla.printName(); // 3. Kill the Cat! for (int i = 1; i < 10; i++) { Kayla.kill(); } } }
League-Level1-Student/level1-module1-kaylarwright
Cat.java
371
/* * Copyright (c) The League of Amazing Programmers 2013-2017 * Level 1 */
block_comment
en
true
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
40
Edit dataset card