file_id
int64
1
250k
content
stringlengths
0
562k
repo
stringlengths
6
115
path
stringlengths
1
147
247,980
import java.io.IOException; import java.util.StringTokenizer; import java.lang.NumberFormatException; import java.util.NoSuchElementException; import org.apache.hadoop.util.ToolRunner; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.conf.Configured; import java.util.ArrayList; import java.util.List; import java.text.SimpleDateFormat; import java.text.ParseException; import java.util.Map; import java.util.Comparator; import java.util.PriorityQueue; import java.lang.Comparable; public class TaskThree extends Configured implements Tool { static int printUsage() { System.out.println("taskone [-m <maps>] [-r <reduces>] <input> <output>"); ToolRunner.printGenericCommandUsage(System.out); return -1; } public static class TaskThreeMapper extends Mapper<Object, Text, Text, Text> { public class Tuple{ public final String x; public final Double y; public Tuple(String x, Double y) { this.x = x; this.y = y; } public int compareTo(Tuple t) { return this.y.compareTo(t.y); } } private Comparator<Tuple> byRevenue = (Tuple t1, Tuple t2) -> t1.compareTo(t2); private PriorityQueue<Tuple> queue = new PriorityQueue(5, byRevenue); private final static Text key = new Text(); private Text driverPair = new Text(); public void map(Object key, Text value, Context context ) throws IOException, InterruptedException { //Lines from the csv come in and the tokenizer breaks them up String[] input = value.toString().split("\\s"); if(input.length == 2) { double curRevenue; try { curRevenue = Double.parseDouble(input[1]); } catch(NumberFormatException e) { return; } queue.add(new Tuple(input[0], curRevenue)); if(queue.size() > 5) queue.remove(); } } public void cleanup(Context context) throws IOException, InterruptedException { key.set("key"); while(queue.size() > 0) { Tuple cur = queue.poll(); driverPair.set(cur.x.toString() + "=" + cur.y.toString()); context.write(key, driverPair); } } } public static class TaskThreeReducer extends Reducer<Text,Text,Text,Text> { public class Tuple{ public final String x; public final Double y; public Tuple(String x, Double y) { this.x = x; this.y = y; } public int compareTo(Tuple t) { return this.y.compareTo(t.y); } } private Comparator<Tuple> byRevenue = (Tuple t1, Tuple t2) -> t1.compareTo(t2); private PriorityQueue<Tuple> queue = new PriorityQueue(5, byRevenue); private Text revenue = new Text(); private Text driver = new Text(); public void reduce(Text key, Iterable<Text> values, Context context ) throws IOException, InterruptedException { for (Text pair : values) { String[] pairArray = pair.toString().split("="); queue.add(new Tuple(pairArray[0], Double.parseDouble(pairArray[1]))); if(queue.size() > 5) queue.remove(); } while(queue.size() > 0) { Tuple cur = queue.remove(); revenue.set(cur.y.toString()); driver.set(cur.x); context.write(driver,revenue); } } } public int run(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "Task Three"); job.setJarByClass(TaskThree.class); job.setMapperClass(TaskThreeMapper.class); //job.setCombinerClass(TaskThreeReducer.class); job.setReducerClass(TaskThreeReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); List<String> other_args = new ArrayList<String>(); for(int i=0; i < args.length; ++i) { try { if ("-r".equals(args[i])) { job.setNumReduceTasks(Integer.parseInt(args[++i])); } else { other_args.add(args[i]); } } catch (NumberFormatException except) { System.out.println("ERROR: Double expected instead of " + args[i]); return printUsage(); } catch (ArrayIndexOutOfBoundsException except) { System.out.println("ERROR: Required parameter missing from " + args[i-1]); return printUsage(); } } // Make sure there are exactly 2 parameters left. if (other_args.size() != 2) { System.out.println("ERROR: Wrong number of parameters: " + other_args.size() + " instead of 2."); return printUsage(); } FileInputFormat.setInputPaths(job, other_args.get(0)); FileOutputFormat.setOutputPath(job, new Path(other_args.get(1))); return (job.waitForCompletion(true) ? 0 : 1); } public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new TaskThree(), args); System.exit(res); } }
ell0ry/comp330
asgmt3/TaskThree.java
247,981
package codeptit; import java.io.*; import java.util.*; //@author Nevir2002 class KH06006{ String id,name,gender,dob,address; static int idx = 1; public KH06006(String name, String gender, String dob, String address) { id = String.format("KH%03d",idx++); this.name = name; this.gender = gender; this.dob = dob; this.address = address; } } class MH06006{ String id,name,unit; long buy,sell; static int idx = 1; public MH06006(String name, String unit, long buy, long sell) { id = String.format("MH%03d",idx++); this.name = name; this.unit = unit; this.buy = buy; this.sell = sell; } } class HD06006 implements Comparable<HD06006>{ String id; KH06006 customer; MH06006 product; int quantity; long total,revenue; static int idx = 1; static Vector<KH06006> customerList = new Vector<>(); static Vector<MH06006> productList = new Vector<>(); public HD06006(String customerID, String productID, int quantity) { id = String.format("HD%03d",idx++); for(KH06006 x:customerList){ if(x.id.equals(customerID)){ customer = x; break; } } for(MH06006 x:productList){ if(x.id.equals(productID)){ product = x; break; } } this.quantity = quantity; total = this.quantity*product.sell; revenue = total - this.quantity*product.buy; } public static void addCustomer(KH06006 a){ customerList.add(a); } public static void addProduct(MH06006 a){ productList.add(a); } @Override public int compareTo(HD06006 a){ // if(a.revenue == revenue) return id.com return Long.compare(a.revenue, revenue); } @Override public String toString(){ return String.format("%s %s %s %s %d %d %d", id,customer.name,customer.address,product.name,quantity,total,revenue); } } public class J06006 { public static void main(String[] args){ Scanner sc = new Scanner(System.in); Vector<HD06006> v = new Vector<>(); int t = Integer.parseInt(sc.nextLine()); while(t-->0){ HD06006.addCustomer(new KH06006(sc.nextLine(), sc.nextLine(), sc.nextLine(), sc.nextLine())); } t = Integer.parseInt(sc.nextLine()); while(t-->0){ HD06006.addProduct(new MH06006(sc.nextLine(), sc.nextLine(), Long.parseLong(sc.nextLine()), Long.parseLong(sc.nextLine()))); } t = Integer.parseInt(sc.nextLine()); while(t-->0){ v.add(new HD06006(sc.next(),sc.next(),sc.nextInt())); } Collections.sort(v); for(HD06006 x:v) System.out.println(x); sc.close(); } } //2 //Nguyen Van Nam //Nam //12/12/1997 //Mo Lao-Ha Dong-Ha Noi //Tran Van Binh //Nam //11/14/1995 //Phung Khoang-Nam Tu Liem-Ha Noi //2 //Ao phong tre em //Cai //25000 //41000 //Ao khoac nam //Cai //240000 //515000 //3 //KH001 MH001 2 //KH001 MH002 3 //KH002 MH002 4
Nevir2002/OOP-CodePTIT
J06006.java
247,984
import java.util.ArrayList; public class Company { protected String name, owner; protected ArrayList<String> grievances; // Initially empty protected int revenue, id; private static int cnt = 0; Company(String name, String owner) { this.name = name; this.owner = owner; id = cnt++; } Company(int id){ // TODO: get company by id from the database } int getId(){ return this.id; } }
t0mcr8se/SSAD-Project
Company.java
247,986
/* * Copyright (c) 2018. Aymen Naghmouchi * Copyright (c) 2018. Andrea Mennillo a[dot]mennillo1(at)studenti(dot)unisa[dot]it */ package model; public class Query { protected static final String deleteUser = "UPDATE user SET `password`=NULL, permission=NULL WHERE id=?;" + "DElETE FROM Wishlist WHERE user=?;"; protected static final String numOfProduct = "UPDATE productvariant SET available=?"; protected static final String deleteRow = "DELETE FROM tableName WHERE id=?"; protected static final String numberInfo = "SELECT COUNT(*) FROM "; protected static final String revenue = "SELECT SUM(price) FROM composition"; protected static final String allUsers = "SELECT * FROM user"; protected static final String category = "SELECT id, name FROM Category WHERE id=?"; protected static final String variantByProd = "SELECT id,size,discounted_price,sold,price,weight,available,color,path "+ "FROM ProductVariant p, Image i " + "WHERE p.product=? and i.product=p.product and i.variant = p.id"; protected static final String variantByKey = "SELECT size,discounted_price,sold,price,weight,available,color,path " + "FROM ProductVariant p, Image i " + "WHERE p.product=? and p.id=? and i.product=p.product and i.variant = p.id"; protected static final String productByKey = "SELECT Product.id, title, priceMin, priceMax, numReviews, path "+ " FROM Product, Image"+ " WHERE Product.id=? AND Image.product=Product.id AND Image.path LIKE '%default%' AND Image.variant=1"; protected static final String productAll = "SELECT Product.id,title, priceMin, priceMax, numReviews, path FROM Product, Image "+ "WHERE Image.product=Product.id AND path LIKE '%default%' AND VARIANT=1"; protected static final String productDetail = "SELECT title,description,category,gender,numReviews,priceMin,priceMax,path " + "FROM Product, Image " + "WHERE id=? AND Image.product=Product.id AND Image.path LIKE '%default%' AND Image.variant=1"; protected static final String userByMail = "SELECT id,password,permission "+ "FROM User WHERE email=?"; protected static final String userById = "SELECT id,name,surname,email,sex,date_of_birth as birth,password,permission "+ "FROM User WHERE id=?"; protected static final String signup = "INSERT INTO User (name,surname,email,password,sex,date_of_birth,permission)"+ "VALUES (?,?,?,?,?,?,?)"; protected static final String productSearch = "SELECT DISTINCT Product.id, title, priceMin, priceMax, numReviews, path "+ " FROM Product, Image, ProductVariant"+ " WHERE ProductVariant.product=Product.id" + " AND Image.product=Product.id AND Image.path LIKE '%default%' AND Image.variant=1"; protected static final String productDiscounted = "SELECT DISTINCT Product.id, ProductVariant.id, title, discounted_price,price, numReviews, path" + " FROM Product, Image, ProductVariant WHERE ProductVariant.product=Product.id AND Image.product=Product.id AND Image.path LIKE '%default%' AND Image.variant=1 AND discounted_price<price LIMIT ?" ; protected static final String countMatches = "SELECT COUNT( DISTINCT Product.id)"+ " FROM Product, Image, ProductVariant"+ " WHERE ProductVariant.product=Product.id" + " AND Image.product=Product.id AND Image.path LIKE '%default%' AND Image.variant=1"; protected static final String categorySearch = "SELECT DISTINCT Category.id as id, Category.name as name"+ " FROM Product, Category, ProductVariant"+ " WHERE ProductVariant.product=Product.id AND Category.id=category "; protected static final String sizeSearch = "SELECT DISTINCT size"+ " FROM Product, ProductVariant"+ " WHERE ProductVariant.product=Product.id"; protected static final String colorSearch = "SELECT DISTINCT color"+ " FROM Product, ProductVariant"+ " WHERE ProductVariant.product=Product.id"; protected static final String genderSearch = "SELECT DISTINCT gender"+ " FROM Product, ProductVariant"+ " WHERE ProductVariant.product=Product.id"; protected static final String updatePassword = "UPDATE User " + "SET password = ? WHERE id=?"; protected static final String updateProfile = "UPDATE User SET name=?, surname=?, email=?, sex=?, date_of_birth=?, permission=? " + " WHERE id=?"; protected static final String addressByUser = "SELECT id,city,country,phone_number, province, consignee, address_line,zip" + " FROM Address WHERE user=?"; protected static final String addressByid_User = "SELECT id,city,country,phone_number, province, consignee, address_line,zip" + " FROM Address WHERE user=? and id=?"; protected static final String insertAddress = "SET @user=?;SET @id = IFNULL((SELECT MAX(id) FROM address where user=@user),0)+1;" + "\nINSERT INTO address (id,`user`, country, province, city, zip, address_line, consignee, phone_number)" + "values (@id,@user,?,?,?,?,?,?,?);" + " SELECT @id as id;"; protected static final String updateAddress = "UPDATE address SET country=?,province=?,city=?,zip=?,address_line=?,consignee=?,phone_number=?" + " WHERE user=? and id=?"; protected static final String removeAddress = "DELETE FROM address" + " WHERE user=? AND id=?"; protected static final String reviewsByProd = "SELECT product, user, date, comment, score,User.name as user_name FROM Review,User WHERE product=? AND User.id=user"; protected static final String orderByUser= "SELECT id, address, track,consignee, total, shipping_date, ordering_date, delivery_date, shipping_fees, status, sign, payment_method" + " FROM `order` WHERE user=?"; protected static final String orderById_User= "SELECT user, address, track, consignee, total, shipping_date, ordering_date, delivery_date, shipping_fees, status, sign, payment_method" + " FROM `order` WHERE id=? and user=?"; protected static final String compositionByOrd = "SELECT title, color, size, quantity, Composition.price FROM Composition, Product, ProductVariant " + "WHERE `order`=? AND Product.id=Composition.product AND ProductVariant.id=Composition.variant AND Product.id=ProductVariant.product"; protected static final String saveOrder = "INSERT INTO `Order` (total, ordering_date, `user`, shipping_fees, status, payment_method, address, consignee) values (?,?,?,?,?,?,?,?)"; protected static final String saveComposition = "INSERT INTO Composition (product, variant, `order`, quantity, price) values (?,?,?,?,?)"; protected static String additionalWhere(String query, String q, int category, char gender, int countSize, int countColor, int sort, int limit, int offset) { if(q!=null && q.length()>0) query+=" AND MATCH (title,description) AGAINST (? IN NATURAL LANGUAGE MODE)"; if(gender=='M' || gender=='W') query+=" AND (gender=? OR gender='U')"; else if(gender=='K') query+=" AND gender=?"; if(category!=0) query+= " AND category=?"; if(countSize>0) { query+= " AND ( size=?"; while(--countSize>0) query+=" OR size=?"; query+=" ) "; } if(countColor>0) { query+= " AND ( color=?"; while(--countColor>0) query+=" OR color=?"; query+=" )"; } if(sort==1) query+=" ORDER BY priceMin ASC, priceMax ASC"; else if(sort==2) query+=" ORDER BY priceMax DESC, priceMin DESC"; else if(sort==3) query+=" ORDER BY name"; else if(sort==4) query+=" ORDER BY size"; if(limit>0) { query+=" LIMIT ?"; } if(offset>0) { query+=" OFFSET ?"; } return query; } }
aymen94/visionario
src/model/Query.java
247,988
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class measure { public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine(), " "); int count = 0, answer = -1; int N = Integer.parseInt(st.nextToken()); int K = Integer.parseInt(st.nextToken()); for(int i = 1; i <= N; i++){ if(N % i == 0){ count++; if(count == K){ answer = i; } } } if(answer == -1){ System.out.println(0); }else{ System.out.println(answer); } } }
Sean1016/commit_test
measure.java
247,989
public class Measure{ public static double inches2CMs(double num){ return num * 2.54; } }
jamesfallon99/CA269
Measure.java
247,990
import java.util.Arrays; import java.util.Scanner; public class ccc20s1 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); measure[] s = new measure[n]; for(int i = 0; i < n; i++) { int ac = sc.nextInt(); int bc = sc.nextInt(); s[i] = new measure(ac, bc); } Arrays.sort(s); double max = 0; for(int i = 0; i < n-1; i++) { double dist = Math.abs(s[i+1].ds-s[i].ds); double time = Math.abs(s[i+1].ts-s[i].ts); max = Math.max(dist/time, max); }System.out.println(max); } } class measure implements Comparable<measure>{ int ts; int ds; measure(int T, int D){ ts = T; ds = D; } @Override public int compareTo(measure o) { // TODO Auto-generated method stub return this.ts-o.ts; } }
VincentQu888/ccc-solutions
ccc20s1.java
247,991
package QuantSim; import org.ejml.data.CMatrixRMaj; import org.ejml.data.Complex_F32; import org.ejml.dense.row.CommonOps_CDRM; import java.lang.*; import java.math.BigDecimal; import java.math.MathContext; import java.util.Random; import java.io.IOException; class Measure { public static void main(String[] args) { MathContext mc = new MathContext(100); BigDecimal mean = new BigDecimal(0,mc); AnuRandom random = new AnuRandom(4096); byte[] bytes = random.getBytes(); for (int j = 0; j< 1024; j++){ int val = 0; String x = ""; for (int i = 4 * j; i < 4; i++) { x += Integer.toString(bytes[i], 2); } Random rand = new Random(val); mean = mean.add(new BigDecimal(rand.nextDouble(), mc), mc); } mean = mean.divide(new BigDecimal(1024, mc), mc); System.out.println(); System.out.println(mean.toString()); } public static int getSeed() { //Gets bytes from server, will exit if server inaccessible AnuRandom random = new AnuRandom(4); String temp = new String(random.getBytes()); //System.out.println(temp); //Gets bytes from server, throws catchable exception if server inaccessible try { temp = new String(random.getBytesSafe()); } catch (IOException e) { //Handle inaccessible server } int val = 0; for (int i = 0; i < 4; i++) { val = val << 8; val = val | (random.getBytes()[i] & 0xFF); } return val; } public static CMatrixRMaj measure(CMatrixRMaj amplitudes, int[] bits) { // get seed int seed = getSeed(); Random rand = new Random(seed); for (int index = 0; index < bits.length; index++) { // calculate probability that |x> = |1> double prob = 0.0; int ampsize = amplitudes.numRows; int bit = bits[index]; // statement inspired by a logarithm identity if (!(0 <= bit && bit < Math.log(ampsize) / Math.log(2))) return null; // precalculate some numbers for iteration int twobit = ampsize / (int) Math.pow(2, bit); int twobit1 = ampsize / (int) Math.pow(2, bit + 1); Complex_F32 out = new Complex_F32(0, 0); for (int pos = ampsize - 1; pos > 0; pos -= twobit) for (int i = 0; i < twobit1; i++) { amplitudes.get(pos - i, 0, out); prob += out.getMagnitude2(); } System.out.println(prob); //System.out.print("prob:"+prob+" // "); // "measure" |x> with random quantum seed int state; int x =rand.nextInt(100); System.out.println(x); if (prob * 100 > x -10) state = 1; else state = 0; //System.out.println("state:"+state); // given the measurement, 0 out entries for (int j = (state == 1 ? 0 : twobit1); j < ampsize; j += twobit) { for (int k = 0; k < twobit1; ++k) amplitudes.set(k + j, 0, 0, 0); } // renormalize new state vectors float mag = 0; for (int i = 0; i < ampsize; i++) { amplitudes.get(i, 0, out); mag += out.getMagnitude2(); } mag = (float) (1 / Math.sqrt(mag)); CommonOps_CDRM.scale(mag, 0, amplitudes); } return amplitudes; } }
bpatmiller/1
Measure.java
247,993
/* * Copyright © 1996-2009 Bart Massey * ALL RIGHTS RESERVED * [This program is licensed under the "MIT License"] * Please see the file COPYING in the source * distribution of this software for license terms. */ package aux; import java.awt.*; public class Table extends Panel implements LayoutManager { private static final int COL_LEFT = 1; private static final int COL_CENTER = 2; private static final int COL_RIGHT = 3; private static final int COL_FILL = 4; private boolean box = false; private boolean box_rows = false; private int cols[]; private int ncols; private int separators[]; private int hsizes[]; private int vsizes[]; private boolean stretches[]; private int nrows; private Component comp[] = null; public Table(String spec) { super(); table_layout(spec); setLayout(this); } private void table_layout(String spec) { ncols = 0; for (int i = 0; i < spec.length(); i++) switch(spec.charAt(i)) { case 'l': case 'r': case 'c': case 'f': ncols++; break; case '|': case '*': break; default: throw new IllegalArgumentException("Bad table specification char"); } cols = new int[ncols]; separators = new int[ncols - 1]; for (int i = 0; i < ncols - 1; i++) separators[i] = 0; stretches = new boolean[ncols]; for (int i = 0; i < ncols; i++) stretches[i] = false; boolean stretchable = false; int curcol = 0; for (int i = 0; i < spec.length(); i++) switch (spec.charAt(i)) { case 'l': cols[curcol++] = COL_LEFT; stretchable = true; break; case 'r': cols[curcol++] = COL_RIGHT; stretchable = true; break; case 'c': cols[curcol++] = COL_CENTER; stretchable = true; break; case 'f': cols[curcol++] = COL_FILL; stretchable = true; break; case '*': if (!stretchable) throw new IllegalArgumentException("Unexpected table stretch"); stretches[curcol - 1] = true; stretchable = false; break; case '|': if (curcol < 1 || curcol >= ncols || separators[curcol - 1] >= 2) throw new IllegalArgumentException("Bad table separator specification"); separators[curcol - 1]++; stretchable = false; break; default: throw new IllegalArgumentException("Unusual table specification error"); } if (ncols == 0) throw new IllegalArgumentException("Empty table specification"); } public void setBox(boolean box) { this.box = box; } public void setBoxRows(boolean box_rows) { this.box_rows = box_rows; } private void set_minimums(Component comp[]) { for (int i = 0; i < ncols; i++) { hsizes[i] = 0; vsizes[i] = 0; } for (int i = 0; i < comp.length; i++) { int x = i % ncols; int y = i / ncols; Dimension dm = comp[i].minimumSize(); if (dm.width > hsizes[x]) hsizes[x] = dm.width; if (dm.height > vsizes[y]) vsizes[y] = dm.height; } } private void set_preferreds(Component comp[]) { for (int i = 0; i < ncols; i++) hsizes[i] = 0; for (int i = 0; i < nrows; i++) vsizes[i] = 0; for (int i = 0; i < comp.length; i++) { int x = i % ncols; int y = i / ncols; Dimension dm = comp[i].preferredSize(); if (dm.width > hsizes[x]) hsizes[x] = dm.width; if (dm.height > vsizes[y]) vsizes[y] = dm.height; } } private Dimension csizes() { Dimension result = new Dimension(0, 0); for (int i = 0; i < ncols; i++) result.width += hsizes[i]; for (int i = 0; i < nrows; i++) result.height += vsizes[i]; for (int i = 0; i < ncols - 1; i++) if (separators[i] > 0) result.width += 1 + 2 * separators[i]; if (box) { result.height += 4; result.width += 4; } if (box_rows) result.height += 3 * (nrows - 1); return result; } private void set_slack(Dimension current, Dimension target) { Dimension raw = new Dimension(0, 0); for (int i = 0; i < ncols; i++) if (stretches[i]) raw.width += hsizes[i]; for (int i = 0; i < nrows; i++) raw.height += vsizes[i]; if (current.width < target.width) { int hslack = target.width - current.width; for (int i = 0; i < ncols; i++) if (stretches[i]) hsizes[i] += hslack * hsizes[i] / raw.width; } if (current.height < target.height) { int vslack = target.height - current.height; for (int i = 0; i < nrows; i++) vsizes[i] += vslack * vsizes[i] / raw.height; } } private void setup_measure(Container c) { comp = c.getComponents(); nrows = 1 + (comp.length - 1) / ncols; hsizes = new int[ncols]; vsizes = new int[nrows]; } private void measure(Container c) { setup_measure(c); set_preferreds(comp); Dimension dc = c.size(); Insets insets = c.insets(); dc.width -= insets.left + insets.right; dc.height -= insets.top + insets.bottom; Dimension ds = csizes(); if (ds.width < dc.width && ds.height < dc.height) { set_slack(ds, dc); return; } set_minimums(comp); Dimension dsx = csizes(); set_slack(dsx, dc); } public void paint(Graphics g) { super.paint(g); measure(this); Dimension ls = csizes(); Dimension cs = size(); Insets insets = insets(); cs.width -= insets.left + insets.right; cs.height -= insets.top + insets.bottom; int xpos = insets.left; if (cs.width > ls.width) xpos += (cs.width - ls.width) / 2; int ypos = insets.top; if (cs.height > ls.height) ypos += (cs.height - ls.height) / 2; if (box) g.drawRect(xpos, ypos, ls.width - 1, ls.height - 1); if (box_rows) { int ybase = ypos; if (box) ybase += 2; for (int i = 0; i < nrows; i++) { ybase += vsizes[i]; g.drawLine(xpos, ybase + 1, xpos + ls.width - 1, ybase + 1); ybase += 3; } } int xbase = xpos; if (box) xbase += 2; for (int i = 0; i < ncols - 1; i++) { xbase += hsizes[i]; switch (separators[i]) { case 2: g.drawLine(xbase + 1, ypos, xbase + 1, ypos + ls.height - 1); xbase += 2; case 1: g.drawLine(xbase + 1, ypos, xbase + 1, ypos + ls.height - 1); xbase += 3; } } } public Dimension minimumLayoutSize(Container c) { setup_measure(c); set_minimums(comp); Dimension dc = csizes(); Insets insets = c.insets(); dc.width += insets.left + insets.right; dc.height += insets.top + insets.bottom; return dc; } public Dimension preferredLayoutSize(Container c) { setup_measure(c); set_preferreds(comp); Dimension dc = csizes(); Insets insets = c.insets(); dc.width += insets.left + insets.right; dc.height += insets.top + insets.bottom; return dc; } public void layoutContainer(Container c) { measure(c); Dimension ls = csizes(); Dimension cs = c.size(); Insets insets = c.insets(); cs.width -= insets.left + insets.right; cs.height -= insets.top + insets.bottom; int ypos = insets.top; if (cs.height > ls.height) ypos += (cs.height - ls.height) / 2; if (box) ypos += 2; int voffsets[] = new int[nrows]; for (int i = 0; i < nrows; i++) { voffsets[i] = ypos; ypos += vsizes[i]; if (box_rows) ypos += 3; } int xpos = insets.left; if (cs.width > ls.width) xpos += (cs.width - ls.width) / 2; if (box) xpos += 2; int hoffsets[] = new int[ncols]; for (int i = 0; i < ncols; i++) { hoffsets[i] = xpos; xpos += hsizes[i]; if (i < ncols - 1) switch (separators[i]) { case 2: xpos += 2; case 1: xpos += 3; } } for (int i = 0; i < comp.length; i++) if (comp[i].isVisible()) { Dimension ps = comp[i].preferredSize(); int x = i % ncols; int y = i / ncols; int ho = hoffsets[x]; int hs = hsizes[x]; switch(cols[x]) { case COL_FILL: break; case COL_CENTER: if (hs > ps.width) { ho += (hs - ps.width) / 2; hs = ps.width; } break; case COL_RIGHT: if (hs > ps.width) { ho += hs - ps.width; hs = ps.width; } break; case COL_LEFT: if (hs > ps.width) hs = ps.width; break; } comp[i].reshape(ho, voffsets[y], hs, vsizes[y]); } } public void addLayoutComponent(String s, Component c) { } public void removeLayoutComponent(Component c) { } }
BartMassey/java-aux
Table.java
247,994
import android.app.Activity; import android.content.Context; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; import android.view.ViewParent; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import com.google.android.gms.ads.internal.client.AdSizeParcel; import com.google.android.gms.ads.internal.util.client.VersionInfoParcel; import java.util.Map; @aih public abstract interface ajm extends agi { public abstract WebView a(); public abstract void a(int paramInt); public abstract void a(Context paramContext); public abstract void a(AdSizeParcel paramAdSizeParcel); public abstract void a(String paramString); public abstract void a(String paramString, Map<String, ?> paramMap); public abstract void a(sn paramsn); public abstract void a(boolean paramBoolean); public abstract View b(); public abstract void b(int paramInt); public abstract void b(sn paramsn); public abstract void b(boolean paramBoolean); public abstract void c(); public abstract void c(boolean paramBoolean); public abstract void d(); public abstract Activity e(); public abstract Context f(); public abstract uh g(); public abstract Context getContext(); public abstract ViewGroup.LayoutParams getLayoutParams(); public abstract void getLocationOnScreen(int[] paramArrayOfInt); public abstract int getMeasuredHeight(); public abstract int getMeasuredWidth(); public abstract ViewParent getParent(); public abstract sn h(); public abstract sn i(); public abstract AdSizeParcel j(); public abstract ajn k(); public abstract boolean l(); public abstract void loadDataWithBaseURL(String paramString1, String paramString2, String paramString3, String paramString4, String paramString5); public abstract void loadUrl(String paramString); public abstract adw m(); public abstract void measure(int paramInt1, int paramInt2); public abstract VersionInfoParcel n(); public abstract boolean o(); public abstract void onPause(); public abstract void onResume(); public abstract boolean p(); public abstract void q(); public abstract boolean r(); public abstract ajl s(); public abstract void setBackgroundColor(int paramInt); public abstract void setOnClickListener(View.OnClickListener paramOnClickListener); public abstract void setOnTouchListener(View.OnTouchListener paramOnTouchListener); public abstract void setWebChromeClient(WebChromeClient paramWebChromeClient); public abstract void setWebViewClient(WebViewClient paramWebViewClient); public abstract afc t(); public abstract afe u(); public abstract void v(); public abstract void w(); } /* Location: * Qualified Name: ajm * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
reverseengineeringer/com.ubercab
src/ajm.java
247,995
import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Locale; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.safety.Whitelist; import org.jsoup.select.Elements; import org.jsoup.select.NodeFilter; import org.w3c.dom.Node; import javax.swing.text.html.parser.Parser; public class Stemmer { private char[] b; private int i, i_end, j, k; private static final int INITIAL_SIZE = 40; /* unit of size whereby b is increased */ public Stemmer() { b = new char[INITIAL_SIZE]; i = 0; i_end = 0; } /** * Add a character to the word being stemmed. When you are finished adding * characters, you can call stem(void) to stem the word. */ public void add(char ch) { if (i == b.length) { char[] new_b = new char[i + INITIAL_SIZE]; for (int c = 0; c < i; c++) new_b[c] = b[c]; b = new_b; } b[i++] = ch; } public void add(String w) { int wLen = w.length(); if (i + wLen >= b.length) { char[] new_b = new char[i + wLen + INITIAL_SIZE]; for (int c = 0; c < i; c++) new_b[c] = b[c]; b = new_b; } for (int c = 0; c < wLen; c++) b[i++] = w.charAt(c); } /** * return stemmed word */ public String getStem() { return new String(b, 0, i_end); } /** * Returns the length of the word resulting from the stemming process. */ public int getResultLength() { return i_end; } /* isConsonant(i) is true <=> b[i] is a consonant. */ private final boolean isConsonant(int i) { switch (b[i]) { case 'a': case 'e': case 'i': case 'o': case 'u': return false; case 'y': return (i == 0) ? true : !isConsonant(i - 1); default: return true; } } /* * measure() measures the number of consonant sequences between 0 and j. if c is * a consonant sequence and v a vowel sequence, and <..> indicates arbitrary * presence, <c><v> gives 0 <c>vc<v> gives 1 <c>vcvc<v> gives 2 <c>vcvcvc<v> * gives 3 .... */ private final int measure() { int n = 0; int i = 0; while (true) { if (i > j) return n; if (!isConsonant(i)) break; i++; } i++; while (true) { while (true) { if (i > j) return n; if (isConsonant(i)) break; i++; } i++; n++; while (true) { if (i > j) return n; if (!isConsonant(i)) break; i++; } i++; } } /* vowelinstem() is true <=> 0,...j contains a vowel */ private final boolean vowelinstem() { int i; for (i = 0; i <= j; i++) if (!isConsonant(i)) return true; return false; } /* doubleConsonant(j) is true <=> j,(j-1) contain a double consonant. */ private final boolean doubleConsonant(int j) { if (j < 1) return false; if (b[j] != b[j - 1]) return false; return isConsonant(j); } /* * cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant and * also if the second c is not w,x or y. this is used when trying to restore an * e at the end of a short word. e.g. cav(e), lov(e), hop(e), crim(e), but snow, * box, tray. */ private final boolean cvc(int i) { if (i < 2 || !isConsonant(i) || isConsonant(i - 1) || !isConsonant(i - 2)) return false; { int ch = b[i]; if (ch == 'w' || ch == 'x' || ch == 'y') return false; } return true; } private final boolean endsWith(String s) { int l = s.length(); int o = k - l + 1; if (o < 0) return false; for (int i = 0; i < l; i++) if (b[o + i] != s.charAt(i)) return false; j = k - l; return true; } /* * replaceWith(s) sets (j+1),...k to the characters in the string s, readjusting * k. */ private final void replaceWith(String s) { int l = s.length(); int o = j + 1; for (int i = 0; i < l; i++) b[o + i] = s.charAt(i); k = j + l; } /* replaceIfMeasure(s) is used further down. */ private final void replaceIfMeasure(String s) { if (measure() > 0) replaceWith(s); } /* * first() gets rid of plurals and -ed or -ing. e.g. caresses -> caress ponies * -> poni ties -> ti caress -> caress cats -> cat feed -> feed agreed -> agree * disabled -> disable matting -> mat mating -> mate meeting -> meet milling -> * mill messing -> mess meetings -> meet */ private final void first() { // first-a if (b[k] == 's') { if (endsWith("sses")) k -= 2; else if (endsWith("ies")) { replaceWith("i"); } else if (b[k - 1] != 's') k--; } // first-b if (endsWith("eed")) { if (measure() > 0) k--; } else if ((endsWith("ed") || endsWith("ing")) && vowelinstem()) { k = j; if (endsWith("at")) replaceWith("ate"); else if (endsWith("bl")) replaceWith("ble"); else if (endsWith("iz")) replaceWith("ize"); else if (doubleConsonant(k)) { k--; { int ch = b[k]; if (ch == 'l' || ch == 's' || ch == 'z') k++; } } else if (measure() == 1 && cvc(k)) replaceWith("e"); } if (endsWith("y") && vowelinstem()) b[k] = 'i'; } /* * second() maps double suffices to single ones. so -ization ( = -ize plus * -ation) maps to -ize etc. note that the string before the suffix must give * measure() > 0. */ private final void second() { if (k == 0) return; if (endsWith("ational")) { replaceIfMeasure("ate"); return; } if (endsWith("tional")) { replaceIfMeasure("tion"); return; } if (endsWith("enci")) { replaceIfMeasure("ence"); return; } if (endsWith("anci")) { replaceIfMeasure("ance"); return; } if (endsWith("izer")) { replaceIfMeasure("ize"); return; } if (endsWith("bli")) { replaceIfMeasure("ble"); return; } if (endsWith("alli")) { replaceIfMeasure("al"); return; } if (endsWith("entli")) { replaceIfMeasure("ent"); return; } if (endsWith("eli")) { replaceIfMeasure("e"); return; } if (endsWith("ousli")) { replaceIfMeasure("ous"); return; } if (endsWith("ization")) { replaceIfMeasure("ize"); return; } if (endsWith("ation")) { replaceIfMeasure("ate"); return; } if (endsWith("ator")) { replaceIfMeasure("ate"); return; } if (endsWith("alism")) { replaceIfMeasure("al"); return; } if (endsWith("iveness")) { replaceIfMeasure("ive"); return; } if (endsWith("fulness")) { replaceIfMeasure("ful"); return; } if (endsWith("ousness")) { replaceIfMeasure("ous"); return; } if (endsWith("aliti")) { replaceIfMeasure("al"); return; } if (endsWith("iviti")) { replaceIfMeasure("ive"); return; } if (endsWith("biliti")) { replaceIfMeasure("ble"); return; } if (endsWith("logi")) { replaceIfMeasure("log"); return; } } /* third() deals with -ic-, -full, -ness etc. similar strategy to second. */ private final void third() { if (endsWith("icate")) { replaceIfMeasure("ic"); return; } if (endsWith("ative")) { replaceIfMeasure(""); return; } if (endsWith("alize")) { replaceIfMeasure("al"); return; } if (endsWith("iciti")) { replaceIfMeasure("ic"); return; } if (endsWith("ical")) { replaceIfMeasure("ic"); return; } if (endsWith("ful")) { replaceIfMeasure(""); return; } if (endsWith("ness")) { replaceIfMeasure(""); return; } if (endsWith("er")) { replaceIfMeasure(""); return; } } /* fourth() takes off -ant, -ence etc., in context <c>vcvc<v>. */ private final void fourth() { if (k == 0) return; switch (b[k - 1]) { case 'a': if (endsWith("al")) break; return; case 'c': if (endsWith("ance")) break; if (endsWith("ence")) break; return; case 'e': if (endsWith("er")) break; return; case 'i': if (endsWith("ic")) break; return; case 'l': if (endsWith("able")) break; if (endsWith("ible")) break; return; case 'n': if (endsWith("ant")) break; if (endsWith("ement")) break; if (endsWith("ment")) break; if (endsWith("ent")) break; return; case 'o': if (endsWith("ion") && j >= 0 && (b[j] == 's' || b[j] == 't')) break; if (endsWith("ou")) break; return; case 's': if (endsWith("ism")) break; return; case 't': if (endsWith("ate")) break; if (endsWith("iti")) break; return; case 'u': if (endsWith("ous")) break; return; case 'v': if (endsWith("ive")) break; return; case 'z': if (endsWith("ize")) break; return; default: return; } if (measure() > 1) k = j; } /* fifth() removes a final -e if measure() > 1. */ private final void fifth() { j = k; if (b[k] == 'e') { int a = measure(); if (a > 1 || a == 1 && !cvc(k - 1)) k--; } if (b[k] == 'l' && doubleConsonant(k) && measure() > 1) k--; } /** * You can retrieve the result with getResultLength() or getStem(). */ public void stem() { k = i - 1; if (k > 1) { first(); second(); third(); fourth(); fifth(); } i_end = k + 1; i = 0; } public static String parser(String fileName) throws IOException { FileWriter myWriter = new FileWriter("StemmedWords.txt"); StringBuilder sb = new StringBuilder(); String line; FileReader reader = new FileReader("C:\\Users\\kahmd\\Desktop\\Indexer\\"+fileName+".html"); BufferedReader br = new BufferedReader(reader); while ( (line=br.readLine()) != null) { sb.append(line); } Stemmer s = new Stemmer(); //Parsing html code : remove tags and returns seperated words in string Document doc = Jsoup.parse(sb.toString()); String title = doc.title(); Elements headers = doc.select("h2,h3,h4,h5,h6"); String headings = Jsoup.parse(headers.html()).text(); doc.select("h1,h2,h3,h4,h5,h6").remove(); String bodyParsed = doc.text(); //remove Digits and Special Characters from bodyParsed string bodyParsed = bodyParsed.replaceAll("[\\d-+.^:,*!@#$%_·?©×\"'()<>{}؛÷،/:φ=]",""); List<String> stopwords = Files.readAllLines(Paths.get("stopWords.txt")); myWriter.write("*title\n"); for (String word : title.split(" ")) { word = word.toLowerCase(); if(!stopwords.contains(word)&&word!="") { s.add(word); s.stem(); myWriter.write(s.getStem()+"\n"); } } myWriter.write("*headers\n"); for (String word : headings.split(" ")) { word = word.toLowerCase(); if(!stopwords.contains(word)&&word!="") { s.add(word); s.stem(); myWriter.write(s.getStem()+"\n"); } } myWriter.write("*plainText\n"); for (String word : bodyParsed.split(" ")) { word = word.toLowerCase(); if(!stopwords.contains(word)&&word!="") { s.add(word); s.stem(); myWriter.write(s.getStem()+"\n"); } } myWriter.close(); return bodyParsed; } public static void main(String[] args) throws IOException { parser("page"); } }
AhmedKhaled590/AP_Search_engine
Stemmer.java
247,996
import java.util.Scanner; class Measure{ static int min(int a, int b){ if (a < b){ return a; //defining a method that takes two int argumnets and returns the smaller int value }else{ return b; } } static int max(int a, int b){ if (a > b){ return a; // defining a second method that also takes two arguments and returns the larger int value }else{ return b; } } public static void main(String[] args){ Scanner xt = new Scanner(System.in); while (1 > 0){ System.out.println("What mathematical operation do you want to calculate"); System.out.println("min - minimum \nmax - maximum"); String user_input = xt.nextLine(); if (user_input== "min"){ System.out.println("Enter the numbers; "); int x = xt.nextInt(); int y = xt.nextInt(); System.out.println("The smaller number is: "+ min(x,y)); continue; } else if (user_input.equals("max")){ System.out.println("Enter the numbers; "); int x = xt.nextInt(); int y = xt.nextInt(); System.out.println("The larger number is: "+ max(x,y)); continue; }else{ System.out.println("Invalid input"); } } } }
thechibuzor1/Cs-Class-Projects
Measure.java
247,997
import java.util.ArrayList; import java.util.concurrent.ThreadLocalRandom; public class Qubit { private QuantumSystem quantumSystem; private ComplexNumber alpha; // Represents the probability amplitude of |0> state private ComplexNumber beta; // Represents the probability amplitude of |1> state public Qubit(QuantumSystem system) { this.quantumSystem = system; // Initialize with equal probabilities for |0> and |1> states this.alpha = new ComplexNumber(1, 0).normalize(); this.beta = new ComplexNumber(0, 0); } // Add getters and setters as necessary for the amplitudes list // Also include any methods required for the functionality of your Qubit class public void measure() { double probability = ThreadLocalRandom.current().nextDouble(0, 1); if (probability < Math.pow(alpha.magnitude(), 2)) { // Collapse to |0> state alpha = new ComplexNumber(1, 0); beta = new ComplexNumber(0, 0); System.out.println("Collapse to |0> state"); } else { // Collapse to |1> state System.out.println("Collapse to |1> state"); alpha = new ComplexNumber(0, 0); beta = new ComplexNumber(1, 0); } } @Override public String toString() { return "|0>: " + alpha.toString() + ", |1>: " + beta.toString(); } }
pwgit-create/VirtualQuantumSystemTemplate
Qubit.java
248,001
import java.lang.*; import java.util.*; import rosas.lou.weatherclasses.PortSniffer; import gnu.io.*; import com.dalsemi.onewire.*; import com.dalsemi.onewire.adapter.*; import com.dalsemi.onewire.container.*; import com.dalsemi.onewire.utils.Convert; public class PortApp{ private PortSniffer ps; private DSPortAdapter dspa; private TemperatureContainer thermo; { ps = null; dspa = null; thermo = null; }; public static void main(String[] args){ new PortApp(); } public PortApp(){ ps = new PortSniffer(PortSniffer.PORT_USB); Hashtable<Stack<String>,Stack<String>> hash = ps.findPorts(); Enumeration<Stack<String>> e = hash.keys(); String name = null; String port = null; while(e.hasMoreElements()){ Stack<String> key = e.nextElement(); Stack<String> elements = hash.get(key); name = key.pop(); port = key.pop(); System.out.println("Name: "+name+", "+"Port: "+port); while(!elements.empty()){ System.out.println("Element: "+elements.pop()); } } try{ this.dspa = OneWireAccessProvider.getAdapter(name, port); this.printSensors(); try{ int x = 0; while(x < 10000){ this.measure(); Thread.sleep(600000); ++x; } } catch(InterruptedException ie){} } catch(OneWireIOException ioe){ ioe.printStackTrace(); } catch(OneWireException owe){ owe.printStackTrace(); } } private void measure(){ try{ byte [] state = this.thermo.readDevice(); this.thermo.doTemperatureConvert(state); state = this.thermo.readDevice(); double currentTemp = this.thermo.getTemperature(state); System.out.println(currentTemp); System.out.println(Convert.toFahrenheit(currentTemp)); } catch(OneWireIOException ioe){ ioe.printStackTrace(); } catch(OneWireException owe){ owe.printStackTrace(); } } private void printSensors(){ try{ Enumeration<OneWireContainer> e = this.dspa.getAllDeviceContainers(); while(e.hasMoreElements()){ OneWireContainer o = (OneWireContainer)e.nextElement(); if(o.getName().equals("DS1920") || o.getName().equals("DS18S20")){ System.out.println(o.getName()); System.out.println(o.getAddressAsString()); System.out.println(o.getDescription()); this.thermo = new OneWireContainer10(dspa, o.getAddressAsString()); byte [] state = this.thermo.readDevice(); if(this.thermo.hasSelectableTemperatureResolution()){ double [] resolution = this.thermo.getTemperatureResolutions(); this.thermo.setTemperatureResolution( resolution[resolution.length-1],state); this.thermo.writeDevice(state); } } } } catch(OneWireIOException ioe){ ioe.printStackTrace(); } catch(OneWireException owe){ owe.printStackTrace(); } } }
lourosas/bin
PortApp.java
248,002
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.stream.Collectors; public class Day14 { public static void main(String... args) { for (var input : List.of(TEST_INPUT, INPUT)) { partI(input); partII(input); } } private static void partI(String state) { System.out.println("Part I: " + measure(tilt(state))); } private static void partII(String state) { long totalSpinCycles = 1_000_000_000; var stateToCycle = new HashMap<String, Long>(); for (long spinCycle = 1; spinCycle <= totalSpinCycles; spinCycle++) { state = spin(state); Long cycleStart = stateToCycle.putIfAbsent(state, spinCycle); if (cycleStart != null) { long cycleLength = spinCycle - cycleStart; while (spinCycle < totalSpinCycles - cycleLength) { spinCycle += cycleLength; } long spinCyclesLeft = totalSpinCycles - spinCycle; state = stateToCycle.entrySet() .stream() .filter(entry -> entry.getValue() == cycleStart + spinCyclesLeft) .map(Entry::getKey) .findFirst() .orElseThrow(); break; } } System.out.println("Part II: " + measure(state)); } static String spin(String state) { for (int i = 0; i < 4; i++) { state = rotate(tilt(state)); } return state; } static String rotate(String input) { var rotated = new ArrayList<StringBuilder>(); var lines = input.lines().toList(); for (int x = 0; x < lines.get(0).length(); x++) { StringBuilder sb = new StringBuilder(); for (String line : lines.reversed()) { sb.append(line.charAt(x)); } rotated.add(sb); } return String.join("\n", rotated); } static String tilt(String state) { List<String> lines = state.lines().collect(Collectors.toList()); for (int y = 0; y < lines.size(); y++) { for (int x = 0; x < lines.get(y).length(); x++) { if (lines.get(y).charAt(x) == '.') { for (int y2 = y + 1; y2 < lines.size(); y2++) { if (lines.get(y2).charAt(x) == 'O') { lines.set(y, with(lines.get(y), x, 'O')); lines.set(y2, with(lines.get(y2), x, '.')); break; } else if (lines.get(y2).charAt(x) == '#') { break; } } } } } return String.join("\n", lines); } static String with(String s, int ix, char v) { var sb = new StringBuilder(s); sb.setCharAt(ix, v); return sb.toString(); } static long measure(String state) { var lineTotals = state.lines().map(line -> line.chars().filter(c -> c == 'O').count()).toList(); long total = 0; for (int lineNbr = 1; lineNbr <= lineTotals.size(); lineNbr++) { total += lineNbr * lineTotals.get(lineTotals.size() - lineNbr); } return total; } static final String TEST_INPUT = """ O....#.... O.OO#....# .....##... OO.#O....O .O.....O#. O.#..O.#.# ..O..#O..O .......O.. #....###.. #OO..#...."""; static final String INPUT = """ ..#.#O##....O.O#O#O...O.....O........OO...#OO.O..O...O..O...O.....O....#O#..O#.......O.##..O....#..# .O#O.#O.O#OO..#..O....OOO#....#.O#O..OO#..O...OOO.#.O..#..O#OO.#O..O#...##.#O#..OO#O#O.....#O.O.OO.O ...O..O.....#..#.O...O##.O...O...OO..#O.OO..###.OO.....##O.#.#.O.#.......O.....O...O...#.....O.#.#O. .#..O.....#..O..OO.O#.....#OOO...OO..#....OO#..O.......................O..#.#O....#.OO.#..O.......#. ......O.##O......##.#.#..O.##............#.O.O.O..O#O.#.O....#....#....#OOO....O#O.O..#..#....O#..O# ...O#..O...O.O#.O#O...#..O.O.....O..#..#O.#......##..OO.#....#.....###..#...#.O.#.OOO.O.....#O...#O. .#O##.#O.O.##O.##.#O....#..O..#......OOO..OO..#.#.#..#O...#O.#.#.O#O...#.#O..#.#....O........OO..... ##......O##.#.......O.#..#OO....O..OO.O.O..O#.....OO..O.O....#.O................#O...#O.#...O.O....O ...OO.O....##.##...##O...O..O..O#...O.#....#..O...O..#...O....#...O#OO..#.O.O.#.#O#O.O.......#.#O.#. ..O...#......#.....#.#.....#...........O..O..##..#.....#.O#.......O.##.....O.OO..#..O..#..........#. .#.O...O#O#...OOO............OOO...#O#...#.....#OO.#.O..#OO.##.OOO..#O...#O#...O.O..##.#..O.O#O...O. ....O...O#OO..O..O.#.....###....O#..#OO...##.#O.#.#.O.O...OO.O....#..O..O..OOO.#......O...##OOO.O... .OOO.....#.O..#..O.O..O..#O..#O#O.#..#.O.........O......#.#......O..#O.........OO#O..OOO......O#.O.. O.O.#O.....O.O..##......O#....O#.O..##.....O.#..###O.O...#O.....##..#O..#O.O.#.O.OO#....O...OO#....O .O#O..#...O.#...O......#.....O......OO...O.#...#..#.O.#..O.#...#.......#.#....O#..OO..O#O...O..O..#. .#..#...#.OOOO..#.#.O...O##O##....O..##..OO..#OO#..##.OO#.....#............O..#O....OO.#..#......#O. .....O......O..........O#...O...#.O#O...O.#...O.......O#..OOOO......O..O..#.#....O....#.O..O.###.#.O .#OO.O#..O.O#...OO...##OO.O....O.O.##O.......O.#O...OO#O#...#.OO.#.O.O..OO.O.O.#...OOO..#...O.O#.#OO OO.#.##O..O#.O.#..O#O..#.O#.....O#..O......OOOOO#..O#.#......O.O..OO....##.##O.OO#O#.#.#......O..... .O.....O.O.#....OO.O..#..O##.#.....#.#......#..O...O.#..#..O#.O..O..##....##.O..#O....#...O#..O.#... ....OO#OO..#..O..O..O#.##O.OO.O.OO.##...#..#..O........#.O......O.#OO#...........#...O#O##.......O.. #.#O........O...##..........#.###.OO#O.O#.....O#.....#.OO.#..OO..#..O...O...O..OO.OO..#OO..O..##.OO. ..#...O.....O.OO#OO##....#O#..#O...O#.....#O.O.O.......#...O..O.O#.O.....#O..OO#...O...O.OO.O.O....# OO.#O..O..OOO.....O.....OOO.#........O........OO..##OOO...#.OOO..OO....#..#..........O...#..#.O#.#O. #.#O##.O#.#O#.#.OO...O.#O.......O...#O......#.#..O##......#.....O.....O##..#...#.....#..O...O......O O.......#...O...O.#O#.O...#..O..#.OO...OO.O.#.#........#OO.#..OOO#...#O#O......O.....##.O.#..O..#.#. .#O....O...#OO..O........OO.#O...#...#O#O.O#.#...O....O.....##.#.#..#.#....##.#....#........#O...#.# .......O........#.##.........#.O#.O.....OO..O..#.OO.##.O....#..O..OO.#O#.#....O......O..O#OO........ ..#.O...#.....OO.O.......#...O...O##O..OO.....O.O.#.#....#....O....#O....#..#O.OO..O.#O......O...O.. .......O#.O.#O....OO##.......#.....##..O.OOO...O...OO#OO#.O#....#.#.O..#O.....OO..#..OOO....O#...O#O ......#.O##....O..O...O#...O#.O....O.#O#O#.O..#.O......O#......O.#O.#..#.O.......OO.#.#.O#.OO......# ..#.OOOO.#...#O#......#...#OOO.....O..#...O.......#.#O.O...#.O#..O..O....##...........O....O#.O#.O.. ...#.#...####.#O.......O.#O....OO..O.#....OOO.....#.O..OO.#O#.O.O##O#...OO....O.O..#.OO..........##. O.O#..........O#.........OO.....#.O....OOO.O...#.....#O....#..O.#....O#OOOO.#...#.#O.O#.OOO..OO#.O.. O......O.#....O#O..OOO##..........#OO.........#..O..O.....O..#O...##.OO.O.O........O.O...OOO......O. #.....O........#OO.###O..O....#OO.##O#OO.....OO.#O.......#.......#..O..O.........#...O....#.#...O.O. .#O....O##.O#....O.#.#..O#.#..........#........#..#O.#O...O.OOO.OO..##.#....OO.O..O#..O.#.#.......O. ...O.O....O##OO#..#..#.....O..#..OO..##.O.#.............O.......#.O.........OOO#.#...OO##...#.#..... OO.O..O......O...#.O#..##O...O.....#.##.....O##........#.OO#.O..O.....O#.......##.O.OO.O##.O........ .O#..OO.#O...O...#..O.O.O..##........OO.O.....O.O#.#..OO.O...O.OO..O.O#OO..O..O.......O......OOOO... ..O....#..O..OO.#.##O......#.#.........OO.....O....#..O.OO...OO.#O.#O....#........O....#O#...O#O.#.# ....O...O.OOO.O...OOO....O.#....##.OO....O.O.##............O..#..OO....O....#......#....OO...O#OO..O .O.OO.....##.OOOO.#O#.......OOOO.O..#.....#O#O.........##OO.#.....O.O.#..##.O#..#O....#..O#...O..#.. #....##O#.O#......O...OO.....O..O....##.O##.....O##O..OO..##O.###......#....#.#O....###.......#..... ...##..O.O.#...OOO...OO#.O....OOOO....O....#O..###.#....O..OO....#.....O#O#.O.....O.....O..#..#O..## ...OO.O...O.O..O..#.#OO..O#..OOO....#.O..#O#.###..O##..#.#..#....O....OOOO....#O.#.....O#O.....##... .........#...O..O#.O#..#..OO..O..#...#......#..OO..O..O.O..OO.O.....O.................O...O#.#O..... #.##...O.......#.#O#.....##O#.#..O.O.......#..O......O..O#.OOO#..O..OO#...O.O..O.#O.#.....##..OOOO.# .O...O...###..OOOO.#.##.O.#..#O#.O.#O.#.O#O#......#.O.#OO.##.....O...O#.O##.#..#...OO..O...O..##...O ..##......O.#OO......#.O...#.......O##.........#.O.#....O...O....#O...O#O#.OO#.O...OO..O#....O.OO..O .........#...#.O..#.#........##.O.....O.#...##.#.#.O##...##..OO...#.........#..O.....O...O....#.O... .O.OO.#..O.OO..OO..O........O#.#O..O..O...#O.##.......#..#.....#O#..O....O.OOOOO#...O..#......O..... ...O..O....#O...O......#.OOO.#.#......O##O#..##O..OO#O.....O..#.#...O.O##O.OO.OO...........O..###... ....#.O..#..O#O.....#.OO.....##O....O#....#...O..OO.O...##..O.#O...OO.#..OO.#O.O.O..OOOO......O..O#. O.#.....#...O#O..O##....#......#.O.O.....O#....#........##.O...O...O..#.....#O....O..O....#.#...#... ....O...O...O.OO.O##......#.......O.#....#.....#O.O...O#O.####.##..........#.#OO...........#.O.O#... #.......#...O#.O..#O...#..#.#..O..###.OO.#..O.#..#..O#....###O...O..#..#......#O#.OO#.....#O#....... .....#..#..O#.#.#O.....O..O...O.O#....OO......#O#..#O....#.#O#....O##.O.....#O...........O...O.O.#.. .#OO##.......O....OO.OO.....O.O.....OO.........#.#O.O.O.O.OO......#O...#O#.....OO.OO.O.O.#..#..#..#. .O...OOO#O..O.##.....#.#O#O.O.#O.....#.OO#.O...#O....OO..#...OO#.O.....O...O....O..O#...##.OO##..O.O #.#.#...O........O##.#....#.....#..........O.#...O.....##O....#...OO..##......#...OO.O#OO......O.O.. ......#...O..##...O........O#.......#.......OO.##..#...#..#.....#...O#.#O........O#.O............... ...O..O....OOO...#.......O..OOO##.O.O#....#O..O.#O#...O.#.O..O.O#O..#...O..O.O.OO.O.#..#O..#O#..#..# O.O..O#..O...O...O.O....##..OO#..O#.#OO##...OO..#OO....#..#..O.........O..O....#.#...OO#.#..O....O#. .#.##.#..O.O#....#....#O..#O.O....O...#.#.OO..O.OO..#.#O..OOOO#..O..##O.#..O##O..O......#.O..O..O..O O#OO..O.....O...O...#...#...#.....O...#.O...#.#O...O..O.###......#O.........#O..........O..OOO..O.O. ..#.#.O.....O....#....O..#.OO......O#.....O....O#.#.#...#O.O#OO..........#..#.O....O........O..O..O# ..#........##O#O.#....#O.O....OOO..#.O.....#OO.O...#....O#...##O#.O...O.#OO#.O.OO#..OO.....OO..#O... ...OO.#O#.#O.......OO#.O..O..OO...O..##O.#O.......#...#.O..O##O...O..O#.#....OO.###...#..O#...O..O.. .O#O#....#.....###..#.#..#...#O...#..O#.....##.OO.....OO...O....#O.O........##...O.....OO#O.....#... #.....OOO..#....O.O..........#.......O...#....O.O...O........O...#O##.O.O#OO....#.#..O.O.##........O O..OO...#OO.#O........#...O#OO#..O....#......OOO..OOO#...OO.O....##..#...O#...#.#..#O..O...##..##.#. OO..#O#..O...#......#.#.#O#.....#..OO......OO#.OO..#.....O...O#....#O..O...#O...#.OO.##.###.....O..O .#.O......#...OO##.#.......O...O.......O#..O#...#..O#..O#O#..O.#O..OO.O..O.#..O..O#......O....O..... #..#O#O.#.O...O...#...#.#.#.#O....O.O..#O........O#..#.#...O.O.##.....O.O.O....OO..OO.....##.#O..O.. ...#......O#...#..O#O.O...#..OOO....#O#...#.....#..O#....#O......#.O..O.#O.......O#..O.#......O.O... ..O.....O...O.....O#...#..#OO..##O.O.........OO...##.O.#..#.##O.O.O#..O#.#.#OO#......O#..#.#.O#O#.O. ##..OO.O..##O..O...O.O.....#.O#.O.OO....#..##O.O.##.O.#....#......O........##.....OOO.O.#.###....O#O ..OO..O.OO..#..O....O..O.###.#..#..#..#......OO#O#..#.#.#.OO#.#...O.....#..O#...............#....O.. .#O.O..#...#.#OO..O.........O.##.#.....OOO.O.O.......OO##.##.OO.#......OO..O.O...#.....O...#O.#.O.O. .O.O#O...O.O#O.O..O.O.O.O..O.O.O...O.#.#....#....#..O.#O.#........#.#...O.......#...O..O...O..#O...O ..O...O.O...O.#..........#O.O..........#......O...#OO..O..O##..O......O...#.O...O..#......OO..O....O ..#........#..O..O..#...#O...O.O...##....O..#O.#.#.#......O#.O....##O...O.OO.#...O.OOO.#..OOO...O... ..OO..O#...O..O#O..O.##...#.O.#O###.O#...O.###...O....O...#...#..#.#....#...O..O....O...####O.#OOO.O .O....#.#O#.O.#.#.........O#.#..#.O.....O####.O.OO.O.O#O..O......O.#.OO.O.......OOO..#........OO..#O #O....#...O..O.#..O.O#.O..OO#OO.O#..#.#....#.O...#..#O#.O.O.O...O#.O#...#O..O..O..O.O...#.#.#O....O# #.....##...O.O..OO..O#.....O...........#.....#O#O......O..OO.....##..#...#O..#.O.........O.....O.... #...#.#O#O..O...OO.O.O.O..#O..##..O..OO.....#OO.#.#....#.....O.#....#....#...#O....O.#.##..#O.O..#.. O.##....O..O.#.OO.....#..OO#..#.OO.....#O..OOO#.......#.#....O....#.....OO....#.OO.....#.#..O...O.#. ..O...O#..O..#...OO.......#O.O.OO..OO.O...O.O.O.#..#OOO.#.....O....O..OO........#.....O.O#.O.O##.... ....O..#.#O...#.O....#O.OO.#..#.O...##..#......#OO..#....#....#.O..#OO#.#...O..O..O#.O.O#...O##...OO .O.O....#...O#.O.......#.O........#..OO.#O...O##O......#.O.OOO......#OO.O.O..O###..#.O..OO.O.O.O.... O.......#..O#......O.O#..O...O..O..O..O#..##....................O.#...........##....#..##.#...#O.### ..O...O.......O....O..OO..O.#......#.......O#O.....#..##..O.O#.....O...O.#OO....O.#.O.O.#O.#..OO..O# #OOO....O.....O..O.O.....OO.OOO..#O.O..O..#O.#.....#.O...OO.O.......#..#O...O.....O.#...O#...O...OO. O.#..O..OO.OO#O....#.O.......O....O....#..O...O.....OOOOO#.#...O#.#O.O..OO#O.O.......#.....O...O.OO. .O#O.O....O.#OO##......O.......O#.#..##...O......#.#........#O..#.##..#.O.....#..OO..#..#.O.#.O...#O .OO....#..O..O#.O.#O.........O.....#OOO............OOO..#.....#...#.O..##.OO....##...O#O....OO#.#.O# ...O.##.....###......O#...O.......#.#...#.......O.....###..OOO...O.O..O..O#.O....#O....#.#.......O.# OO#....##..O.#......#OO..#....#.#.O.........#.OOO....OO.###....O#.#..#O.O.O..#...OO#.OO#.....O#O#..."""; }
thomas-raneland/aoc2023
Day14.java
248,003
public class Measure { String label; long start; public Measure(String label) { System.out.println("START\t" + label); this.label = label; this.start = System.currentTimeMillis(); } public void finish() { long end = System.currentTimeMillis(); System.out.println("END\t" + label + " = " + (end - start) + "ms"); } }
TilBlechschmidt/ucd-adahackathon
Measure.java
248,004
/* * Copyright © 1996-2009 Bart Massey * ALL RIGHTS RESERVED * [This program is licensed under the "MIT License"] * Please see the file COPYING in the source * distribution of this software for license terms. */ import java.awt.*; public class Table extends Panel implements LayoutManager { private static final int COL_LEFT = 1; private static final int COL_CENTER = 2; private static final int COL_RIGHT = 3; private static final int COL_FILL = 4; private boolean box = false; private boolean box_rows = false; private int cols[]; private int ncols; private int separators[]; private int hsizes[]; private int vsizes[]; private boolean stretches[]; private int nrows; private Component comp[] = null; public Table(String spec) { super(); table_layout(spec); setLayout(this); } private void table_layout(String spec) { ncols = 0; for (int i = 0; i < spec.length(); i++) switch(spec.charAt(i)) { case 'l': case 'r': case 'c': case 'f': ncols++; break; case '|': case '*': break; default: throw new IllegalArgumentException("Bad table specification char"); } cols = new int[ncols]; separators = new int[ncols - 1]; for (int i = 0; i < ncols - 1; i++) separators[i] = 0; stretches = new boolean[ncols]; for (int i = 0; i < ncols; i++) stretches[i] = false; boolean stretchable = false; int curcol = 0; for (int i = 0; i < spec.length(); i++) switch (spec.charAt(i)) { case 'l': cols[curcol++] = COL_LEFT; stretchable = true; break; case 'r': cols[curcol++] = COL_RIGHT; stretchable = true; break; case 'c': cols[curcol++] = COL_CENTER; stretchable = true; break; case 'f': cols[curcol++] = COL_FILL; stretchable = true; break; case '*': if (!stretchable) throw new IllegalArgumentException("Unexpected table stretch"); stretches[curcol - 1] = true; stretchable = false; break; case '|': if (curcol < 1 || curcol >= ncols || separators[curcol - 1] >= 2) throw new IllegalArgumentException("Bad table separator specification"); separators[curcol - 1]++; stretchable = false; break; default: throw new IllegalArgumentException("Unusual table specification error"); } if (ncols == 0) throw new IllegalArgumentException("Empty table specification"); } public void setBox(boolean box) { this.box = box; } public void setBoxRows(boolean box_rows) { this.box_rows = box_rows; } private void set_minimums(Component comp[]) { for (int i = 0; i < ncols; i++) { hsizes[i] = 0; vsizes[i] = 0; } for (int i = 0; i < comp.length; i++) { int x = i % ncols; int y = i / ncols; Dimension dm = comp[i].minimumSize(); if (dm.width > hsizes[x]) hsizes[x] = dm.width; if (dm.height > vsizes[y]) vsizes[y] = dm.height; } } private void set_preferreds(Component comp[]) { for (int i = 0; i < ncols; i++) hsizes[i] = 0; for (int i = 0; i < nrows; i++) vsizes[i] = 0; for (int i = 0; i < comp.length; i++) { int x = i % ncols; int y = i / ncols; Dimension dm = comp[i].preferredSize(); if (dm.width > hsizes[x]) hsizes[x] = dm.width; if (dm.height > vsizes[y]) vsizes[y] = dm.height; } } private Dimension csizes() { Dimension result = new Dimension(0, 0); for (int i = 0; i < ncols; i++) result.width += hsizes[i]; for (int i = 0; i < nrows; i++) result.height += vsizes[i]; for (int i = 0; i < ncols - 1; i++) if (separators[i] > 0) result.width += 1 + 2 * separators[i]; if (box) { result.height += 4; result.width += 4; } if (box_rows) result.height += 3 * (nrows - 1); return result; } private void set_slack(Dimension current, Dimension target) { Dimension raw = new Dimension(0, 0); for (int i = 0; i < ncols; i++) if (stretches[i]) raw.width += hsizes[i]; for (int i = 0; i < nrows; i++) raw.height += vsizes[i]; if (current.width < target.width) { int hslack = target.width - current.width; for (int i = 0; i < ncols; i++) if (stretches[i]) hsizes[i] += hslack * hsizes[i] / raw.width; } if (current.height < target.height) { int vslack = target.height - current.height; for (int i = 0; i < nrows; i++) vsizes[i] += vslack * vsizes[i] / raw.height; } } private void setup_measure(Container c) { comp = c.getComponents(); nrows = 1 + (comp.length - 1) / ncols; hsizes = new int[ncols]; vsizes = new int[nrows]; } private void measure(Container c) { setup_measure(c); set_preferreds(comp); Dimension dc = c.size(); Insets insets = c.insets(); dc.width -= insets.left + insets.right; dc.height -= insets.top + insets.bottom; Dimension ds = csizes(); if (ds.width < dc.width && ds.height < dc.height) { set_slack(ds, dc); return; } set_minimums(comp); Dimension dsx = csizes(); set_slack(dsx, dc); } public void paint(Graphics g) { super.paint(g); measure(this); Dimension ls = csizes(); Dimension cs = size(); Insets insets = insets(); cs.width -= insets.left + insets.right; cs.height -= insets.top + insets.bottom; int xpos = insets.left; if (cs.width > ls.width) xpos += (cs.width - ls.width) / 2; int ypos = insets.top; if (cs.height > ls.height) ypos += (cs.height - ls.height) / 2; if (box) g.drawRect(xpos, ypos, ls.width - 1, ls.height - 1); if (box_rows) { int ybase = ypos; if (box) ybase += 2; for (int i = 0; i < nrows; i++) { ybase += vsizes[i]; g.drawLine(xpos, ybase + 1, xpos + ls.width - 1, ybase + 1); ybase += 3; } } int xbase = xpos; if (box) xbase += 2; for (int i = 0; i < ncols - 1; i++) { xbase += hsizes[i]; switch (separators[i]) { case 2: g.drawLine(xbase + 1, ypos, xbase + 1, ypos + ls.height - 1); xbase += 2; case 1: g.drawLine(xbase + 1, ypos, xbase + 1, ypos + ls.height - 1); xbase += 3; } } } public Dimension minimumLayoutSize(Container c) { setup_measure(c); set_minimums(comp); Dimension dc = csizes(); Insets insets = c.insets(); dc.width += insets.left + insets.right; dc.height += insets.top + insets.bottom; return dc; } public Dimension preferredLayoutSize(Container c) { setup_measure(c); set_preferreds(comp); Dimension dc = csizes(); Insets insets = c.insets(); dc.width += insets.left + insets.right; dc.height += insets.top + insets.bottom; return dc; } public void layoutContainer(Container c) { measure(c); Dimension ls = csizes(); Dimension cs = c.size(); Insets insets = c.insets(); cs.width -= insets.left + insets.right; cs.height -= insets.top + insets.bottom; int ypos = insets.top; if (cs.height > ls.height) ypos += (cs.height - ls.height) / 2; if (box) ypos += 2; int voffsets[] = new int[nrows]; for (int i = 0; i < nrows; i++) { voffsets[i] = ypos; ypos += vsizes[i]; if (box_rows) ypos += 3; } int xpos = insets.left; if (cs.width > ls.width) xpos += (cs.width - ls.width) / 2; if (box) xpos += 2; int hoffsets[] = new int[ncols]; for (int i = 0; i < ncols; i++) { hoffsets[i] = xpos; xpos += hsizes[i]; if (i < ncols - 1) switch (separators[i]) { case 2: xpos += 2; case 1: xpos += 3; } } for (int i = 0; i < comp.length; i++) if (comp[i].isVisible()) { Dimension ps = comp[i].preferredSize(); int x = i % ncols; int y = i / ncols; int ho = hoffsets[x]; int hs = hsizes[x]; switch(cols[x]) { case COL_FILL: break; case COL_CENTER: if (hs > ps.width) { ho += (hs - ps.width) / 2; hs = ps.width; } break; case COL_RIGHT: if (hs > ps.width) { ho += hs - ps.width; hs = ps.width; } break; case COL_LEFT: if (hs > ps.width) hs = ps.width; break; } comp[i].reshape(ho, voffsets[y], hs, vsizes[y]); } } public void addLayoutComponent(String s, Component c) { } public void removeLayoutComponent(Component c) { } }
BartMassey/java-yacht
Table.java
248,006
import java.io.*; public class Measure{ private double[][] densities; public Measure(){ densities = new double[30][20]; /* this checks for existing data file, if not then set values for densities*/ if(checkForData()){ for(int r = 0; r < densities.length; r++){ for(int c = 0; c < densities[r].length; c++){ //double material = possible[(int)(Math.random()*possible.length)]; double max = 3.0; double min = 0.0; double material = Math.random()*(max-min+1)+min; densities[r][c] = material; } } writeToFile(); // create and write densities values to file readFromFile(); // reads from file into densities in column-major order } else{ readFromFile(); // reads from file into densities in column-major order } } public double getMaterial(int r, int c){ if((r >= 0 && r <= 29) && (c >= 0 && c <= 19)){ return densities[r][c]; } else{ System.out.println("WARNING! That is not inside the grid."); } return -1; } // not used private boolean checkBoundary(double material, int r, int c){ if(material > 0.5 && material < 0.6){ for(int j = r - 1; j < r + 2; j++){ for(int k = c - 1; k < c + 2; k++){ if(j >= 0 && k >= 0 && j < densities.length && k < densities[0].length){ if(densities[j][k] >= 0.9 && densities[j][k] <= 1.2){ return false; } } } } } return true; } private void writeToFile(){ try{ FileWriter fw = new FileWriter("data.txt"); BufferedWriter bw = new BufferedWriter(fw); for(int r = 0; r < densities.length; r++){ for(int c = 0; c < densities[0].length; c++){ String data = "" + densities[r][c]; bw.write(data); bw.newLine(); } } bw.close(); fw.close(); }catch(IOException e1){} } private boolean checkForData(){ String line = ""; try{ FileReader fr = new FileReader("data.txt"); BufferedReader br = new BufferedReader(fr); line = br.readLine(); br.close(); fr.close(); }catch(IOException e2){} return line == null || line.length() < 1; } /* reads from data file and puts values in densities in column-major order */ private void readFromFile(){ try{ FileReader fr = new FileReader("data.txt"); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); int r = 0; int c = 0; while(line != null){ densities[r][c] = Double.parseDouble(line); r++; if(r == densities.length){ r = 0; c++; } line = br.readLine(); } br.close(); fr.close(); }catch(IOException e2){} } }
bcwlkr/resource-finder
Measure.java
248,007
// CLAIRE WANG // CS Final Project import org.jfugue.player.*; import java.awt.Color; import java.awt.Font; import java.util.*; import java.io.*; import javax.swing.*; import java.awt.event.*; import org.jfugue.midi.MidiFileManager; import org.jfugue.pattern.*; import java.lang.String; // named App because that's the default name and I don't want to mess it up! public class App { static Player player = new Player(); static JFrame f = new JFrame(); static int keyboardSize = 20; //default public static int measure = 4; // key signature // set up an arrayList of notes, it's the music score public static ArrayList<Note> score = new ArrayList<>(20); public static void scoreAdd(String letter, int octave) { // add a note to the score score.add(new Note(letter, octave, 3)); } public static void toMIDI(ArrayList<Note> arr) { // export the score to a midi file, readable by jFugue // converting to mp3 is much more complicated String pattern = ""; for (Note key : arr) { pattern.concat(key.getLetter() + key.getOctave() + " "); } Pattern notes = new Pattern(pattern); try { MidiFileManager.savePatternToMidi(notes, new File("src/assets/fugue-score.mid")); } catch (IOException ex) { } } public static void toFile(ArrayList<Note> arr, int measure) { // this prints the score into a file try { FileWriter writer = new FileWriter("score.txt"); // these separate it into measures and lines int rowC = 0; int counter = 0; for (Note key : arr) { counter++; rowC++; writer.write(" " + key.toString() + " "); if (rowC >= measure) { writer.write(" | "); rowC = 0; } if (counter >= (measure * 3)) { writer.write(System.lineSeparator()); counter = 0; } } writer.close(); } catch (IOException ioException) { // not very applicable, but required ioException.fillInStackTrace(); } } public static void displayScore(int measure) { // this displays the score in the console -> not that needed since we have print to .txt file System.out.println("Time Signature: " + measure + "/4"); int rowCounter = 0; int lineCount = 0; for (Note note : score) { rowCounter++; lineCount++; System.out.print(" " + note.toString() + " "); if (lineCount > (measure * 3)) { System.out.println(); lineCount = 0; } else if (rowCounter > measure) { System.out.print("|"); rowCounter = 0; } } } public static Pattern loadMIDI(String filename) { try { // final Player player = new Player(); final Pattern pattern = MidiFileManager.loadPatternFromMidi(new File("src/assets/" + filename)); return pattern; } catch (final Exception e) { e.printStackTrace(); return new Pattern("C"); } } public static boolean render(int numKeys) { String[] letters = new String[]{"C", "D", "E", "F", "G", "A", "B"}; // start on C because starting on A loops around int letterIndex = 0; int xPos = 20; int yPos = 100; int octave = 3; int rowCounter = 0; for (int i = 0; i < numKeys; i++) { rowCounter++; JButton b = new JButton(letters[letterIndex] + octave); b.setBounds(xPos, yPos, 40, 100); b.setBackground(Color.WHITE); b.setOpaque(true); f.add(b); final int letI = letterIndex; final int play = octave; b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { player.play(letters[letI] + play); scoreAdd(letters[letI], play); } }); // makes sure that it doesn't overflow to hidden depths letterIndex++; if (letterIndex == letters.length) { // goes up an octave octave++; letterIndex = 0; } xPos += 50; if (rowCounter > 10) { yPos += 130; xPos = 20; rowCounter = 0; } } return true; } public static void main(String[] args) { f.setLayout(null); // self-layout, don't need layout manager f.setSize(700, 400); // allows resizing, hopefully not too big of a keyboard // keys are 40 by 100 // 10 keys per row f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // generator button and exit Color altGreen = new Color(92, 219, 149); JButton display = new JButton("Exit", new ImageIcon("src/assets/docs.png")); display.setBounds(20, 20, 100, 40); display.setBorderPainted(false); display.setBackground(altGreen); display.setFont(new java.awt.Font("SansSerif", Font.BOLD, 18)); display.setForeground(new Color(250, 55, 121)); display.setOpaque(true); display.setVisible(true); Scanner input = new Scanner(System.in); display.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayScore(measure); toFile(score, measure); toMIDI(score); // remember to check the terminal after you're done! System.out.println("Playback? (y/n):"); char playback = input.next().charAt(0); if (playback == 'y' || playback == 'Y') { // a bit buggy because jFugue is slow player.play(loadMIDI("fugue-score.mid")); } input.close(); System.exit(0); } }); f.add(display); render(keyboardSize); f.setVisible(true); } }
ClaireBookworm/fuguedState
src/App.java
248,009
public class square extends rectangle { // method specific to our square shape public double measure; public square(double measure) { super(measure, measure); } public int getSides() { sides = 4; return sides; } }
kaneclev/CS219
square.java
248,014
package com.example.hp.sunshine; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.VectorDrawable; import android.os.Build; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.RelativeLayout; /** * Created by hp on 9/22/2016. */ public class Compass extends View { float angle; int bitmap_width; int bitmap_height; Path path = new Path(); Path trianglePath = new Path(); Paint arrow_brush = new Paint(Paint.ANTI_ALIAS_FLAG); Paint triangle_fill = new Paint(Paint.ANTI_ALIAS_FLAG); public Compass(Context context) { super(context); setWillNotDraw(false); this.bitmap_width = getPxFromDP(22); this.bitmap_height = getPxFromDP(22); angle = 0; this.setRotation(angle); definePath(11,11,1f); arrow_brush.setStyle(Paint.Style.STROKE); trianglePath.setFillType(Path.FillType.EVEN_ODD); arrow_brush.setColor(getResources().getColor(R.color.sunshine_blue)); arrow_brush.setStrokeWidth(getPxFromDP(4)); triangle_fill.setStyle(Paint.Style.FILL); triangle_fill.setColor(getResources().getColor(R.color.sunshine_blue)); arrow_brush.setAntiAlias(true); arrow_brush.setFilterBitmap(true); triangle_fill.setAntiAlias(true); triangle_fill.setFilterBitmap(true); defineTriangle(11,11,1f); } public Compass(Context context, AttributeSet attrs) { super(context, attrs); setWillNotDraw(false); this.bitmap_width = getPxFromDP(22); this.bitmap_height = getPxFromDP(22); angle = 0; this.setRotation(angle); definePath(11,11,1f); trianglePath.setFillType(Path.FillType.EVEN_ODD); arrow_brush.setStyle(Paint.Style.STROKE); arrow_brush.setColor(getResources().getColor(R.color.sunshine_blue)); arrow_brush.setStrokeWidth(getPxFromDP(4)); triangle_fill.setStyle(Paint.Style.FILL); triangle_fill.setColor(getResources().getColor(R.color.sunshine_blue)); arrow_brush.setAntiAlias(true); arrow_brush.setFilterBitmap(true); triangle_fill.setAntiAlias(true); triangle_fill.setFilterBitmap(true); defineTriangle(11,11,1f); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // Measure Modes int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); // dimensions passed by parent int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); int widthToDraw; int heightToDraw; if(widthMode == MeasureSpec.EXACTLY){ widthToDraw = width; }else{ widthToDraw = bitmap_width; } if(heightMode == MeasureSpec.EXACTLY){ heightToDraw = height; }else{ heightToDraw = bitmap_height; } setMeasuredDimension(widthToDraw,heightToDraw); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawPath(path,arrow_brush); canvas.drawPath(trianglePath,triangle_fill); } public void setAngle(float angle){ this.angle = angle; this.setRotation(this.angle); this.invalidate(); this.requestLayout(); } public void setScale(float scale){ path = new Path(); trianglePath = new Path(); trianglePath.setFillType(Path.FillType.EVEN_ODD); this.defineTriangle(11,11,scale); this.definePath(11,11,scale); arrow_brush.setStrokeWidth(getPxFromDP(4f*scale)); this.invalidate(); this.requestLayout(); } void definePath(int x_dps, int y_dps, float scale){ path.moveTo(getPxFromDP(x_dps),getPxFromDP(y_dps+11f*scale)); path.lineTo(getPxFromDP(x_dps),getPxFromDP(y_dps-9f*scale)); } void defineTriangle(int x_dps, int y_dps, float scale){ trianglePath.moveTo(getPxFromDP(x_dps),getPxFromDP(y_dps-11f*scale)); trianglePath.lineTo(getPxFromDP(x_dps-9f*scale),getPxFromDP(y_dps-3f*scale)); //trianglePath.moveTo(getPxFromDP(x_dps-7f*scale),getPxFromDP(y_dps-5.5f*scale)); trianglePath.lineTo(getPxFromDP(x_dps),getPxFromDP(y_dps-5f*scale)); //trianglePath.moveTo(getPxFromDP(x_dps),getPxFromDP(y_dps-7f*scale)); trianglePath.lineTo(getPxFromDP(x_dps+9f*scale),getPxFromDP(y_dps-3f*scale)); //trianglePath.moveTo(getPxFromDP(x_dps+7f*scale),getPxFromDP(y_dps-5.5f*scale)); trianglePath.lineTo(getPxFromDP(x_dps),getPxFromDP(y_dps-11f*scale)); trianglePath.moveTo(getPxFromDP(x_dps),getPxFromDP(y_dps-11f*scale)); trianglePath.close(); } void scaleBrushWidth(float scale){ arrow_brush.setStrokeWidth(getPxFromDP(4*scale)); } int getPxFromDP(float dps){ return (int) (dps* getResources().getDisplayMetrics().density); } }
muddassir235/CompassView-Android
Compass.java
248,017
package pack; public class Global{ public static final int ARRIVAL = 1, READY = 2, MEASURE = 3; public static double time = 0; }
Juhnke057/EITG01
Global.java
248,019
// AUTHOR: danpost // Version: 2 // Last modified: February, 8, 2012 import greenfoot.*; import java.awt.Font; /** * Class Bar: for use as a health bar or progress bar as well as for other types of measurements for visual of value in a bar form * DO NOT EDIT THIS CLASS as everything can be controlled through method calls. */ public class Bar extends Actor { private int barWidth = 100; // the width of the color portion of the bar private int barHeight = 10; // the height of the color portion of the bar private int breakPercent = 20; // the percentage amount that changes the color of the bar private int breakValue = 20; // in tandem with breakPercent private boolean usingBreakValue = false; private boolean breakLow = true; // when true, with low-percent values bar is dangerColor, else safeColor; reversed when false private Color backgroundColor = new Color(0, 0, 0, 0); // the background color of the entire object private Color textColor = Color.BLACK; // the color of all text and the frame of the bar itself private Color safeColor = Color.GREEN; // the color of the bar while in the safe range private Color dangerColor = Color.RED; // the color of the bar while in the danger range // The color of the bar AT the breakpoint will be the average color between the safe color and the danger color private float fontSize = 18.0f; // the size of the text private int value = 0; // the current value of the bar private int maximumValue = 0; // the maximum value of the bar private int minimumValue = 0; // the minimum value of the bar private String referenceText = ""; // the title string (who or what the meter/bar is for) private String unitOfMeasure = ""; // the unit of measure of the bar (any quantitative standard of measurement) private boolean showTextualUnits = true; // determines whether or not the textual quantity of the bar is to show /** * Bar Constructor: saves the initial values that are brought in and creates the bar image through the 'add(int)' call, * which sets the initial value of the bar and calls the 'newImage' method to build and set a new image for the bar. * * @param 'refText': a text string to specify what the bar is for (be specific enough so that all bars can be distinguished one from another) * @param 'unitType': a text string to specify what measure is being used in the bar ("percentage", "points", "frames per second", or whatever) * @param 'initValue': the value the bar should be initially set to * @param 'maxValue': the highest value the bar is allowed to hold */ public Bar(String refText, String unitType, int initValue, int maxValue) { referenceText = refText; unitOfMeasure = unitType; maximumValue = maxValue; add(initValue); } /** * Method 'newImage': builds a new image for the bar, determined by the values set for it */ private void newImage() { int barValue = (int) (barWidth * (value - minimumValue) / (maximumValue - minimumValue)); GreenfootImage leftImg = new GreenfootImage(referenceText + " ", (int) fontSize, textColor, backgroundColor); GreenfootImage rightImg = (showTextualUnits) ? new GreenfootImage(" " + value + " " + unitOfMeasure, (int) fontSize, textColor, backgroundColor) : new GreenfootImage(1, 1); int maxX = (leftImg.getWidth() > rightImg.getWidth()) ? leftImg.getWidth() : rightImg.getWidth(); GreenfootImage barImg = new GreenfootImage(barWidth + 4, barHeight + 4); barImg.setColor(backgroundColor); barImg.fill(); barImg.setColor(textColor); barImg.drawRect(0, 0, barImg.getWidth() - 1, barImg.getHeight() - 1); if (value > minimumValue) { if (breakLow) { if (value > (usingBreakValue ? breakValue : (int) (breakPercent * (maximumValue - minimumValue) / 100 + minimumValue))) barImg.setColor(safeColor); else barImg.setColor(dangerColor); } else { if (value < (usingBreakValue ? breakValue : (int) (breakPercent * (maximumValue - minimumValue) / 100 + minimumValue))) barImg.setColor(safeColor); else barImg.setColor(dangerColor); } if (value == (usingBreakValue ? breakValue : (int) (breakPercent * (maximumValue - minimumValue) / 100 + minimumValue))) { int r = (int) ((safeColor.getRed() + dangerColor.getRed()) / 2); int g = (int) ((safeColor.getGreen() + dangerColor.getGreen()) / 2); int b = (int) ((safeColor.getBlue() + dangerColor.getBlue()) / 2); barImg.setColor(new Color(r, g, b)); } barImg.fillRect(2, 2, barValue, barHeight); } int sumX = 2 * maxX + barImg.getWidth(); int maxY = 0; if (leftImg.getHeight() > maxY) maxY = leftImg.getHeight(); if (barImg.getHeight() > maxY) maxY = barImg.getHeight(); if (rightImg.getHeight() > maxY) maxY = rightImg.getHeight(); GreenfootImage image = new GreenfootImage(sumX, maxY); image.setColor(backgroundColor); image.fill(); image.drawImage(leftImg, maxX - leftImg.getWidth(), (image.getHeight() - leftImg.getHeight()) / 2); image.drawImage(barImg, maxX, (image.getHeight() - barImg.getHeight()) / 2); image.drawImage(rightImg, maxX + barImg.getWidth(), (image.getHeight() - rightImg.getHeight()) / 2); setImage(image); } /** * Method 'add': add an amount to the value of the bar, checks to make sure the new value is between minimumValue and maximumValue, * then, calls 'newImage' to build and set the new image for the bar. * * @param 'amount': the amount to add (if not negative) or subtract (if negative) to the current value of the bar */ public void add(int amount) { value += amount; checkValue(); newImage(); } /** * Method 'subtract': subtracts an amount from the value of the bar, checks to make sure the new value does not overstep its bounds, * then, calls 'newImage' to build and set the new image for the bar. * * @param 'amount': the amount to subtract (if positive) or add (if negative) to the current value of the bar */ public void subtract(int amount) { value -= amount; checkValue(); newImage(); } /** * Method 'checkValue': ensures that the new value in between the minimum value and the maximum value for the bar */ private void checkValue() { if (value < minimumValue) value = minimumValue; if (value > maximumValue) value = maximumValue; } /** * Method 'getValue': returns the current value of the bar * * @return: the current value of the bar */ public int getValue() { return value; } /** * Method 'getBarWidth': returns the current width of the bar (color portion only) * * @return: the current width of the bar */ public int getBarWidth() { return barWidth; } /** * Method 'getBarHeight': returns the current height of the bar (color portion only) * * @return: the current height of the bar */ public int getBarHeight() { return barHeight; } /** * Method 'getBreakPercent': returns the range percent at which the color of the bar changes between lower values and higher values * (the variable 'usingBreakValue' must be 'false' for percent breaking is to be active; using 'setBreakPercent' will automatically * set 'usingBreakValue' to 'false'. * * @return: the percent value that determines where the color of the bar will change */ public int getBreakPercent() { return breakPercent; } // use boolean getUsingBreakValue() method before calling (if false) /** * Method 'getBreakValue': returns the current value at which the color of the bar will change * (the variable 'usingBreakValue' must be 'true' for value breaking is to be active; using 'setBreakValue' will automatically * set 'usingBreakVaule' to 'true'. * * @return: the value where the color of the bar will change */ public int getBreakValue() { return breakValue; } // use boolean getUsingBreakValue() method before calling (if true) /** * Method 'getBreakLow': returns the boolean value that determines if the danger color is used at the low end or the high end of the range * (setting it to 'minimumValue' or 'maximumValue' will essentially deactivate breaking) * * @return: the break state (danger color for low values when true) of the bar */ public boolean getBreakLow() { return breakLow; } /** * Method 'getBackgroundColor': returns the current background color of the image for the bar * * @return: the current color used for the background of the bar image (behind the bar and the text, alike) */ public Color getBackgroundColor() { return backgroundColor; } /** * Method 'getTextColor': returns the current text and frame color * * @return: the current color used for the text and the frame of the bar */ public Color getTextColor() { return textColor; } /** * Method 'getSafeColor': returns the current color used for values above any break point, if 'breakLow' is 'true', else below * * @return: the current color of the color portion of the bar used for 'safe' values */ public Color getSafeColor() { return safeColor; } /** * Method 'getDangerColor': returns the current color used for values below any break point, if 'breakLow' is 'true' else above * * @return: the current color of the color portion of the bar used for 'danger' values */ public Color getDangerColor() { return dangerColor; } /** * Method 'getFontSize': returns the current font size for the text used in the bar image * * @return: the current font size for the text of the bar */ public float getFontSize() { return fontSize; } /** * Method 'getMaximumValue': returns the current maximum value of the bar * * @return: the current value set as the maximum value of the bar */ public int getMaximumValue() { return maximumValue; } /** * Method 'getMinimumValue': returns the current minimum value of the bar * * @return: the current value set as the minimum value of the bar */ public int getMinimumValue() { return minimumValue; } /** * Method 'getReferenceText': returns the string set as the title text of the bar * * @return: the current title text of the bar */ public String getReferenceText() { return referenceText; } /** * Method 'getUnitOfMeasure': returns the current string used to qualify the value of the bar * * @return: the current unit of measure for the value of the bar */ public String getUnitOfMeasure() { return unitOfMeasure; } /** * Method 'getShowTextualUnits': returns the current state of showing/hiding of the textual value and unit of measure of the bar * * @return: the current state of showing/hiding of the string representation of the value and unit of measure on the right side of the bar */ public boolean getShowTextualUnits() { return showTextualUnits; } /** * Method 'setValue': sets a new value for the bar, if in bounds * * @param 'val': the new value for the bar */ public void setValue(int val) { value = val; checkValue(); newImage(); } /** * Method 'setBarWidth': sets a new width for the color portion of the bar * * @param 'width': the new width for the color portion of the bar */ public void setBarWidth(int width) { if (width > 9) { barWidth = width; newImage(); } } /** * Method 'setBarHeight': sets a new height for the color portion of the bar * * @param 'height': the new height for the color portion of the bar */ public void setBarHeight(int height) { if (height > 1) { barHeight = height; newImage(); } } /** * Method 'setBreakPercent': sets a new percentage value where the bar changes colors between safe and danger values * (if set to zero or one hundred, the bar will stay a constant color) * 'usingBreakValue' will be automatically set to 'false' when this method is called * * @param 'percent': the new percentage in the range of allowable values in the bar at which the color of the bar changes between 'safeColor' and 'dangerColor' */ public void setBreakPercent(int percent) { if (percent >= 0 && percent <= 100) { breakPercent = percent; usingBreakValue = false; newImage(); } } /** * Method 'setBreakValue': sets a new value for where the color of the color portion of the bar will change between safe and danger values * (if set to minimumValue or maximumValue, the bar will stay a constant color) * 'usingBreakValue' will be automatically set to 'true' when this method is called * * @param 'brkVal': the new value where the color of the color portion of the bar will change between 'safeColor' and 'dangerColor' */ public void setBreakValue(int brkVal) { if (brkVal >= minimumValue && brkVal <= maximumValue) {breakValue = brkVal; usingBreakValue = true; newImage(); } } /** * Method setBreakLow: sets the direction of safe to danger values; true: danger values are low and safe values are high; false: danger values are high ... * * @param 'lowBreak': the new state of break direction to use with the bar */ public void setBreakLow(boolean lowBreak) { breakLow = lowBreak; newImage(); } /** * Method 'setBackgroundColor': sets a new color to use behind the text and bar of the image * * @param 'color': the new color to use for the background color of the bar image */ public void setBackgroundColor(Color color) { backgroundColor = color; newImage(); } /** * Method 'setTextColor': sets a new color for the text and frame of the bar image * * @param 'color': the new color for the text and frame of the bar image */ public void setTextColor(Color color) { textColor = color; newImage(); } /** * Method 'setSafeColor': sets a new color for the color portion of the bar for safe values * * @param 'color': the new color for safe values in the color portion of the bar */ public void setSafeColor(Color color) { safeColor = color; newImage(); } /** * Method 'setDangerColor': sets a new color for the color portion of the bar for danger values * * @param 'color': the new color for danger values in the color portion of the bar */ public void setDangerColor(Color color) { dangerColor = color; newImage(); } /** * Method 'setFontSize': sets the font size to use for all text in the bar image * * @param 'size': the new font size for text used in the bar */ public void setFontSize(float size) { if (size > 7) { fontSize = size; newImage(); } } /** * Method 'setMaximumValue': sets a new maximum for allowable values for the bar * * @param 'maxVal': the new maximum for the value of the bar */ public void setMaximumValue(int maxVal) { if (maxVal > minimumValue) { maximumValue = maxVal; newImage(); } } /** * Method 'setMinimumValue': sets a new minimum for allowable values for the bar * * @param 'minVal': the new minimum for the value of the bar */ public void setMinimumValue(int minVal) { if (minVal < maximumValue) { minimumValue = minVal; newImage(); } } /** * Method 'setReferenceText': sets new title text for the bar * * @param 'refText': the new title text (or reference text) for the bar */ public void setReferenceText(String refText) { referenceText = refText; newImage(); } /** * Method 'setUnitOfMeasure': sets new unit of measure text for the bar * * @param 'uom': the new unit of measure text for the bar */ public void setUnitOfMeasure(String uom) { unitOfMeasure = uom; newImage(); } /** * Method 'setShowTextualUnits': sets the state of showing/hiding of the textual value and unit of measure on the right side of the bar * * @param 'show': the new state of showing/hiding of value text for the bar */ public void setShowTextualUnits(boolean show) { showTextualUnits = show; newImage(); } }
nguyensjsu/sp19-202-cavka
war/Bar.java
248,022
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; public class Harness { public static void main(String[] args) { List<Solution> solutions = new ArrayList<>(); solutions.add(new AlecSolution()); solutions.add(new SortSolution()); for (Solution solution : solutions) { Harness harness = new Harness(solution, 10); harness.checkAllPermutations(); harness.printReport(); } for (Solution solution : solutions) { Harness harness = new Harness(solution, 100); harness.checkRandomPermutations(10_000); harness.printReport(); } } private final Solution solution; private final int arrayLength; private final int[] timesWrong; private final long[] sumOfSquaredDifferences; private final List<Integer> originals; private int comparisons; private int permutations; private final Comparator<Integer> comparator = (a, b) -> { comparisons++; return -Integer.compare(a, b); }; private Harness(Solution solution, int arrayLength) { this.solution = solution; this.arrayLength = arrayLength; this.timesWrong = new int[arrayLength]; this.sumOfSquaredDifferences = new long[arrayLength]; originals = new ArrayList<>(arrayLength); for (int i = 0; i < arrayLength; i++) { originals.add(i); } } private void checkRandomPermutations(int trials) { Random random = new Random(0); for (int i = 0; i < trials; i++) { Collections.sort(originals); Collections.shuffle(originals, random); measurePermutation(originals); } } private void checkAllPermutations() { permute(originals, 0); } private void permute(List<Integer> list, int k){ for(int i = k; i < list.size(); i++){ Collections.swap(list, i, k); permute(list, k+1); Collections.swap(list, k, i); } if (k == list.size() - 1) { measurePermutation(list); } } private void measurePermutation(List<Integer> permutation) { permutations++; List<Integer> sorted = solution.pizzaSort(new ArrayList<>(permutation), comparator); for (int i = 0; i < permutation.size(); i++) { int actual = sorted.get(i); int expected = arrayLength - i - 1; if (actual != expected) { int difference = actual - expected; timesWrong[i]++; sumOfSquaredDifferences[i] += (difference * difference); } } } private void printReport() { System.out.printf("%s%n", solution.getClass().getSimpleName()); for (int i = 0; i < arrayLength; i++) { double standardDeviation = Math.sqrt((double) sumOfSquaredDifferences[i] / permutations); System.out.printf("Got %dth place wrong %.2f%% of the time (σ=%.2f)%n", i, ((double)timesWrong[i]/permutations)*100, standardDeviation); } System.out.printf("%.2f comparisons per element (%d total comparisons)%n", ((double) comparisons/permutations/arrayLength), comparisons); System.out.println(); } }
AlecKazakova/pizzasort
Harness.java
248,027
package cell_measurer; import ij.IJ; import ij.ImagePlus; import ij.Prefs; import ij.WindowManager; import ij.gui.Roi; import ij.plugin.PlugIn; import ij.plugin.frame.RoiManager; import ij.process.ImageProcessor; import ij.gui.WaitForUserDialog; import java.io.File; import java.util.Arrays; import java.util.Hashtable; import java.util.stream.IntStream; import ij.gui.GenericDialog; import ij.gui.ImageWindow; import ij.io.Opener; import ij.WindowManager; public class Measure implements PlugIn { public void closeAll() { int[] l = WindowManager.getIDList(); if (l != null) { for (final int id : l) { final ImagePlus imp = WindowManager.getImage(id); if (imp == null) continue; imp.changes = false; imp.close(); } } System.gc(); } public void run(String s) { String dir = IJ.getDirectory("Files?"); String out = IJ.getDirectory("Where to save?"); File[] files = new File(dir).listFiles((_dir, name) -> name.toLowerCase().endsWith(".tif")); for (File f : files) { closeAll(); String outTest = out + "DUP_" + f.getName().replace(".tif", "-0.txt"); if (!new File(outTest).exists()) if (!actuallyRun(f.getAbsolutePath(), out)) { return; } } } boolean actuallyRun(String f, String out) { ImagePlus im = new Opener().openImage(f); // necessary to ensure we get measurements in pixels IJ.run(im, "Set Scale...", "distance=0 known=0"); RoiManager rois = RoiManager.getRoiManager(); if (rois.getCount() > 0) { int[] indices = IntStream.range(0, rois.getCount()).toArray(); rois.setSelectedIndexes(indices); rois.runCommand("Delete"); } im.show(); im = im.duplicate(); im.show(); IJ.setAutoThreshold(im, "Intermodes"); // IJ.setAutoThreshold(im, "Default"); Prefs.blackBackground = false; IJ.run(im, "Convert to Mask", null); IJ.run(im, "Analyze Particles...", "size=200-20000 pixel exclude clear add"); IJ.run("Tile"); GenericDialog d = new GenericDialog("Controls"); d.addMessage("Choose an option from the menu"); d.addChoice("", new String[] { "continue", "skip" }, "continue"); d.showDialog(); if (d.wasCanceled()) return false; if (d.getNextChoice() == "skip" || rois.getCount() == 0) { return true; } new WaitForUserDialog("Fix the ROIs, then press OK!\nDon't press it yet (I know it's as reflex :) )").show(); int[] indices = IntStream.range(0, rois.getCount()).toArray(); rois.setSelectedIndexes(indices); rois.runCommand(im, "Combine"); IJ.setBackgroundColor(255, 255, 255); IJ.run(im, "Clear Outside", ""); IJ.run(im, "Select All", ""); rois.deselect(); for (int roi : rois.getIndexes()) { rois.deselect(); rois.select(im, roi); IJ.run(im, "Save XY Coordinates...", "save=[" + out + im.getTitle() + "-" + roi + ".txt]"); } return true; } }
dlesl/cell_measurer
Measure.java
248,035
/** * Die.java program * @author Matthew Soulanille * @version 2015-01-28 */ import java.lang.Math; public class Die implements Measurable { private double value; public Die() { } public void cast() { value = Math.ceil(Math.random() * 6); } public double getMeasure() { return value; } }
mattsoulanille/compSci
Die/Die.java
248,040
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package o; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.widget.TextView; public final class ns extends TextView { private int LO; private int LP; public ns(Context context) { super(context); LO = 0; LP = 0; } public ns(Context context, AttributeSet attributeset) { super(context, attributeset); LO = 0; LP = 0; } public ns(Context context, AttributeSet attributeset, int i) { super(context, attributeset, i); LO = 0; LP = 0; } public final void draw(Canvas canvas) { canvas.translate(LP / 2, LO / 2); super.draw(canvas); } protected final void onMeasure(int i, int j) { super.onMeasure(i, j); i = getMeasuredWidth(); j = getMeasuredHeight(); int k = Math.max(i, j); if (i > j) { LO = i - j; LP = 0; } else { LO = 0; LP = j - i; } setMeasuredDimension(k, k); } }
zhuharev/periscope-android-source
src/o/ns.java
248,042
package xxx; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Movie; import android.graphics.PorterDuff; import android.os.Build; import android.os.Handler; import android.util.AttributeSet; import android.view.View; /** * Created by song on 2017-6-21 * GIF动图 */ public class GifView extends View { public static final int MATRIX = 0; public static final int FIT_XY = 1; public static final int FIT_START = 2; public static final int FIT_CENTER = 3; public static final int FIT_END = 4; public static final int CENTER = 5; public static final int CENTER_CROP = 6; public static final int CENTER_INSIDE = 7; private int resourceId; private String resourcePath; private Movie movie; private int currentPosition; private int scaleType; private float mLeft; private float mTop; private float mScaleX, mScaleY; private int time = 50;//绘制间隔毫秒 影响cpu使用率 根据情况调节 private float speed = 1.0f; private volatile boolean isPlaying; private boolean mVisible = true; private Handler handler = new Handler(); public GifView(Context context) { this(context, null); } public GifView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public GifView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setViewAttributes(context, attrs, defStyle); } private void setViewAttributes(Context context, AttributeSet attrs, int defStyle) { //关闭硬件加速,可能有兼容性问题 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { setLayerType(View.LAYER_TYPE_SOFTWARE, null); } TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.GifView); resourceId = array.getResourceId(R.styleable.GifView_gif, -1); isPlaying = array.getBoolean(R.styleable.GifView_paused, true); scaleType = array.getInt(R.styleable.GifView_scaleType, FIT_CENTER); array.recycle(); if (resourceId != -1) { movie = Movie.decodeStream(getResources().openRawResource(resourceId)); } handler.post(refreshRun); } public void setGifResource(int movieResourceId) { resourcePath = null; movie = Movie.decodeStream(getResources().openRawResource(this.resourceId = movieResourceId)); tempNowTime = currentPosition = 0; requestLayout(); } public void setGifPath(String path) { resourceId = -1; movie = Movie.decodeFile(this.resourcePath = path); tempNowTime = currentPosition = 0; requestLayout(); } public void setScaleType(int scaleType) { this.scaleType = scaleType; requestLayout(); } /** * 设置速度 支持 十倍加减速 */ public void setSpeed(float speed) { if (speed > 0) { if (speed < 0.1) speed = 0.1f; if (speed > 10) speed = 10; } else { if (speed > -0.1) speed = -0.1f; if (speed < -10) speed = -10; } this.speed = speed; } /** * 测试发现非常耗费cpu 不要调太高 默认20fps */ public void setFPS(int fps) { time = 1000 / fps; } public int getGifResource() { return this.resourceId; } public String getGifPath() { return this.resourcePath; } public float getSpeed() { return speed; } /** * 播放,恢复进度 */ public void play() { if (!isPlaying) { isPlaying = true; tempNowTime = 0; } } /** * 重播 */ public void rePlay() { isPlaying = true; currentPosition = 0; tempNowTime = 0; } /** * 暂停 */ public void pause() { isPlaying = false; } /** * 停止 */ public void stop() { if (resourceId > 0) movie = Movie.decodeStream(getResources().openRawResource(resourceId)); else if (resourcePath != null) movie = Movie.decodeFile(resourcePath); isPlaying = false; tempNowTime = 0; currentPosition = 0; invalidate(); } public boolean isPlaying() { return isPlaying; } /** * 根据模式计算缩放倍数和坐标点 */ private void setScaleWithMode(int viewW, int viewH, int gifW, int gifH, int mode) { float scaleW = 1.0f * viewW / gifW; float scaleH = 1.0f * viewH / gifH; boolean isH = scaleW > scaleH;//是否gif比view高瘦 switch (scaleType = mode) { case MATRIX: mLeft = mTop = 0; mScaleX = mScaleY = 1; break; case FIT_XY: mLeft = mTop = 0; mScaleX = scaleW; mScaleY = scaleH; break; case FIT_START: mLeft = mTop = 0; mScaleX = mScaleY = isH ? scaleH : scaleW; break; default: case FIT_CENTER: mScaleX = mScaleY = isH ? scaleH : scaleW; if (isH) { mTop = 0; mLeft = (viewW - gifW * mScaleX) / 2; } else { mLeft = 0; mTop = (viewH - gifH * mScaleY) / 2; } break; case FIT_END: mScaleX = mScaleY = isH ? scaleH : scaleW; if (isH) { mLeft = viewW - gifW * mScaleX; mTop = 0; } else { mLeft = 0; mTop = viewH - gifH * mScaleY; } break; case CENTER: mScaleX = mScaleY = 1; mLeft = (viewW - gifW) / 2; mTop = (viewH - gifH) / 2; break; case CENTER_CROP: mScaleX = mScaleY = !isH ? scaleH : scaleW; if (!isH) { mTop = 0; mLeft = (viewW - gifW * mScaleX) / 2; } else { mLeft = 0; mTop = (viewH - gifH * mScaleY) / 2; } break; case CENTER_INSIDE: if (scaleH < 1 | scaleW < 1) { mScaleX = mScaleY = isH ? scaleH : scaleW; if (isH) { mTop = 0; mLeft = (viewW - gifW * mScaleX) / 2; } else { mLeft = 0; mTop = (viewH - gifH * mScaleY) / 2; } } else { mScaleX = mScaleY = 1; mLeft = (viewW - gifW) / 2; mTop = (viewH - gifH) / 2; } break; } } //MATCH_PARENT(EXACTLY) WRAP_CONTENT(AT_MOST) @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // if (movie != null) { // int movieWidth = movie.width(); // int movieHeight = movie.height(); // int measureModeWidth = MeasureSpec.getMode(widthMeasureSpec); // int maximumWidth = MeasureSpec.getSize(widthMeasureSpec); // } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if (movie != null) setScaleWithMode(getWidth(), getHeight(), movie.width(), movie.height(), scaleType); mVisible = getVisibility() == View.VISIBLE; invalidate(); } @Override protected void onDraw(Canvas canvas) { if (movie == null) canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); else drawMovieFrame(canvas); } private void drawMovieFrame(Canvas canvas) { if (!mVisible) return; if (isPlaying()) updateAnimationTime(); movie.setTime(currentPosition); canvas.save(Canvas.MATRIX_SAVE_FLAG); canvas.scale(mScaleX, mScaleY); movie.draw(canvas, mLeft / mScaleX, mTop / mScaleY); // if (currentPosition == 0) {//谜一样的bug 播放过后调用stop settime并不能马上绘制出该帧,调用几次才会,而且time必须递增,目前新建一个movie解决,不用这种方式 // movie.setTime(10); // movie.draw(canvas, mLeft / mScaleX, mTop / mScaleY); // movie.setTime(20); // movie.draw(canvas, mLeft / mScaleX, mTop / mScaleY); // } canvas.restore(); // Log.e("====", "drawMovieFrame" + currentPosition); } private Runnable refreshRun = new Runnable() { @Override public void run() { handler.postDelayed(refreshRun, time); if (isPlaying()) invalidate(); } }; private long tempNowTime; //计算播放进度 private void updateAnimationTime() { long nowTime = android.os.SystemClock.uptimeMillis(); if (tempNowTime == 0) tempNowTime = nowTime; int dur = movie.duration(); if (dur == 0) dur = 1000; currentPosition = (int) ((dur * 100 + currentPosition + ((nowTime - tempNowTime) % dur) * speed) % dur); tempNowTime = nowTime; } @Override public void onScreenStateChanged(int screenState) { super.onScreenStateChanged(screenState); mVisible = screenState == SCREEN_STATE_ON; } @Override protected void onVisibilityChanged(View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); mVisible = visibility == View.VISIBLE; } @Override protected void onWindowVisibilityChanged(int visibility) { super.onWindowVisibilityChanged(visibility); mVisible = visibility == View.VISIBLE; } }
tohodog/GifView
GifView.java
248,044
/* * 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. */ package control; /** * * @author User-pc */ import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.doublealgo.Statistic; import cern.colt.matrix.doublealgo.Statistic.VectorVectorFunction; import cern.colt.matrix.impl.DenseDoubleMatrix2D; import cern.colt.matrix.impl.SparseDoubleMatrix2D; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.random.RandomGenerator; public class KMeans { private DoubleMatrix2D means; private DoubleMatrix2D partition; private int maxIterations = 1000; private RandomGenerator randomGenerator = new MersenneTwister(); private PartitionGenerator partitionGenerator = new HardRandomPartitionGenerator(); // private VectorVectorFunction distanceMeasure = Statistic.EUCLID; private CosineDistance distanceMeasure = new CosineDistance(); private DoubleMatrix2D data; private DoubleMatrix2D SV; int totalIterations; int clusters; double distance = 0; long output; public KMeans(DoubleMatrix2D data, int clusters) { this.data = data; this.clusters = clusters; } public KMeans(DoubleMatrix2D data, DoubleMatrix2D SV, int clusters) { this.data = data; this.SV = SV; this.clusters = clusters; } public void cluster() { long lStartTime = System.currentTimeMillis(); int n = data.rows(); // Number of features int p = data.columns(); // Dimensions of features partition = new SparseDoubleMatrix2D(n, clusters); partitionGenerator.setRandomGenerator(randomGenerator); partitionGenerator.generate(partition); means = new DenseDoubleMatrix2D(p, clusters); boolean changedPartition = true; // Begin the main loop of alternating optimization for (int itr = 0; itr < maxIterations && changedPartition; ++itr) { // Get new prototypes (v) for each cluster using weighted median for (int k = 0; k < clusters; k++) { for (int j = 0; j < p; j++) { double sumWeight = 0; double sumValue = 0; for (int i = 0; i < n; i++) { double Um = partition.getQuick(i, k); sumWeight += Um; sumValue += data.getQuick(i, j) * Um; } means.setQuick(j, k, sumValue / sumWeight); } } // Calculate distance measure d: DoubleMatrix2D distances = new DenseDoubleMatrix2D(n, clusters); for (int k = 0; k < clusters; k++) { for (int i = 0; i < n; i++) { // Euclidean distance calculation if(SV != null){ distance = distanceMeasure.calculateDistance(means.viewColumn(k), SV.viewRow(i)); }else{ distance = distanceMeasure.calculateDistance(means.viewColumn(k), data.viewRow(i)); } distances.setQuick(i, k, distance); } } // Get new partition matrix U: changedPartition = false; for (int i = 0; i < n; i++) { double minDistance = Double.MAX_VALUE; int closestCluster = 0; for (int k = 0; k < clusters; k++) { // U = 1 for the closest prototype // U = 0 otherwise if (distances.getQuick(i, k) < minDistance) { minDistance = distances.getQuick(i, k); closestCluster = k; } } if (partition.getQuick(i, closestCluster) == 0) { changedPartition = true; for (int k = 0; k < clusters; k++) { partition.setQuick(i, k, (k == closestCluster) ? 1 : 0); } } } totalIterations = itr; } long lEndTime = System.currentTimeMillis(); output = lEndTime - lStartTime; } public DoubleMatrix2D getMeans() { return means; } public DoubleMatrix2D getPartition() { return partition; } public double getExecTime(){ return (double) output/1000; } public int getTotalIterations(){ return totalIterations+1; } public int getMaxIterations() { return maxIterations; } public void setMaxIterations(int maxIterations) { this.maxIterations = maxIterations; } public RandomGenerator getRandomGenerator() { return randomGenerator; } public void setRandomGenerator(RandomGenerator random) { this.randomGenerator = random; } // public VectorVectorFunction getDistanceMeasure() { // return distanceMeasure; // } // // public void setDistanceMeasure(VectorVectorFunction distanceMeasure) { // this.distanceMeasure = distanceMeasure; // } }
hinovita/SVDxCluster
KMeans.java
248,050
public class coin implements Interfaccia{ private double value; private String name; public coin(String coinName, double coinValue ) { value = coinValue; name = coinName; } public String getName(){ return name; } public double getValue(){ return value; } public boolean sonoUguali(Object moneta1) { coin moneta2 = (coin)moneta1; if(this.value == moneta2.value && this.name.equals(moneta2)) { System.out.println("argh"); return true; } else { System.out.println("hgra"); return false; } } public double getMeasure() { return value; } }
AcamporaV2/Programmazione-3-Ciaramella
coin.java
248,051
package my.game; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; public class Ball extends Entity { private static final long serialVersionUID = 1L; private static final int ballMeasure = 36; //-- the width and height of the circular ball. protected static double ticks = 0; //-- ticks since last bounce. protected static double t = 0; //-- seconds since last bounce for gravity calculation. protected static double lastVel; //-- saves the last yvel of the last bounce. private static double startX = Game.WIDTH - (ballMeasure + 100), startY = (ballMeasure + 25), startVelX = -3, startVelY = 1; private Clip clip = null; private AudioInputStream ais = null; public Ball() { id = ID.Ball; width = height = ballMeasure; x = startX; y = startY; velX = startVelX; velY = startVelY; lastVel = velY; //--Bounce sound effect try { clip = AudioSystem.getClip(); } catch (LineUnavailableException e) { e.printStackTrace(); } try { ais = AudioSystem.getAudioInputStream(new File("resources/bounce.wav")); } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); } try { clip.open(ais); } catch (LineUnavailableException | IOException e) { e.printStackTrace(); } } public void tick() { velY = lastVel - (9.8 * t); //-- this is the gravity calculation. we don't need all that math since we know the explicit bounce velocity. //Check paddle intersection for bounce back if (Game.entList.get(0).getBounds().intersects(getBounds())) { velY *= -1; ticks = -1; lastVel = velY - 0.3286; // to make ball not lose any energy on the bounce. //-- If paddle is moving left, add left ball velocity. if right, add right. if (Paddle.movingLeft) velX -= 2; if (Paddle.movingRight) velX += 2; //-- Bounce sound effect clip.setMicrosecondPosition(0); clip.start(); } //-- Bounce off ceiling if (y <= 1) { velY *= -1; y = 2; } //-- Bounce off walls. if (x < 0 || x > Game.WIDTH-ballMeasure) velX *= -1; //-- if ball fell through bottom, reset to launch point. if (y >= Game.HEIGHT + 200) { ticks = -1; x = startX; y = startY; velX = startVelX; velY = startVelY; lastVel = startVelY; Game.lives--; } x += velX; y -= velY; ticks++; t = ticks / 60; } }
larscase98/lob-pong
Ball.java
248,056
import java.io.IOException; import java.sql.*; import java.util.ArrayList; public class SQL{ //SQL kode til oprettelse af database /* CREATE DATABASE semesterprojekt2; Use semesterprojekt2; CREATE TABLE MeasurementNumber( MeasurementID INT NOT NULL auto_increment, CPR VARCHAR(10) NOT NULL, mearsurementStartedAt TIMESTAMP default current_timestamp, PRIMARY KEY (MeasurementID) ); CREATE TABLE EKG( Measurement INT NOT NULL auto_increment, EKGValue DOUBLE NOT NULL, MeasurementID INT, PRIMARY KEY(Measurement), FOREIGN KEY (MeasurementID) REFERENCES MeasurementNumber(MeasurementID) );*/ //Singleton af SQL Objekt private SQL() {} static private final SQL sqlOBJ = new SQL(); static public SQL getSqlOBJ() { return sqlOBJ; } //Variabler til database connection private String url = "jdbc:mysql://localhost:3306/semesterprojekt2"; private String user = "root"; private String password = ""; private Connection myConn; private Statement myStatement; //Int til at gemme hvilken primary key measurementID var private int measurementID; //Arraylist der gemmes værdier på private final ArrayList<String> DateOfmeasurementonsameCPER = new ArrayList<>(); private final ArrayList<Integer> dataArray = new ArrayList<>(); //Metode der opretter connection til SQL Database public void makeConnectionSQL(String url, String user, String password) throws SQLException { myConn = DriverManager.getConnection(getUrl(),getUser(),getPassword()); myStatement = myConn.createStatement(); } //metode der fjerner connection til SQL Database public void removeConnectionSQL() { try { if (!myConn.isClosed()) { myConn.close(); } } catch (SQLException throwables) { throwables.printStackTrace(); } } //Metode der opretter en patient i MeasurementNumber Tabel public void makePatientMeasurement(String CPR) { try { makeConnectionSQL(getUrl(),getUser(),getPassword()); } catch (SQLException throwables) { throwables.printStackTrace(); } try { String write_to_measurementNumber = "insert into MeasurementNumber(CPR) values(?);"; PreparedStatement PP = myConn.prepareStatement(write_to_measurementNumber); PP.setString(1,(CPR)); PP.execute(); System.out.println("SQL Made patient"); removeConnectionSQL(); } catch ( SQLException throwables) { throwables.printStackTrace(); removeConnectionSQL(); } } //Metode der finder hvilket MeasurementID, der skal gemmes data via. public void findMeasurementID(String CPRstring) { try { makeConnectionSQL(getUrl(),getUser(),getPassword()); String findmeasurementIDFromCPR = "SELECT * FROM MeasurementNumber" + " WHERE CPR = " + CPRstring + ";"; ResultSet rs; rs = myStatement.executeQuery(findmeasurementIDFromCPR); while (rs.next()) { setMeasurementID(rs.getInt(1)); } removeConnectionSQL(); } catch ( SQLException throwables) { throwables.printStackTrace(); removeConnectionSQL(); } } //Metode der finderMeasurementId hvor CPR er et bestemt CPR, bruges i finddata på EKGScene public void FindMeasureIDWhereCPRRead(String CPRstring) throws IOException, SQLException { int counter = 0; int counter2 = 0; makeConnectionSQL(getUrl(),getUser(),getPassword()); String findmeasurementIDFromCPR2 = "SELECT * FROM MeasurementNumber" + " WHERE CPR = " + CPRstring + ";"; ResultSet rs1 = myStatement.executeQuery(findmeasurementIDFromCPR2);// Finder antallet af gange der er taget en measurement på patient while (rs1.next()) { counter++; } //Hvis der er taget flere målinger skal, der være mulighed for at vælge hvilken man vil bruge via Date Timestamp ResultSet rs2 = myStatement.executeQuery(findmeasurementIDFromCPR2); if (counter > 1) { while (rs2.next()) { setNumberOfMeasurementsOnSameCPR(rs2.getString(3), counter2); //fylder String arraylist ud med date timestamp counter2++; } Main.openStage(Main.MultipleMeasurementStage, "Multiple Measurements", "MultipleMeasurements", 220, 180); } else { rs2 = myStatement.executeQuery(findmeasurementIDFromCPR2); rs2.next(); setMeasurementID(rs2.getInt(1)); Algorithm.getAlgorithmOBJ().textBox("Patient Found"); } removeConnectionSQL(); } //Indlæser data fra database til DataArray via, et sat measurementID public void readToDataArray() { try { int counter = 0; makeConnectionSQL(getUrl(),getUser(),getPassword()); String ReadDatatoarray = "SELECT * FROM EKG" + " WHERE MeasurementID=" + measurementID + ";"; ResultSet rs; rs = myStatement.executeQuery(ReadDatatoarray); while (rs.next()) { setDataArray(rs.getInt(2), counter); counter++; } removeConnectionSQL(); } catch ( SQLException throwables) { throwables.printStackTrace(); removeConnectionSQL(); } } //Finder MeasurementID hvor date er en specifik date public void getIdWhereDate(String date) { try { makeConnectionSQL(getUrl(),getUser(),getPassword()); String findmeasurementIDFromDate = "SELECT * FROM MeasurementNumber" + " WHERE mearsurementStartedAt='" + date + "';"; ResultSet rs; rs = myStatement.executeQuery(findmeasurementIDFromDate); while (rs.next()) { setMeasurementID(rs.getInt(1)); } removeConnectionSQL(); } catch ( SQLException throwables) { throwables.printStackTrace(); removeConnectionSQL(); } } //Metode der returnere true hvis, der findes et resultset, og false hvis ikke public boolean doesPatientExsist(String CPR) throws SQLException { makeConnectionSQL(getUrl(),getUser(),getPassword()); String findPatient = "SELECT CPR FROM MeasurementNumber WHERE CPR =" + CPR + ";"; ResultSet rs; try { rs = myStatement.executeQuery(findPatient); rs.next(); boolean buffer = rs.getBoolean(1); removeConnectionSQL(); return buffer; } catch (SQLException throwables) { removeConnectionSQL(); return false; } } //Metode der skriver data til databasen, af 25 datapunkter per query. public void writeToMeasurementArray(int[] array) { try { makeConnectionSQL(getUrl(),getUser(),getPassword()); for (int i = 0; i < array.length - 1; i += 25) { String write_to_measurement = "insert into EKG(EKGValue, MeasurementId) values" + "(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ")" + ",(?," + getMeasurementID() + ");"; PreparedStatement PP = myConn.prepareStatement(write_to_measurement); PP.setInt(1, array[i]); PP.setInt(2, array[i + 1]); PP.setInt(3, array[i + 2]); PP.setInt(4, array[i + 3]); PP.setInt(5, array[i + 4]); PP.setInt(6, array[i + 5]); PP.setInt(7, array[i + 6]); PP.setInt(8, array[i + 7]); PP.setInt(9, array[i + 8]); PP.setInt(10, array[i + 9]); PP.setInt(11, array[i + 10]); PP.setInt(12, array[i + 11]); PP.setInt(13, array[i + 12]); PP.setInt(14, array[i + 13]); PP.setInt(15, array[i + 14]); PP.setInt(16, array[i + 15]); PP.setInt(17, array[i + 16]); PP.setInt(18, array[i + 17]); PP.setInt(19, array[i + 18]); PP.setInt(20, array[i + 19]); PP.setInt(21, array[i + 20]); PP.setInt(22, array[i + 21]); PP.setInt(23, array[i + 22]); PP.setInt(24, array[i + 23]); PP.setInt(25, array[i + 24]); PP.execute(); } System.out.println("Done SQL"); removeConnectionSQL(); } catch (SQLException throwables) { throwables.printStackTrace(); removeConnectionSQL(); } } //Getters and setters til klassen attributter pga. indkapsling public int getMeasurementID() { return measurementID; } public void setMeasurementID(int measurementID) { this.measurementID = measurementID; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public ArrayList<String> getNumberOfMeasurementsOnSameCPR() { return DateOfmeasurementonsameCPER; } public void setNumberOfMeasurementsOnSameCPR(String string, int plads) { this.DateOfmeasurementonsameCPER.add(plads, string); } public ArrayList<Integer> getDataArray() { return dataArray; } public void setDataArray(int data, int plads) { this.dataArray.add(plads, data); } }
Troels21/SemesterProjekt-2
src/SQL.java
248,057
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; public class App { // Função de ordenação Bubble Sort public static int[] bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; } // Função de ordenação Counting Sort public static int[] countingSort(int[] arr) { int n = arr.length; // Encontrar o valor máximo no array int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) { max = arr[i]; } } // Criar um array de contagem int[] count = new int[max + 1]; // Contar as ocorrências de cada elemento for (int i = 0; i < n; i++) { count[arr[i]]++; } // Reconstruir o array ordenado int[] sortedArray = new int[n]; int index = 0; for (int i = 0; i <= max; i++) { while (count[i] > 0) { sortedArray[index++] = i; count[i]--; } } return sortedArray; } // Função de ordenação Insertion Sort public static int[] insertionSort(int[] arr) { for (int i = 1; i < arr.length; i++) { int key = arr[i]; int j = i - 1; while (j >= 0 && key < arr[j]) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } return arr; } // Função de ordenação Merge Sort public static int[] mergeSort(int[] arr) { if (arr.length > 1) { int mid = arr.length / 2; int[] leftHalf = Arrays.copyOfRange(arr, 0, mid); int[] rightHalf = Arrays.copyOfRange(arr, mid, arr.length); leftHalf = mergeSort(leftHalf); rightHalf = mergeSort(rightHalf); int i = 0, j = 0, k = 0; while (i < leftHalf.length && j < rightHalf.length) { if (leftHalf[i] < rightHalf[j]) { arr[k] = leftHalf[i]; i++; } else { arr[k] = rightHalf[j]; j++; } k++; } while (i < leftHalf.length) { arr[k] = leftHalf[i]; i++; k++; } while (j < rightHalf.length) { arr[k] = rightHalf[j]; j++; k++; } } return arr.clone(); } // Função de ordenação Quick Sort public static int[] quickSort(int[] arr) { if (arr.length <= 1) { return arr; } int pivot = arr[arr.length / 2]; int[] left = Arrays.stream(arr).filter(x -> x < pivot).toArray(); int[] middle = Arrays.stream(arr).filter(x -> x == pivot).toArray(); int[] right = Arrays.stream(arr).filter(x -> x > pivot).toArray(); return concatenateArrays(quickSort(left), middle, quickSort(right)); } // Função de ordenação Selection Sort public static int[] selectionSort(int[] arr) { for (int i = 0; i < arr.length; i++) { int minIndex = i; for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } int temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } return arr; } // Função de ordenação Bucket Sort public static int[] bucketSort(int[] arr, SortingFunction internalSort) { int n = arr.length; // Encontrar o valor máximo no array int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) { max = arr[i]; } } // Definir o número de baldes int numBuckets = 10; List<List<Integer>> buckets = new ArrayList<>(numBuckets); for (int i = 0; i < numBuckets; i++) { buckets.add(new ArrayList<>()); } // Distribuir os elementos nos baldes for (int i = 0; i < n; i++) { int bucketIndex = (arr[i] * numBuckets) / (max + 1); buckets.get(bucketIndex).add(arr[i]); } // Ordenar cada balde usando o algoritmo interno for (List<Integer> bucket : buckets) { int[] bucketArray = bucket.stream().mapToInt(Integer::intValue).toArray(); internalSort.sort(bucketArray); } // Juntar os baldes ordenados int index = 0; for (List<Integer> bucket : buckets) { for (int value : bucket) { arr[index++] = value; } } return arr; } // Função para medir o tempo de execução de cada algoritmo public static long measureTime(SortingFunction function, int[] arr) { long startTime = System.nanoTime(); function.sort(arr.clone()); long endTime = System.nanoTime(); long timeTaken = endTime - startTime; double seconds = (double) timeTaken / 1_000_000_000.0; String formattedTime = String.format("%.7f", seconds); System.out.println(formattedTime + " segundos"); return timeTaken; } // Função para gerar um array de números aleatórios e únicos public static int[] generateRandomArray(int size) { int[] dataSet = new int[size]; Random random = new Random(); for (int i = 0; i < size; i++) { dataSet[i] = random.nextInt(size + 1); } return dataSet; } // Função auxiliar para concatenar arrays private static int[] concatenateArrays(int[] left, int[] middle, int[] right) { int[] result = new int[left.length + middle.length + right.length]; System.arraycopy(left, 0, result, 0, left.length); System.arraycopy(middle, 0, result, left.length, middle.length); System.arraycopy(right, 0, result, left.length + middle.length, right.length); return result; } // Função para encontrar o algoritmo mais rápido private static String findFastestAlgorithm(long... times) { long minTime = Long.MAX_VALUE; String fastestAlgorithm = ""; String[] algorithms = {"Bubble Sort", "Counting Sort", "Insertion Sort", "Merge Sort", "Quick Sort", "Selection Sort"}; for (int i = 0; i < times.length; i++) { if (times[i] < minTime) { minTime = times[i]; fastestAlgorithm = algorithms[i]; } } return fastestAlgorithm; } public static void main(String[] args) { int[] randomArray = generateRandomArray(200000); // Tamanhos dos subarrays a serem testados int[] sizes = {100, 500, 1000, 5000, 30000, 80000, 100000, 150000, 200000}; // Testa cada algoritmo para cada tamanho de subarray for (int size : sizes) { int[] subarray = Arrays.copyOfRange(randomArray, 0, size); System.out.println("\nTamanho do Subarray: " + size); // Bucket Sort com Bubble Sort interno System.out.print("Bucket Sort (Bubble Sort): "); long bubbleSortTime = measureTime((arr) -> bucketSort(arr, App::bubbleSort), subarray); // Bucket Sort com Selection Sort interno System.out.print("Bucket Sort (Selection Sort): "); long selectionSortTime = measureTime((arr) -> bucketSort(arr, App::selectionSort), subarray); // Bucket Sort com Insertion Sort interno System.out.print("Bucket Sort (Insertion Sort): "); long insertionSortTime = measureTime((arr) -> bucketSort(arr, App::insertionSort), subarray); // Bucket Sort com Merge Sort interno System.out.print("Bucket Sort (Merge Sort): "); long mergeSortTime = measureTime((arr) -> bucketSort(arr, App::mergeSort), subarray); // Bucket Sort com Quick Sort interno System.out.print("Bucket Sort (Quick Sort): "); long quickSortTime = measureTime((arr) -> bucketSort(arr, App::quickSort), subarray); // Bucket Sort com Counting Sort interno System.out.print("Bucket Sort (Counting Sort): "); long countingSortTime = measureTime((arr) -> bucketSort(arr, App::countingSort), subarray); // Comparar os tempos e identifica o algoritmo mais rápido String fastestAlgorithm = findFastestAlgorithm( bubbleSortTime, countingSortTime, insertionSortTime, mergeSortTime, quickSortTime, selectionSortTime); System.out.println("O algoritmo interno mais rápido para Bucket Sort foi: " + fastestAlgorithm); } } interface SortingFunction { int[] sort(int[] arr); } }
MatheusGODZILLA/bucket-sort
src/App.java
248,058
package my.firework; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JSlider; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class Program extends JFrame implements ActionListener, ChangeListener, ItemListener{ private static final long serialVersionUID = 1L; public static int WIDTH = 1600; public static int HEIGHT = WIDTH / 16 * 9; public static Dimension RES = new Dimension(WIDTH, HEIGHT); private JPanel fwPanel; private JComponent fireworkCanvas; private JPanel uiPanel; public static int UIWIDTH = 470; //-- Declaring JComponents for controls private JPanel titlePanel; private JLabel titleLabel; private JPanel anglePanel; private JLabel angleLabel; public static JSlider angleSlider; public static int angleMeasure = 0; //The stored value for the angle, between -90 & 90 private JPanel velPanel; private JLabel velLabel; public static JSlider velSlider; public static int velMeasure = 40; //Stored value for the velocity, between 0 and 100. private JPanel fusePanel; private JLabel fuseLabel; public static JSlider fuseSlider; public static double fuseMeasure = 3; private JPanel colorPanel; private JLabel colorLabel; private ButtonGroup colorGroup; public static JRadioButton redTrailRadio; public static JRadioButton greenTrailRadio; public static JRadioButton cyanTrailRadio; public static JRadioButton yellowTrailRadio; public static Color trailColor = Color.red; private JPanel explosionPanel; private JLabel explosionLabel; private ButtonGroup explosionGroup; public static JRadioButton radialRadio; public static JRadioButton arcsRadio; public static JRadioButton ovalsRadio; public static int explosionValue = 1; //1 = radial, 2 = arcs, 3 = ovals //private JButton startButton; private static final Font SMALL_FONT = new Font("Verdana", Font.PLAIN, 17); private static final Color TRANSPARENT = new Color(255, 255, 255, 0); public static Color TWILIGHT = new Color(59, 44, 119); public Program() { setTitle("FireworkSimulator 2017"); setSize(WIDTH, HEIGHT); setBackground(Color.cyan); fireworkCanvas = new FireworkCanvas(); fwPanel = new JPanel(); fwPanel.setBackground(Color.white); fwPanel.add(fireworkCanvas); uiPanel = new JPanel(); uiPanel.setBounds(25, 25, UIWIDTH, 700); uiPanel.setBackground(new Color(175, 122, 7, 150)); uiPanel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5), Color.black)); uiPanel.setLayout(new FlowLayout()); titlePanel = new JPanel(); titlePanel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5), Color.black)); anglePanel = new JPanel(); anglePanel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5), Color.black)); anglePanel.setLayout(new FlowLayout()); velPanel = new JPanel(); velPanel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5), Color.black)); fusePanel = new JPanel(); fusePanel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5), Color.black)); colorPanel = new JPanel(); colorPanel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5), Color.black)); explosionPanel = new JPanel(); explosionPanel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5), Color.black)); //Title pane titleLabel = new JLabel("Controls"); titleLabel.setFont(new Font("Verdana", Font.BOLD, 36)); titlePanel.add(titleLabel); // Making the angle-setting pane angleLabel = new JLabel("Angle = 0\u00b0"); angleLabel.setFont(new Font("Verdana", Font.BOLD, 16)); angleSlider = new JSlider(); angleSlider.setMinimum(-60); angleSlider.setMaximum(60); angleSlider.setValue(0); angleSlider.setPaintTicks(true); angleSlider.setMajorTickSpacing(30); angleSlider.setMinorTickSpacing(15); angleSlider.setPaintLabels(true); angleSlider.addChangeListener(this); anglePanel.add(angleLabel); anglePanel.add(angleSlider); //Making the velocity-setting pane velLabel = new JLabel("Velocity = 40 m/s"); velLabel.setFont(new Font("Verdana", Font.BOLD, 16)); velSlider = new JSlider(); velSlider.setMaximum(100); velSlider.setMinimum(0); velSlider.setValue(40); velSlider.setPaintTicks(true); velSlider.setMajorTickSpacing(25); velSlider.setMinorTickSpacing(10); velSlider.setPaintLabels(true); velSlider.addChangeListener(this); velPanel.add(velLabel); velPanel.add(velSlider); //Making the fuse-setting pane fuseLabel = new JLabel("Fuse timer = 3 sec"); fuseLabel.setFont(new Font("Verdana", Font.BOLD, 16)); fuseSlider = new JSlider(); fuseSlider.setMaximum(15); fuseSlider.setMinimum(0); fuseSlider.setValue(3); fuseSlider.setPaintTicks(true); fuseSlider.setMajorTickSpacing(5); fuseSlider.setMinorTickSpacing(1); fuseSlider.setPaintLabels(true); fuseSlider.addChangeListener(this); fuseSlider.setOpaque(false); fusePanel.add(fuseLabel); fusePanel.add(fuseSlider); colorGroup = new ButtonGroup(); //For all radio buttons for trail color colorLabel = new JLabel("Firework Trail Color"); colorLabel.setFont(new Font("Verdana", Font.BOLD, 16)); colorLabel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(10), TRANSPARENT)); redTrailRadio = new JRadioButton("Red"); redTrailRadio.addItemListener(this); redTrailRadio.setSelected(true); redTrailRadio.setFont(SMALL_FONT); greenTrailRadio = new JRadioButton("Green"); greenTrailRadio.addItemListener(this); greenTrailRadio.setFont(SMALL_FONT); cyanTrailRadio = new JRadioButton("Cyan"); cyanTrailRadio.addItemListener(this); cyanTrailRadio.setFont(SMALL_FONT); yellowTrailRadio = new JRadioButton("Yellow"); yellowTrailRadio.addItemListener(this); yellowTrailRadio.setFont(SMALL_FONT); colorGroup.add(redTrailRadio); colorGroup.add(greenTrailRadio); colorGroup.add(cyanTrailRadio); colorGroup.add(yellowTrailRadio); colorPanel.setLayout(new GridBagLayout()); GridBagConstraints colGBC = new GridBagConstraints(); colGBC.fill = GridBagConstraints.BOTH; colGBC.weightx = 1; colGBC.weighty = 1; colGBC.gridwidth = GridBagConstraints.REMAINDER; colorPanel.add(colorLabel, colGBC); colorPanel.add(redTrailRadio, colGBC); colorPanel.add(greenTrailRadio, colGBC); colorPanel.add(cyanTrailRadio, colGBC); colorPanel.add(yellowTrailRadio, colGBC); explosionGroup = new ButtonGroup(); explosionLabel = new JLabel("Explosion Type"); explosionLabel.setFont(new Font("Verdana", Font.BOLD, 16)); explosionLabel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(10), TRANSPARENT)); radialRadio = new JRadioButton("Radial"); radialRadio.addItemListener(this); radialRadio.setSelected(true); radialRadio.setFont(SMALL_FONT); arcsRadio = new JRadioButton("Rays"); arcsRadio.addItemListener(this); arcsRadio.setFont(SMALL_FONT); ovalsRadio = new JRadioButton("Confetti"); ovalsRadio.addItemListener(this); ovalsRadio.setFont(SMALL_FONT); explosionGroup.add(radialRadio); explosionGroup.add(arcsRadio); explosionGroup.add(ovalsRadio); explosionPanel.setLayout(new GridBagLayout()); explosionPanel.add(explosionLabel, colGBC); explosionPanel.add(radialRadio, colGBC); explosionPanel.add(arcsRadio, colGBC); explosionPanel.add(ovalsRadio, colGBC); /* startButton = new JButton("Go!"); //startButton.setToolTipText("Update the simulation with the current parameters."); startButton.setFont(new Font("Trebuchet", Font.BOLD, 30)); startButton.setBackground(TWILIGHT); startButton.setForeground(Color.black); startButton.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black, 5), BorderFactory.createLineBorder(TRANSPARENT, 20))); startButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); startButton.addActionListener(this); */ uiPanel.add(titlePanel); uiPanel.add(anglePanel); uiPanel.add(velPanel); uiPanel.add(fusePanel); uiPanel.add(colorPanel); uiPanel.add(explosionPanel); //uiPanel.add(startButton); add(uiPanel); add(fireworkCanvas); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } @Override public void stateChanged(ChangeEvent e) { if (e.getSource().equals(angleSlider)) { angleMeasure = angleSlider.getValue(); angleLabel.setText("Angle = " + angleMeasure + "\u00b0"); //Unicode char for degrees symbol } else if (e.getSource().equals(velSlider)) { velMeasure = velSlider.getValue(); velLabel.setText("Velocity = " + velMeasure + " m/s"); } else if (e.getSource().equals(fuseSlider)) { fuseMeasure = fuseSlider.getValue(); fuseLabel.setText("Fuse timer = " + fuseMeasure + " sec"); } repaint(); } @Override public void actionPerformed(ActionEvent e) { /*if (e.getSource().equals(startButton)) { fireworkCanvas.repaint(); }*/ } @Override public void itemStateChanged(ItemEvent e) { //For trail colors if(e.getSource().equals(redTrailRadio)) { trailColor = Color.red; //fireworkCanvas.repaint(); } else if (e.getSource().equals(greenTrailRadio)) { trailColor = Color.green; //fireworkCanvas.repaint(); } else if (e.getSource().equals(cyanTrailRadio)) { trailColor = Color.cyan; //fireworkCanvas.repaint(); } else if (e.getSource().equals(yellowTrailRadio)) { trailColor = Color.yellow; //fireworkCanvas.repaint(); } //For explosion types else if (e.getSource().equals(radialRadio)) { explosionValue = 1; } else if (e.getSource().equals(arcsRadio)) { explosionValue = 2; } else if (e.getSource().equals(ovalsRadio)) { explosionValue = 3; } repaint(); } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (UnsupportedLookAndFeelException|ClassNotFoundException|InstantiationException|IllegalAccessException e) {} new Program(); } }
larscase98/firework-simulator
Program.java
248,059
import android.content.Context; import android.graphics.Bitmap; import android.view.Surface; import android.view.SurfaceHolder; import android.view.View; public final class nkc extends njz implements njx { private njx a; private View b; private boolean c; private boolean d; private njy e; public nkc(Context paramContext) { super(paramContext); } private final void l() { if (!m()) { throw new IllegalStateException("MediaView method called before surface created"); } } private final boolean m() { return a != null; } public final int a() { l(); return a.a(); } public final void a(int paramInt) { if (m()) { d = false; a.a(paramInt); return; } d = true; } public final void a(int paramInt1, int paramInt2) { l(); a.a(paramInt1, paramInt2); } public final void a(njy paramnjy) { e = paramnjy; if (m()) { c = false; a.a(paramnjy); return; } c = true; } public final int b() { l(); return a.b(); } public final Bitmap b(int paramInt1, int paramInt2) { if (m()) { return a.b(paramInt1, paramInt2); } return null; } public final void b(int paramInt) { if (m()) { a.b(paramInt); return; } throw new IllegalStateException("SafeTextureMediaView not initialized."); } public final void c() { if (m()) { a.c(); } d = false; } public final void d() { if (m()) { a.d(); } } public final void e() {} public final Surface f() { if (m()) { return a.f(); } return null; } public final SurfaceHolder g() { if (a != null) { return a.g(); } return null; } public final void h() { if (m()) { a.h(); } } public final boolean i() { return (m()) && (a.i()); } public final int j() { return a.j(); } public final View k() { return this; } protected final void onAttachedToWindow() { super.onAttachedToWindow(); if (b != null) { removeView(b); b = null; } Object localObject; if (isHardwareAccelerated()) { localObject = new nki(getContext()); a = ((njx)localObject); } for (b = ((View)localObject);; b = ((View)localObject)) { addView(b); if (c) { c = false; a.a(e); if (d) { a(0); } } return; localObject = new nke(getContext()); a = ((njx)localObject); } } protected final void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { if (getChildCount() > 0) { getChildAt(0).layout(0, 0, paramInt3 - paramInt1, paramInt4 - paramInt2); } } protected final void onMeasure(int paramInt1, int paramInt2) { if (getChildCount() > 0) { View localView = getChildAt(0); localView.measure(paramInt1, paramInt2); setMeasuredDimension(localView.getMeasuredWidth(), localView.getMeasuredHeight()); return; } setMeasuredDimension(0, 0); } } /* Location: * Qualified Name: nkc * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
reverseengineeringer/com.google.android.youtube
src/nkc.java
248,060
import java.util.Arrays; import java.util.Random; public class App { // Função para medir o tempo de execução de cada algoritmo public static long measureTime(String partitionMethod, SortingFunction function, int[] arr) { long startTime = System.nanoTime(); function.sort(arr.clone()); long endTime = System.nanoTime(); long timeTaken = endTime - startTime; double milliseconds = (double) timeTaken / 1_000_000.0; String formattedTime = String.format("%.7f", milliseconds); int trocas; if (function instanceof QuickSortLomuto) { trocas = ((QuickSortLomuto) function).getTrocas(); } else { trocas = ((QuickSortHoare) function).getTrocas(); } System.out.println(partitionMethod + ": " + formattedTime + " milissegundos"); System.out.println("Quantidade de trocas: " + trocas); return timeTaken; } // Função para gerar um array de números aleatórios e únicos public static int[] generateRandomArray(int size) { int[] dataSet = new int[size]; Random random = new Random(); for (int i = 0; i < size; i++) { dataSet[i] = random.nextInt(size + 1); } return dataSet; } // Função para encontrar o algoritmo/método mais rápido private static String findFastestAlgorithm(long... times) { long minTime = Long.MAX_VALUE; String fastestAlgorithm = ""; String[] algorithms = {"Hoare", "Lomuto"}; for (int i = 0; i < times.length; i++) { if (times[i] < minTime) { minTime = times[i]; fastestAlgorithm = algorithms[i]; } } return fastestAlgorithm; } public static void main(String[] args) { int[] randomArray = generateRandomArray(200000); int[] sizes = {100, 500, 1000, 5000, 30000, 80000, 100000, 150000, 200000}; for (int size : sizes) { int[] subarray = Arrays.copyOfRange(randomArray, 0, size); System.out.println("\nTamanho do Subarray: " + size); // Teste com o método de particionamento de Tony Hoare long hoareTime = measureTime("Hoare", new QuickSortHoare(), subarray); // Teste com o método de particionamento de Lomuto long lomutoTime = measureTime("Lomuto", new QuickSortLomuto(), subarray); // Identificar o método mais rápido String fastestAlgorithm = findFastestAlgorithm(hoareTime, lomutoTime); System.out.println("O método mais rápido foi: " + fastestAlgorithm); } } interface SortingFunction { int[] sort(int[] arr); } }
MatheusGODZILLA/Quick-Sort-Particionamento
src/App.java
248,063
404: Not Found
EmaMaker/blob-evolution-simulation
src/Blob.java
248,069
import org.knowm.xchart.*; import org.knowm.xchart.style.Styler; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; class Main { public static void main(String args[]) throws IOException { int n = (int) 2.5; //int maxElement = 0; int[] inputSizes = {500, 1000, 2000, 4000, 8000, 16000, 32000, 64000, 128000, 250000}; double[][] randomDataResults = new double[3][10]; double[][] sortedDataResults = new double[3][10]; double[][] reversedDataResults = new double[3][10]; double[][] dataResultsOfSearchClass = new double[3][10]; String file_path = args[0]; BufferedReader thereader = null; try{ thereader = new BufferedReader(new FileReader(file_path)); thereader.readLine(); // başlığı atlıyorum. String line; // 500, 1000, 2000, 4000, 8000, 16000, 32000, 64000, 128000, and //250000 int[] flowdurations500 = new int[500]; int[] flowdurations1000 = new int[1000]; int[] flowdurations2000 = new int[2000]; int[] flowdurations4000 = new int[4000]; int[] flowdurations8000 = new int[8000]; int[] flowdurations16000 = new int[16000]; int[] flowdurations32000 = new int[32000]; int[] flowdurations64000 = new int[64000]; int[] flowdurations128000 = new int[128000]; int[] flowdurations250000 = new int[250000]; //System.out.println(thereader.readLine()); int counter = 0; while((line = thereader.readLine()) != null){ String[] data = line.split(","); int flowDuration = Integer.parseInt(data[6]); if(counter<500){flowdurations500[counter] = flowDuration;} if(counter<1000){flowdurations1000[counter] = flowDuration;} if(counter<2000){flowdurations2000[counter] = flowDuration;} if(counter<4000){flowdurations4000[counter] = flowDuration;} if(counter<8000){flowdurations8000[counter] = flowDuration;} if(counter<16000){flowdurations16000[counter] = flowDuration;} if(counter<32000){flowdurations32000[counter] = flowDuration;} if(counter<64000){flowdurations64000[counter] = flowDuration;} if(counter<128000){flowdurations128000[counter] = flowDuration;} if(counter<250000){flowdurations250000[counter] = flowDuration;} counter++; // System.out.println(flowDuration); } ArrayList<int[]> flowDurationLists = new ArrayList<>(); flowDurationLists.add(flowdurations500);flowDurationLists.add(flowdurations1000);flowDurationLists.add(flowdurations2000);flowDurationLists.add(flowdurations4000);flowDurationLists.add(flowdurations8000);flowDurationLists.add(flowdurations16000);flowDurationLists.add(flowdurations32000);flowDurationLists.add(flowdurations64000);flowDurationLists.add(flowdurations128000);flowDurationLists.add(flowdurations250000); for(int i = 0; i < 10;i++){ randomDataResults[0][i] =measureInsertionSortTime(flowDurationLists.get(i)); randomDataResults[1][i] =measureMergeSortTime(flowDurationLists.get(i)); randomDataResults[2][i] =measureCountingSortTime(flowDurationLists.get(i)); int[] sortedData = Arrays.copyOf(flowDurationLists.get(i), flowDurationLists.get(i).length); Arrays.sort(sortedData); sortedDataResults[0][i] = measureInsertionSortTime(sortedData); sortedDataResults[1][i] = measureMergeSortTime(sortedData); sortedDataResults[2][i] = measureCountingSortTime(sortedData); int[] reversedData = reversed(sortedData); reversedDataResults[0][i] = measureInsertionSortTime(reversedData); reversedDataResults[1][i] = measureMergeSortTime(reversedData); reversedDataResults[2][i] = measureCountingSortTime(reversedData); dataResultsOfSearchClass[0][i] = measureLinearSearchTime(flowDurationLists.get(i)); dataResultsOfSearchClass[1][i] = measureLinearSearchTime(sortedData); dataResultsOfSearchClass[2][i] = measureBinarySearchTime(sortedData); } System.out.println("randomDataResults:"); printArray(randomDataResults); System.out.println("\nsortedDataResults:"); printArray(sortedDataResults); System.out.println("\nreversedDataResults:"); printArray(reversedDataResults); System.out.println("\ndataResultsOfSearchClass:"); printArray(dataResultsOfSearchClass); // System.out.println(randomDataResults[0][9]); // showAndSaveChart("Random Data Performance", inputSizes, randomDataResults,true); //showAndSaveChart("Merge Sort Performance", inputSizes, sortedDataResults,true); // showAndSaveChart("Sorted Data Performance", inputSizes, sortedDataResults,true); showAndSaveChart("Search Performance", inputSizes, dataResultsOfSearchClass,false); //showAndSaveChart("Reversed Data Performance", inputSizes, reversedDataResults,true); } catch (IOException e) { e.printStackTrace(); } //System.out.println(n); } public static void printArray(double[][] array) { for (double[] row : array) { for (double value : row) { System.out.print(value + " "); } System.out.println(); } } public static void showAndSaveChart(String title, int[] xAxis, double[][] yAxis, boolean controller) throws IOException { // Create Chart XYChart chart = new XYChartBuilder().width(800).height(600).title(title) .yAxisTitle("Time in Milliseconds").xAxisTitle("Input Size").build(); // Convert x axis to double[] double[] doubleX = Arrays.stream(xAxis).asDoubleStream().toArray(); // Customize Chart chart.getStyler().setLegendPosition(Styler.LegendPosition.InsideNE); chart.getStyler().setDefaultSeriesRenderStyle(XYSeries.XYSeriesRenderStyle.Line); // Add a plot for a sorting algorithm if(controller){ chart.addSeries("Insertion Sort", doubleX, yAxis[0]); chart.addSeries("Merge Sort", doubleX, yAxis[1]); chart.addSeries("Counting Sort", doubleX, yAxis[2]);} else{ chart.setYAxisTitle("Time in Nanoseconds"); chart.addSeries("Linear Search for Random Data", doubleX, yAxis[0]); chart.addSeries("Linear Search for Sorted Data", doubleX, yAxis[1]); chart.addSeries("Binary Search for Sorted Data", doubleX, yAxis[2]);} // chart.addSeries("Insertion Sort", doubleX, yAxis[0]); // chart.addSeries("Merge Sort", doubleX, yAxis[1]); // chart.addSeries("Counting Sort", doubleX, yAxis[2]); // Save the chart as PNG BitmapEncoder.saveBitmap(chart, title + ".png", BitmapEncoder.BitmapFormat.PNG); // Show the chart new SwingWrapper(chart).displayChart(); } public static double measureLinearSearchTime(int[] data){ Random randomGenerator = new Random(); double time = 0; for(int i = 0; i<1000;i++){ int randomIndex = randomGenerator.nextInt(data.length); int randomData = data[randomIndex]; long startTime = System.nanoTime(); searchclass.linearsearch(data,randomData); long endTime = System.nanoTime(); time += (endTime - startTime) ; } return time/1000; } public static double measureBinarySearchTime(int[] data){ Random randomGenerator = new Random(); double time = 0; for(int i = 0; i<1000;i++){ int randomData = randomGenerator.nextInt(data.length); long startTime = System.nanoTime(); searchclass.binarysearch(data,randomData); long endTime = System.nanoTime(); time += (endTime - startTime) ; } return time/1000; } public static double measureInsertionSortTime(int[] data) { double time = 0; for(int i = 0; i<10;i++){ long startTime = System.nanoTime(); sortclass.insertionsort(data); long endTime = System.nanoTime(); time += (endTime - startTime) / 1_000_000.0;} return time/10; } public static double measureMergeSortTime(int[] data){ double time = 0; for(int i = 0; i<10;i++){ long startTime = System.nanoTime(); sortclass.mergesort(data); long endTime = System.nanoTime(); time += (endTime - startTime) / 1_000_000.0;} return time/10; } public static double measureCountingSortTime(int[] data){ double time = 0; for(int i = 0; i<10;i++){ long startTime = System.nanoTime(); sortclass.countingSort(data,findMax(data)); long endTime = System.nanoTime(); time += (endTime - startTime) / 1_000_000.0;} return time/10; } public static int findMax(int[] array) { int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } public static int[] reversed(int[] array) { int[] copy = Arrays.copyOf(array, array.length); for (int i = 0; i < array.length / 2; i++) { int temp = copy[i]; copy[i] = copy[array.length - 1 - i]; copy[array.length - 1 - i] = temp; } return copy; } }
atesethem/Algorithm-Complexity-Analysis
Main.java
248,070
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; public class Main { // Função de ordenação Bubble Sort public static int[] bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; } // Função de ordenação Counting Sort public static int[] countingSort(int[] arr) { int n = arr.length; // Encontrar o valor máximo no array int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) { max = arr[i]; } } // Criar um array de contagem int[] count = new int[max + 1]; // Contar as ocorrências de cada elemento for (int i = 0; i < n; i++) { count[arr[i]]++; } // Reconstruir o array ordenado int[] sortedArray = new int[n]; int index = 0; for (int i = 0; i <= max; i++) { while (count[i] > 0) { sortedArray[index++] = i; count[i]--; } } return sortedArray; } // Função de ordenação Insertion Sort public static int[] insertionSort(int[] arr) { for (int i = 1; i < arr.length; i++) { int key = arr[i]; int j = i - 1; while (j >= 0 && key < arr[j]) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } return arr; } // Função de ordenação Merge Sort public static int[] mergeSort(int[] arr) { if (arr.length > 1) { int mid = arr.length / 2; int[] leftHalf = Arrays.copyOfRange(arr, 0, mid); int[] rightHalf = Arrays.copyOfRange(arr, mid, arr.length); leftHalf = mergeSort(leftHalf); rightHalf = mergeSort(rightHalf); int i = 0, j = 0, k = 0; while (i < leftHalf.length && j < rightHalf.length) { if (leftHalf[i] < rightHalf[j]) { arr[k] = leftHalf[i]; i++; } else { arr[k] = rightHalf[j]; j++; } k++; } while (i < leftHalf.length) { arr[k] = leftHalf[i]; i++; k++; } while (j < rightHalf.length) { arr[k] = rightHalf[j]; j++; k++; } } return arr.clone(); } // Função de ordenação Quick Sort public static int[] quickSort(int[] arr) { if (arr.length <= 1) { return arr; } int pivot = arr[arr.length / 2]; int[] left = Arrays.stream(arr).filter(x -> x < pivot).toArray(); int[] middle = Arrays.stream(arr).filter(x -> x == pivot).toArray(); int[] right = Arrays.stream(arr).filter(x -> x > pivot).toArray(); return concatenateArrays(quickSort(left), middle, quickSort(right)); } // Função de ordenação Selection Sort public static int[] selectionSort(int[] arr) { for (int i = 0; i < arr.length; i++) { int minIndex = i; for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } int temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } return arr; } // Função de ordenação Bucket Sort public static int[] bucketSort(int[] arr, SortingFunction internalSort) { int n = arr.length; // Encontrar o valor máximo no array int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) { max = arr[i]; } } // Definir o número de baldes int numBuckets = 10; List<List<Integer>> buckets = new ArrayList<>(numBuckets); for (int i = 0; i < numBuckets; i++) { buckets.add(new ArrayList<>()); } // Distribuir os elementos nos baldes for (int i = 0; i < n; i++) { int bucketIndex = (arr[i] * numBuckets) / (max + 1); buckets.get(bucketIndex).add(arr[i]); } // Ordenar cada balde usando o algoritmo interno for (List<Integer> bucket : buckets) { int[] bucketArray = bucket.stream().mapToInt(Integer::intValue).toArray(); internalSort.sort(bucketArray); } // Juntar os baldes ordenados int index = 0; for (List<Integer> bucket : buckets) { for (int value : bucket) { arr[index++] = value; } } return arr; } // Função para medir o tempo de execução de cada algoritmo public static long measureTime(SortingFunction function, int[] arr) { long startTime = System.nanoTime(); function.sort(arr.clone()); long endTime = System.nanoTime(); long timeTaken = endTime - startTime; long milliseconds = timeTaken / 1_000_000; System.out.println(milliseconds + " milisegundos"); return timeTaken; } // Função para gerar um array de números aleatórios e únicos public static int[] generateRandomArray(int size) { int[] dataSet = new int[size]; Random random = new Random(); for (int i = 0; i < size; i++) { dataSet[i] = random.nextInt(size + 1); } return dataSet; } // Função auxiliar para concatenar arrays private static int[] concatenateArrays(int[] left, int[] middle, int[] right) { int[] result = new int[left.length + middle.length + right.length]; System.arraycopy(left, 0, result, 0, left.length); System.arraycopy(middle, 0, result, left.length, middle.length); System.arraycopy(right, 0, result, left.length + middle.length, right.length); return result; } // Função para encontrar o algoritmo mais rápido private static String findFastestAlgorithm(long... times) { long minTime = Long.MAX_VALUE; String fastestAlgorithm = ""; String[] algorithms = {"Bubble Sort", "Counting Sort", "Insertion Sort", "Merge Sort", "Quick Sort", "Selection Sort"}; for (int i = 0; i < times.length; i++) { if (times[i] < minTime) { minTime = times[i]; fastestAlgorithm = algorithms[i]; } } return fastestAlgorithm; } public static void main(String[] args) { int[] randomArray = generateRandomArray(200000); // Tamanhos dos subarrays a serem testados int[] sizes = {100, 500, 1000, 5000, 30000, 80000, 100000, 150000, 200000}; // Testa cada algoritmo para cada tamanho de subarray for (int size : sizes) { int[] subarray = Arrays.copyOfRange(randomArray, 0, size); System.out.println("\nTamanho do Subarray: " + size); // Bucket Sort com Bubble Sort interno System.out.print("Bucket Sort (Bubble Sort): "); long bubbleSortTime = measureTime((arr) -> bucketSort(arr, Main::bubbleSort), subarray); // Bucket Sort com Selection Sort interno System.out.print("Bucket Sort (Selection Sort): "); long selectionSortTime = measureTime((arr) -> bucketSort(arr, Main::selectionSort), subarray); // Bucket Sort com Insertion Sort interno System.out.print("Bucket Sort (Insertion Sort): "); long insertionSortTime = measureTime((arr) -> bucketSort(arr, Main::insertionSort), subarray); // Bucket Sort com Merge Sort interno System.out.print("Bucket Sort (Merge Sort): "); long mergeSortTime = measureTime((arr) -> bucketSort(arr, Main::mergeSort), subarray); // Bucket Sort com Quick Sort interno System.out.print("Bucket Sort (Quick Sort): "); long quickSortTime = measureTime((arr) -> bucketSort(arr, Main::quickSort), subarray); // Bucket Sort com Counting Sort interno System.out.print("Bucket Sort (Counting Sort): "); long countingSortTime = measureTime((arr) -> bucketSort(arr, Main::countingSort), subarray); // Comparar os tempos e identifica o algoritmo mais rápido String fastestAlgorithm = findFastestAlgorithm( bubbleSortTime, countingSortTime, insertionSortTime, mergeSortTime, quickSortTime, selectionSortTime); System.out.println("O algoritmo interno mais rápido para Bucket Sort foi: " + fastestAlgorithm); } } interface SortingFunction { int[] sort(int[] arr); } }
devpedrohrd/Bucket-Sort
Main.java
248,071
public class timer { public static long measureTime(Runnable codeToMeasure) { long startTime = System.nanoTime(); codeToMeasure.run(); return (System.nanoTime() - startTime); } }
artemkholev/dotsRect
timer.java
248,072
import java.awt.image.BufferedImage; import java.util.ArrayList; import java.awt.Color; public class Actor { //coordinates double x, y; double vx, vy; //vx and vy are about velocity in the obvious way double vt; //vt is a measure of how much of the player's t coordinate is observed to elapse per unit time in the actor's reference frame BufferedImage img; int radius, health; ArrayList<int[]> points; Color color; public Actor(double x, double y) { this.x = x; this.y = y; radius = 10; } public void update() { Player p = Main.game.player; //update position x += vx; y += vy; //do collisions for (Actor a : Main.game.actors) collide(a); for (Thing t : Main.game.things) collide(t); } public void collide(Thing thing) { thing.collide(this); } public void collide(Actor actor) {} public void takeDamage(int damage) { health -= damage; if (health <= 0) die(); } public void die() { for (int i=0; i<Main.game.actors.size(); i++) if (this == Main.game.actors.get(i)){ Main.game.actorDeathFlags.set(i, true); int random = (int)(Math.random() * 50); if(random < 4){ if(random == 0) Main.game.addThing(new HealthPickup(this.x, this.y)); else if(random == 1) Main.game.addThing(new ShotgunPickup(this.x, this.y)); else if(random == 2) Main.game.addThing(new SniperPickup(this.x, this.y)); else Main.game.addThing(new MachinegunPickup(this.x, this.y)); } Main.game.kills++; } } }
zanesterling/c--
Actor.java
248,073
package Recipes; import java.util.ArrayList; public class Recipe { private String name; private String steps; private int time; private ArrayList<Ingredient> ingredients= new ArrayList<Ingredient>(); public Recipe(String name, String steps, int time) { setName(name); setSteps(steps); setTime(time); } public Recipe(String name, String steps, int time, Object... ingredientData) { this.name = name; this.steps = steps; this.time = time; this.ingredients = new ArrayList<>(); for (int i = 0; i < ingredientData.length; i += 3) { String ingredientName = (String )ingredientData[i]; int quantity = (int) ingredientData[i + 1]; String measure = (String)ingredientData[i + 2]; addIngredient(ingredientName, quantity, measure); } } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getSteps() { return this.steps; } public void setSteps(String steps) { this.steps = steps; } public int getTime() { return this.time; } public void setTime(int time) { this.time = time; } public void addIngredient(String name, int quantity, String unit) { ingredients.add(new Ingredient(name, quantity, unit)); } public void changeQuantity(String key, int quantity) { for (Ingredient i: ingredients) { if (i.getName().equals(key)) { i.setQuantity(quantity); } } System.out.println("Ingredient not found"); } public void changeMeasure(String key, String measure) { for (Ingredient i: ingredients) { if (i.getName().equals(key)) { i.setMeasure(measure); } } System.out.println("Ingredient not found"); } public boolean hasIngredient(String ingredient) { for (Ingredient i: ingredients) { if (i.getName().equals(ingredient)) { return true; } } return false; } public void deleteIngredient(String key) { if (!ingredients.isEmpty()) { for (Ingredient i: ingredients) { if (i.getName().equals(key)) { ingredients.remove(i); } } System.out.println("Ingredient not found"); return; } System.out.println("There are no ingredients!"); } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("\n"); result.append("╔════════════════════════════════════════════════════╗\n"); result.append("║ ").append(this.name).append("\n"); result.append("╚════════════════════════════════════════════════════╝\n\n"); result.append("──────────────────────────────────────────────────────\n"); result.append(" Recipe Steps:\n"); result.append("──────────────────────────────────────────────────────\n"); // Dividimos los pasos de la receta en líneas y los agregamos uno por uno String[] steps = getSteps().split("\n"); for (int i = 0; i < steps.length; i++) { result.append(" ").append(i + 1).append(". ").append(steps[i]).append("\n"); } result.append("\n Time to cook: ").append(getTime()).append(" mins\n\n"); result.append("──────────────────────────────────────────────────────\n"); result.append(" Ingredients:\n"); result.append("──────────────────────────────────────────────────────\n"); // Agregamos los ingredientes uno por uno for (Ingredient i : ingredients) { result.append(" • ").append(i).append("\n"); } result.append("──────────────────────────────────────────────────────\n"); result.append("\n"); return result.toString(); } }
andresovalle11/SemesterAufgabe
Recipe.java
248,077
package e.z.b; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.view.animation.Animation; import android.widget.ImageView; import e.i.j.z; import java.util.concurrent.atomic.AtomicInteger; /* compiled from: CircleImageView.java */ /* loaded from: classes.dex */ public class a extends ImageView { /* renamed from: f reason: collision with root package name */ public Animation.AnimationListener f3014f; /* renamed from: g reason: collision with root package name */ public int f3015g; /* renamed from: h reason: collision with root package name */ public int f3016h; public a(Context context) { super(context); float f2 = getContext().getResources().getDisplayMetrics().density; this.f3015g = (int) (3.5f * f2); TypedArray obtainStyledAttributes = getContext().obtainStyledAttributes(e.z.a.a); this.f3016h = obtainStyledAttributes.getColor(0, -328966); obtainStyledAttributes.recycle(); ShapeDrawable shapeDrawable = new ShapeDrawable(new OvalShape()); AtomicInteger atomicInteger = z.a; z.i.s(this, f2 * 4.0f); shapeDrawable.getPaint().setColor(this.f3016h); z.d.q(this, shapeDrawable); } @Override // android.view.View public void onAnimationEnd() { super.onAnimationEnd(); Animation.AnimationListener animationListener = this.f3014f; if (animationListener != null) { animationListener.onAnimationEnd(getAnimation()); } } @Override // android.view.View public void onAnimationStart() { super.onAnimationStart(); Animation.AnimationListener animationListener = this.f3014f; if (animationListener != null) { animationListener.onAnimationStart(getAnimation()); } } @Override // android.widget.ImageView, android.view.View public void onMeasure(int i2, int i3) { super.onMeasure(i2, i3); } @Override // android.view.View public void setBackgroundColor(int i2) { if (getBackground() instanceof ShapeDrawable) { ((ShapeDrawable) getBackground()).getPaint().setColor(i2); this.f3016h = i2; } } }
subhadip001/sources
e/z/b/a.java
248,078
package e.b.h; import android.content.Context; import android.graphics.Bitmap; import android.util.AttributeSet; import android.view.View; import android.widget.RatingBar; import com.video_converter.video_compressor.R; /* compiled from: AppCompatRatingBar.java */ /* loaded from: classes.dex */ public class s extends RatingBar { /* renamed from: f reason: collision with root package name */ public final q f1836f; public s(Context context, AttributeSet attributeSet) { super(context, attributeSet, R.attr.ratingBarStyle); u0.a(this, getContext()); q qVar = new q(this); this.f1836f = qVar; qVar.a(attributeSet, R.attr.ratingBarStyle); } @Override // android.widget.RatingBar, android.widget.AbsSeekBar, android.widget.ProgressBar, android.view.View public synchronized void onMeasure(int i2, int i3) { super.onMeasure(i2, i3); Bitmap bitmap = this.f1836f.b; if (bitmap != null) { setMeasuredDimension(View.resolveSizeAndState(bitmap.getWidth() * getNumStars(), i2, 0), getMeasuredHeight()); } } }
subhadip001/sources
e/b/h/s.java
248,079
package a.d.b; import a.d.a.i.h; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; import androidx.constraintlayout.widget.ConstraintLayout; public abstract class b extends View { public int[] b; public int c; public Context d; public h e; public boolean f; public String g; public b(Context paramContext) { super(paramContext); int[] arrayOfInt = new int[32]; throw new VerifyError("bad dex opcode"); } private void setIds(String paramString) { if (paramString == null) throw new VerifyError("bad dex opcode"); throw new VerifyError("bad dex opcode"); } public void a() { throw new VerifyError("bad dex opcode"); } public void a(AttributeSet paramAttributeSet) { if (paramAttributeSet != null) throw new VerifyError("bad dex opcode"); throw new VerifyError("bad dex opcode"); } public void a(ConstraintLayout paramConstraintLayout) { throw new VerifyError("bad dex opcode"); } public final void a(String paramString) { if (paramString == null) throw new VerifyError("bad dex opcode"); throw new VerifyError("bad dex opcode"); } public void b() { throw new VerifyError("bad dex opcode"); } public void c() { throw new VerifyError("bad dex opcode"); } public int[] getReferencedIds() { throw new VerifyError("bad dex opcode"); } public void onDraw(Canvas paramCanvas) { throw new VerifyError("bad dex opcode"); } public void onMeasure(int paramInt1, int paramInt2) { throw new VerifyError("bad dex opcode"); } public void setReferencedIds(int[] paramArrayOfint) { throw new VerifyError("bad dex opcode"); } public void setTag(int paramInt, Object paramObject) { throw new VerifyError("bad dex opcode"); } } /* Location: D:\code\BluedHook\classes.dex\com.soft.blued555128-dex2jar.jar!\a\d\b\b.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
lack21115/blued-7.7.4-src
a/d/b/b.java
248,081
import android.content.Context; import android.content.res.Resources; import android.content.res.Resources.Theme; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.FocusFinder; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.view.ViewParent; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import java.util.ArrayList; import java.util.List; public class kpi extends FrameLayout implements ny, oa, oe { private static final kpj w = new kpj(); private static final int[] x = { 16843130 }; private float A; private long a; private final Rect b = new Rect(); kpk c; private uc d = uc.a(getContext(), null); private tc e; private tc f; private int g; private boolean h = true; private boolean i = false; private View j = null; private boolean k = false; private VelocityTracker l; private boolean m; private boolean n = true; private int o; private int p; private int q; private int r = -1; private final int[] s = new int[2]; private final int[] t = new int[2]; private int u; private kpl v; private final ob y; private final nz z; public kpi(Context paramContext) { this(paramContext, null); } public kpi(Context paramContext, AttributeSet paramAttributeSet) { this(paramContext, paramAttributeSet, 0); } public kpi(Context paramContext, AttributeSet paramAttributeSet, int paramInt) { super(paramContext, paramAttributeSet, paramInt); setFocusable(true); setDescendantFocusability(262144); setWillNotDraw(false); ViewConfiguration localViewConfiguration = ViewConfiguration.get(getContext()); o = localViewConfiguration.getScaledTouchSlop(); p = localViewConfiguration.getScaledMinimumFlingVelocity(); q = localViewConfiguration.getScaledMaximumFlingVelocity(); paramContext = paramContext.obtainStyledAttributes(paramAttributeSet, x, paramInt, 0); boolean bool = paramContext.getBoolean(0, false); if (bool != m) { m = bool; requestLayout(); } paramContext.recycle(); y = new ob(); z = new nz(this); setNestedScrollingEnabled(true); ok.a(this, w); } private final int a(Rect paramRect) { if (getChildCount() == 0) { return 0; } int i4 = getHeight(); int i1 = getScrollY(); int i3 = i1 + i4; int i5 = getVerticalFadingEdgeLength(); int i2 = i1; if (top > 0) { i2 = i1 + i5; } i1 = i3; if (bottom < getChildAt(0).getHeight()) { i1 = i3 - i5; } if ((bottom > i1) && (top > i2)) { if (paramRect.height() > i4) { i2 = top - i2 + 0; i1 = Math.min(i2, getChildAt(0).getBottom() - i1); } } for (;;) { return i1; i2 = bottom - i1 + 0; break; if ((top < i2) && (bottom < i1)) { if (paramRect.height() > i4) {} for (i1 = 0 - (i1 - bottom);; i1 = 0 - (i2 - top)) { i1 = Math.max(i1, -getScrollY()); break; } } i1 = 0; } } private final void a(int paramInt1, int paramInt2) { if (getChildCount() == 0) { return; } if (AnimationUtils.currentAnimationTimeMillis() - a > 250L) { paramInt1 = getHeight(); int i1 = getPaddingBottom(); int i2 = getPaddingTop(); i1 = Math.max(0, getChildAt(0).getHeight() - (paramInt1 - i1 - i2)); paramInt1 = getScrollY(); paramInt2 = Math.max(0, Math.min(paramInt1 + paramInt2, i1)); d.a(getScrollX(), paramInt1, paramInt2 - paramInt1); ok.c(this); } for (;;) { a = AnimationUtils.currentAnimationTimeMillis(); return; if (!d.a()) { d.h(); } scrollBy(paramInt1, paramInt2); } } private final void a(MotionEvent paramMotionEvent) { int i1 = paramMotionEvent.getAction() >> 8 & 0xFF; if (ns.b(paramMotionEvent, i1) == r) { if (i1 != 0) { break label64; } } label64: for (i1 = 1;; i1 = 0) { g = ((int)ns.d(paramMotionEvent, i1)); r = ns.b(paramMotionEvent, i1); if (l != null) { l.clear(); } return; } } private final boolean a(int paramInt1, int paramInt2, int paramInt3) { int i1 = getHeight(); int i6 = getScrollY(); int i7 = i6 + i1; int i3; Object localObject1; int i4; label53: Object localObject2; int i5; int i9; int i2; if (paramInt1 == 33) { i3 = 1; ArrayList localArrayList = getFocusables(2); localObject1 = null; i1 = 0; int i8 = localArrayList.size(); i4 = 0; if (i4 >= i8) { break label237; } localObject2 = (View)localArrayList.get(i4); i5 = ((View)localObject2).getTop(); i9 = ((View)localObject2).getBottom(); if ((paramInt2 >= i9) || (i5 >= paramInt3)) { break label312; } if ((paramInt2 >= i5) || (i9 >= paramInt3)) { break label143; } i2 = 1; label115: if (localObject1 != null) { break label149; } localObject1 = localObject2; i1 = i2; } label143: label149: label210: label237: label312: for (;;) { i4 += 1; break label53; i3 = 0; break; i2 = 0; break label115; if (((i3 != 0) && (i5 < ((View)localObject1).getTop())) || ((i3 == 0) && (i9 > ((View)localObject1).getBottom()))) {} for (i5 = 1;; i5 = 0) { if (i1 == 0) { break label210; } if ((i2 == 0) || (i5 == 0)) { break label312; } localObject1 = localObject2; break; } if (i2 != 0) { localObject1 = localObject2; i1 = 1; } else if (i5 != 0) { localObject1 = localObject2; continue; localObject2 = localObject1; if (localObject1 == null) { localObject2 = this; } boolean bool; if ((paramInt2 >= i6) && (paramInt3 <= i7)) { bool = false; if (localObject2 != findFocus()) { ((View)localObject2).requestFocus(paramInt1); } return bool; } if (i3 != 0) { paramInt2 -= i6; } for (;;) { e(paramInt2); bool = true; break; paramInt2 = paramInt3 - i7; } } } } private final boolean a(int paramInt1, int paramInt2, int paramInt3, int paramInt4, int paramInt5) { boolean bool3 = false; ok.a(this); computeHorizontalScrollRange(); computeHorizontalScrollExtent(); computeVerticalScrollRange(); computeVerticalScrollExtent(); paramInt1 = paramInt3 + paramInt1; paramInt2 = paramInt4 + paramInt2; boolean bool1; if (paramInt1 > 0) { bool1 = true; paramInt1 = 0; } for (;;) { boolean bool2; if (paramInt2 > paramInt5) { bool2 = true; } for (;;) { if (bool2) { d.b(paramInt1, paramInt5, a()); } onOverScrolled(paramInt1, paramInt5, bool1, bool2); if (!bool1) { bool1 = bool3; if (!bool2) {} } else { bool1 = true; } return bool1; if (paramInt1 >= 0) { break label140; } bool1 = true; paramInt1 = 0; break; if (paramInt2 < 0) { bool2 = true; paramInt5 = 0; } else { paramInt5 = paramInt2; bool2 = false; } } label140: bool1 = false; } } private final boolean a(View paramView) { boolean bool = false; if (!a(paramView, 0, getHeight())) { bool = true; } return bool; } private final boolean a(View paramView, int paramInt1, int paramInt2) { paramView.getDrawingRect(b); offsetDescendantRectToMyCoords(paramView, b); return (b.bottom + paramInt1 >= getScrollY()) && (b.top - paramInt1 <= getScrollY() + paramInt2); } private static boolean a(View paramView1, View paramView2) { if (paramView1 == paramView2) { return true; } paramView1 = paramView1.getParent(); return ((paramView1 instanceof ViewGroup)) && (a((View)paramView1, paramView2)); } private static int b(int paramInt1, int paramInt2, int paramInt3) { int i1; if ((paramInt2 >= paramInt3) || (paramInt1 < 0)) { i1 = 0; } do { return i1; i1 = paramInt1; } while (paramInt2 + paramInt1 <= paramInt3); return paramInt3 - paramInt2; } private final void b() { if (l == null) { l = VelocityTracker.obtain(); } } private final void b(View paramView) { paramView.getDrawingRect(b); offsetDescendantRectToMyCoords(paramView, b); int i1 = a(b); if (i1 != 0) { scrollBy(0, i1); } } private final void c() { if (l != null) { l.recycle(); l = null; } } private final boolean c(int paramInt) { if (paramInt == 130) {} for (int i1 = 1;; i1 = 0) { int i2 = getHeight(); b.top = 0; b.bottom = i2; if (i1 != 0) { i1 = getChildCount(); if (i1 > 0) { View localView = getChildAt(i1 - 1); b.bottom = (localView.getBottom() + getPaddingBottom()); b.top = (b.bottom - i2); } } return a(paramInt, b.top, b.bottom); } } private final void d() { k = false; c(); stopNestedScroll(); if (e != null) { e.c(); f.c(); } } private final boolean d(int paramInt) { View localView2 = findFocus(); View localView1 = localView2; if (localView2 == this) { localView1 = null; } localView2 = FocusFinder.getInstance().findNextFocus(this, localView1, paramInt); int i2 = (int)(0.5F * getHeight()); if ((localView2 != null) && (a(localView2, i2, getHeight()))) { localView2.getDrawingRect(b); offsetDescendantRectToMyCoords(localView2, b); e(a(b)); localView2.requestFocus(paramInt); if ((localView1 != null) && (localView1.isFocused()) && (a(localView1))) { paramInt = getDescendantFocusability(); setDescendantFocusability(131072); requestFocus(); setDescendantFocusability(paramInt); } return true; } int i1; if ((paramInt == 33) && (getScrollY() < i2)) { i1 = getScrollY(); } while (i1 == 0) { return false; i1 = i2; if (paramInt == 130) { i1 = i2; if (getChildCount() > 0) { int i3 = getChildAt(0).getBottom(); int i4 = getScrollY() + getHeight() - getPaddingBottom(); i1 = i2; if (i3 - i4 < i2) { i1 = i3 - i4; } } } } if (paramInt == 130) {} for (;;) { e(i1); break; i1 = -i1; } } private final void e() { if (ok.a(this) != 2) { if (e == null) { Context localContext = getContext(); e = new tc(localContext); f = new tc(localContext); } return; } e = null; f = null; } private final void e(int paramInt) { if (paramInt != 0) { if (n) { a(0, paramInt); } } else { return; } scrollBy(0, paramInt); } private final void f(int paramInt) { int i1 = getScrollY(); if (((i1 > 0) || (paramInt > 0)) && ((i1 < a()) || (paramInt < 0))) {} for (boolean bool = true;; bool = false) { if (!dispatchNestedPreFling(0.0F, paramInt)) { dispatchNestedFling(0.0F, paramInt, bool); if (bool) { a(paramInt); } } return; } } final int a() { int i1 = 0; if (getChildCount() > 0) { i1 = Math.max(0, getChildAt(0).getHeight() - (getHeight() - getPaddingBottom() - getPaddingTop())); } return i1; } public void a(int paramInt) { if (getChildCount() > 0) { int i1 = getHeight() - getPaddingBottom() - getPaddingTop(); int i2 = getChildAt(0).getHeight(); d.b(getScrollX(), getScrollY(), paramInt, Math.max(0, i2 - i1), i1 / 2); ok.c(this); } } public void addView(View paramView) { if (getChildCount() > 0) { throw new IllegalStateException("ScrollView can host only one direct child"); } super.addView(paramView); } public void addView(View paramView, int paramInt) { if (getChildCount() > 0) { throw new IllegalStateException("ScrollView can host only one direct child"); } super.addView(paramView, paramInt); } public void addView(View paramView, int paramInt, ViewGroup.LayoutParams paramLayoutParams) { if (getChildCount() > 0) { throw new IllegalStateException("ScrollView can host only one direct child"); } super.addView(paramView, paramInt, paramLayoutParams); } public void addView(View paramView, ViewGroup.LayoutParams paramLayoutParams) { if (getChildCount() > 0) { throw new IllegalStateException("ScrollView can host only one direct child"); } super.addView(paramView, paramLayoutParams); } public final void b(int paramInt) { a(0 - getScrollX(), paramInt - getScrollY()); } public int computeHorizontalScrollExtent() { return super.computeHorizontalScrollExtent(); } public int computeHorizontalScrollOffset() { return super.computeHorizontalScrollOffset(); } public int computeHorizontalScrollRange() { return super.computeHorizontalScrollRange(); } public void computeScroll() { int i3; int i5; int i6; int i1; if (d.g()) { int i2 = getScrollX(); i3 = getScrollY(); int i4 = d.b(); i5 = d.c(); if ((i2 != i4) || (i3 != i5)) { i6 = a(); i1 = ok.a(this); if ((i1 != 0) && ((i1 != 1) || (i6 <= 0))) { break label128; } i1 = 1; a(i4 - i2, i5 - i3, i2, i3, i6); if (i1 != 0) { e(); if ((i5 > 0) || (i3 <= 0)) { break label133; } e.a((int)d.f()); } } } label128: label133: while ((i5 < i6) || (i3 >= i6)) { return; i1 = 0; break; } f.a((int)d.f()); } public int computeVerticalScrollExtent() { return super.computeVerticalScrollExtent(); } public int computeVerticalScrollOffset() { return Math.max(0, super.computeVerticalScrollOffset()); } public int computeVerticalScrollRange() { int i2 = getChildCount(); int i1 = getHeight() - getPaddingBottom() - getPaddingTop(); if (i2 == 0) {} int i3; int i4; do { return i1; i2 = getChildAt(0).getBottom(); i3 = getScrollY(); i4 = Math.max(0, i2 - i1); if (i3 < 0) { return i2 - i3; } i1 = i2; } while (i3 <= i4); return i2 + (i3 - i4); } public boolean dispatchKeyEvent(KeyEvent paramKeyEvent) { boolean bool2 = false; int i1; boolean bool1; if (!super.dispatchKeyEvent(paramKeyEvent)) { b.setEmpty(); View localView = getChildAt(0); if (localView == null) { break label142; } i1 = localView.getHeight(); if (getHeight() >= i1 + getPaddingTop() + getPaddingBottom()) { break label137; } i1 = 1; if (i1 != 0) { break label159; } if ((!isFocused()) || (paramKeyEvent.getKeyCode() == 4)) { break label153; } localView = findFocus(); paramKeyEvent = localView; if (localView == this) { paramKeyEvent = null; } paramKeyEvent = FocusFinder.getInstance().findNextFocus(this, paramKeyEvent, 130); if ((paramKeyEvent == null) || (paramKeyEvent == this) || (!paramKeyEvent.requestFocus(130))) { break label147; } bool1 = true; } for (;;) { if (bool1) { bool2 = true; } return bool2; label137: i1 = 0; break; label142: i1 = 0; break; label147: bool1 = false; continue; label153: bool1 = false; continue; label159: if (paramKeyEvent.getAction() == 0) {} switch (paramKeyEvent.getKeyCode()) { default: bool1 = false; break; case 19: if (!paramKeyEvent.isAltPressed()) { bool1 = d(33); } else { bool1 = c(33); } break; case 20: if (!paramKeyEvent.isAltPressed()) { bool1 = d(130); } else { bool1 = c(130); } break; } } label280: int i2; label289: int i3; if (paramKeyEvent.isShiftPressed()) { i1 = 33; if (i1 != 130) { break label408; } i2 = 1; i3 = getHeight(); if (i2 == 0) { break label413; } b.top = (getScrollY() + i3); i2 = getChildCount(); if (i2 > 0) { paramKeyEvent = getChildAt(i2 - 1); if (b.top + i3 > paramKeyEvent.getBottom()) { b.top = (paramKeyEvent.getBottom() - i3); } } } for (;;) { b.bottom = (i3 + b.top); a(i1, b.top, b.bottom); break; i1 = 130; break label280; label408: i2 = 0; break label289; label413: b.top = (getScrollY() - i3); if (b.top < 0) { b.top = 0; } } } public boolean dispatchNestedFling(float paramFloat1, float paramFloat2, boolean paramBoolean) { return z.a(paramFloat1, paramFloat2, paramBoolean); } public boolean dispatchNestedPreFling(float paramFloat1, float paramFloat2) { return z.a(paramFloat1, paramFloat2); } public boolean dispatchNestedPreScroll(int paramInt1, int paramInt2, int[] paramArrayOfInt1, int[] paramArrayOfInt2) { return z.a(paramInt1, paramInt2, paramArrayOfInt1, paramArrayOfInt2); } public boolean dispatchNestedScroll(int paramInt1, int paramInt2, int paramInt3, int paramInt4, int[] paramArrayOfInt) { return z.a(paramInt1, paramInt2, paramInt3, paramInt4, paramArrayOfInt); } public void draw(Canvas paramCanvas) { super.draw(paramCanvas); if (e != null) { int i1 = getScrollY(); int i2; int i3; int i4; if (!e.a()) { i2 = paramCanvas.save(); i3 = getWidth(); i4 = getPaddingLeft(); int i5 = getPaddingRight(); paramCanvas.translate(getPaddingLeft(), Math.min(0, i1)); e.a(i3 - i4 - i5, getHeight()); if (e.a(paramCanvas)) { ok.c(this); } paramCanvas.restoreToCount(i2); } if (!f.a()) { i2 = paramCanvas.save(); i3 = getWidth() - getPaddingLeft() - getPaddingRight(); i4 = getHeight(); paramCanvas.translate(-i3 + getPaddingLeft(), Math.max(a(), i1) + i4); paramCanvas.rotate(180.0F, i3, 0.0F); f.a(i3, i4); if (f.a(paramCanvas)) { ok.c(this); } paramCanvas.restoreToCount(i2); } } } protected float getBottomFadingEdgeStrength() { if (getChildCount() == 0) { return 0.0F; } int i1 = getVerticalFadingEdgeLength(); int i2 = getHeight(); int i3 = getPaddingBottom(); i2 = getChildAt(0).getBottom() - getScrollY() - (i2 - i3); if (i2 < i1) { return i2 / i1; } return 1.0F; } public int getNestedScrollAxes() { return y.a; } protected float getTopFadingEdgeStrength() { if (getChildCount() == 0) { return 0.0F; } int i1 = getVerticalFadingEdgeLength(); int i2 = getScrollY(); if (i2 < i1) { return i2 / i1; } return 1.0F; } public boolean hasNestedScrollingParent() { return z.a(); } public boolean isNestedScrollingEnabled() { return z.a; } protected void measureChild(View paramView, int paramInt1, int paramInt2) { ViewGroup.LayoutParams localLayoutParams = paramView.getLayoutParams(); paramView.measure(getChildMeasureSpec(paramInt1, getPaddingLeft() + getPaddingRight(), width), View.MeasureSpec.makeMeasureSpec(0, 0)); } protected void measureChildWithMargins(View paramView, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { ViewGroup.MarginLayoutParams localMarginLayoutParams = (ViewGroup.MarginLayoutParams)paramView.getLayoutParams(); paramInt1 = getChildMeasureSpec(paramInt1, getPaddingLeft() + getPaddingRight() + leftMargin + rightMargin + paramInt2, width); paramInt2 = topMargin; paramView.measure(paramInt1, View.MeasureSpec.makeMeasureSpec(bottomMargin + paramInt2, 0)); } public void onAttachedToWindow() { i = false; } public boolean onGenericMotionEvent(MotionEvent paramMotionEvent) { if ((ns.d(paramMotionEvent) & 0x2) != 0) { switch (paramMotionEvent.getAction()) { } } for (;;) { return false; if (!k) { float f1 = ns.e(paramMotionEvent, 9); if (f1 != 0.0F) { if (A == 0.0F) { paramMotionEvent = new TypedValue(); Context localContext = getContext(); if (!localContext.getTheme().resolveAttribute(16842829, paramMotionEvent, true)) { throw new IllegalStateException("Expected theme to define listPreferredItemHeight."); } A = paramMotionEvent.getDimension(localContext.getResources().getDisplayMetrics()); } int i1 = (int)(f1 * A); int i2 = a(); int i4 = getScrollY(); int i3 = i4 - i1; if (i3 < 0) { i1 = 0; } while (i1 != i4) { super.scrollTo(getScrollX(), i1); return true; i1 = i2; if (i3 <= i2) { i1 = i3; } } } } } } public boolean onInterceptTouchEvent(MotionEvent paramMotionEvent) { boolean bool = true; int i1 = paramMotionEvent.getAction(); if ((i1 == 2) && (k)) { return true; } switch (i1 & 0xFF) { } for (;;) { return k; i1 = r; if (i1 != -1) { int i2 = ns.a(paramMotionEvent, i1); if (i2 == -1) { Log.e("NestedScrollView", 54 + "Invalid pointerId=" + i1 + " in onInterceptTouchEvent"); } else { i1 = (int)ns.d(paramMotionEvent, i2); if ((Math.abs(i1 - g) > o) && ((getNestedScrollAxes() & 0x2) == 0)) { k = true; g = i1; b(); l.addMovement(paramMotionEvent); u = 0; paramMotionEvent = getParent(); if (paramMotionEvent != null) { paramMotionEvent.requestDisallowInterceptTouchEvent(true); continue; i2 = (int)paramMotionEvent.getY(); i1 = (int)paramMotionEvent.getX(); if (getChildCount() > 0) { int i3 = getScrollY(); View localView = getChildAt(0); if ((i2 >= localView.getTop() - i3) && (i2 < localView.getBottom() - i3) && (i1 >= localView.getLeft()) && (i1 < localView.getRight())) { i1 = 1; } } for (;;) { if (i1 != 0) { break label312; } k = false; c(); break; i1 = 0; continue; i1 = 0; } label312: g = i2; r = ns.b(paramMotionEvent, 0); if (l == null) { l = VelocityTracker.obtain(); label340: l.addMovement(paramMotionEvent); d.g(); if (d.a()) { break label391; } } for (;;) { k = bool; startNestedScroll(2); break; l.clear(); break label340; label391: bool = false; } k = false; r = -1; c(); if (d.b(getScrollX(), getScrollY(), a())) { ok.c(this); } stopNestedScroll(); continue; a(paramMotionEvent); } } } } } } protected void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { super.onLayout(paramBoolean, paramInt1, paramInt2, paramInt3, paramInt4); h = false; if ((j != null) && (a(j, this))) { b(j); } j = null; if (!i) { if (v != null) { scrollTo(getScrollX(), v.a); v = null; } if (getChildCount() <= 0) { break label153; } paramInt1 = getChildAt(0).getMeasuredHeight(); paramInt1 = Math.max(0, paramInt1 - (paramInt4 - paramInt2 - getPaddingBottom() - getPaddingTop())); if (getScrollY() <= paramInt1) { break label158; } scrollTo(getScrollX(), paramInt1); } for (;;) { scrollTo(getScrollX(), getScrollY()); i = true; return; label153: paramInt1 = 0; break; label158: if (getScrollY() < 0) { scrollTo(getScrollX(), 0); } } } protected void onMeasure(int paramInt1, int paramInt2) { super.onMeasure(paramInt1, paramInt2); if (!m) {} View localView; do { do { return; } while ((View.MeasureSpec.getMode(paramInt2) == 0) || (getChildCount() <= 0)); localView = getChildAt(0); paramInt2 = getMeasuredHeight(); } while (localView.getMeasuredHeight() >= paramInt2); FrameLayout.LayoutParams localLayoutParams = (FrameLayout.LayoutParams)localView.getLayoutParams(); localView.measure(getChildMeasureSpec(paramInt1, getPaddingLeft() + getPaddingRight(), width), View.MeasureSpec.makeMeasureSpec(paramInt2 - getPaddingTop() - getPaddingBottom(), 1073741824)); } public boolean onNestedFling(View paramView, float paramFloat1, float paramFloat2, boolean paramBoolean) { if (!paramBoolean) { f((int)paramFloat2); return true; } return false; } public boolean onNestedPreFling(View paramView, float paramFloat1, float paramFloat2) { return false; } public void onNestedPreScroll(View paramView, int paramInt1, int paramInt2, int[] paramArrayOfInt) {} public void onNestedScroll(View paramView, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { paramInt1 = getScrollY(); scrollBy(0, paramInt4); paramInt1 = getScrollY() - paramInt1; dispatchNestedScroll(0, paramInt1, 0, paramInt4 - paramInt1, null); } public void onNestedScrollAccepted(View paramView1, View paramView2, int paramInt) { y.a = paramInt; startNestedScroll(2); } protected void onOverScrolled(int paramInt1, int paramInt2, boolean paramBoolean1, boolean paramBoolean2) { super.scrollTo(paramInt1, paramInt2); } protected boolean onRequestFocusInDescendants(int paramInt, Rect paramRect) { int i1; View localView; if (paramInt == 2) { i1 = 130; if (paramRect != null) { break label44; } localView = FocusFinder.getInstance().findNextFocus(this, null, i1); label24: if (localView != null) { break label58; } } label44: label58: while (a(localView)) { return false; i1 = paramInt; if (paramInt != 1) { break; } i1 = 33; break; localView = FocusFinder.getInstance().findNextFocusFromRect(this, paramRect, i1); break label24; } return localView.requestFocus(i1, paramRect); } protected void onRestoreInstanceState(Parcelable paramParcelable) { paramParcelable = (kpl)paramParcelable; super.onRestoreInstanceState(paramParcelable.getSuperState()); v = paramParcelable; requestLayout(); } protected Parcelable onSaveInstanceState() { kpl localkpl = new kpl(super.onSaveInstanceState()); a = getScrollY(); return localkpl; } protected void onScrollChanged(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { super.onScrollChanged(paramInt1, paramInt2, paramInt3, paramInt4); if (c != null) { c.v(); } } protected void onSizeChanged(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { super.onSizeChanged(paramInt1, paramInt2, paramInt3, paramInt4); View localView = findFocus(); if ((localView == null) || (this == localView)) {} while (!a(localView, 0, paramInt4)) { return; } localView.getDrawingRect(b); offsetDescendantRectToMyCoords(localView, b); e(a(b)); } public boolean onStartNestedScroll(View paramView1, View paramView2, int paramInt) { return (paramInt & 0x2) != 0; } public void onStopNestedScroll(View paramView) { y.a = 0; stopNestedScroll(); } public boolean onTouchEvent(MotionEvent paramMotionEvent) { b(); MotionEvent localMotionEvent = MotionEvent.obtain(paramMotionEvent); int i1 = ns.a(paramMotionEvent); if (i1 == 0) { u = 0; } localMotionEvent.offsetLocation(0.0F, u); int i3; int i4; int i2; switch (i1) { case 4: default: case 0: case 2: ViewParent localViewParent; for (;;) { if (l != null) { l.addMovement(localMotionEvent); } localMotionEvent.recycle(); return true; if (getChildCount() == 0) { return false; } if (!d.a()) {} for (boolean bool = true;; bool = false) { k = bool; if (bool) { localViewParent = getParent(); if (localViewParent != null) { localViewParent.requestDisallowInterceptTouchEvent(true); } } if (!d.a()) { d.h(); } g = ((int)paramMotionEvent.getY()); r = ns.b(paramMotionEvent, 0); startNestedScroll(2); break; } i3 = ns.a(paramMotionEvent, r); if (i3 != -1) { break; } i1 = r; Log.e("NestedScrollView", 45 + "Invalid pointerId=" + i1 + " in onTouchEvent"); } i4 = (int)ns.d(paramMotionEvent, i3); i2 = g - i4; i1 = i2; if (dispatchNestedPreScroll(0, i2, t, s)) { i1 = i2 - t[1]; localMotionEvent.offsetLocation(0.0F, s[1]); u += s[1]; } if ((!k) && (Math.abs(i1) > o)) { localViewParent = getParent(); if (localViewParent != null) { localViewParent.requestDisallowInterceptTouchEvent(true); } k = true; if (i1 > 0) { i1 -= o; } } break; } label390: while (k) { g = (i4 - s[1]); int i5 = getScrollY(); i4 = a(); i2 = ok.a(this); if ((i2 == 0) || ((i2 == 1) && (i4 > 0))) {} for (i2 = 1;; i2 = 0) { if ((a(0, i1, 0, getScrollY(), i4)) && (!hasNestedScrollingParent())) { l.clear(); } int i6 = getScrollY() - i5; if (!dispatchNestedScroll(0, i6, 0, i1 - i6, s)) { break label562; } g -= s[1]; localMotionEvent.offsetLocation(0.0F, s[1]); u += s[1]; break; i1 += o; break label390; } label562: if (i2 == 0) { break; } e(); i2 = i5 + i1; if (i2 < 0) { e.a(i1 / getHeight(), ns.c(paramMotionEvent, i3) / getWidth()); if (!f.a()) { f.c(); } } while ((e != null) && ((!e.a()) || (!f.a()))) { ok.c(this); break; if (i2 > i4) { f.a(i1 / getHeight(), 1.0F - ns.c(paramMotionEvent, i3) / getWidth()); if (!e.a()) { e.c(); } } } if (!k) { break; } paramMotionEvent = l; paramMotionEvent.computeCurrentVelocity(1000, q); i1 = (int)og.b(paramMotionEvent, r); if (Math.abs(i1) > p) { f(-i1); } for (;;) { r = -1; d(); break; if (d.b(getScrollX(), getScrollY(), a())) { ok.c(this); } } if ((!k) || (getChildCount() <= 0)) { break; } if (d.b(getScrollX(), getScrollY(), a())) { ok.c(this); } r = -1; d(); break; i1 = ns.b(paramMotionEvent); g = ((int)ns.d(paramMotionEvent, i1)); r = ns.b(paramMotionEvent, i1); break; a(paramMotionEvent); g = ((int)ns.d(paramMotionEvent, ns.a(paramMotionEvent, r))); break; } } public void requestChildFocus(View paramView1, View paramView2) { if (!h) { b(paramView2); } for (;;) { super.requestChildFocus(paramView1, paramView2); return; j = paramView2; } } public boolean requestChildRectangleOnScreen(View paramView, Rect paramRect, boolean paramBoolean) { paramRect.offset(paramView.getLeft() - paramView.getScrollX(), paramView.getTop() - paramView.getScrollY()); int i1 = a(paramRect); if (i1 != 0) {} for (boolean bool = true;; bool = false) { if (bool) { if (!paramBoolean) { break; } scrollBy(0, i1); } return bool; } a(0, i1); return bool; } public void requestDisallowInterceptTouchEvent(boolean paramBoolean) { if (paramBoolean) { c(); } super.requestDisallowInterceptTouchEvent(paramBoolean); } public void requestLayout() { h = true; super.requestLayout(); } public void scrollTo(int paramInt1, int paramInt2) { if (getChildCount() > 0) { View localView = getChildAt(0); paramInt1 = b(paramInt1, getWidth() - getPaddingRight() - getPaddingLeft(), localView.getWidth()); paramInt2 = b(paramInt2, getHeight() - getPaddingBottom() - getPaddingTop(), localView.getHeight()); if ((paramInt1 != getScrollX()) || (paramInt2 != getScrollY())) { super.scrollTo(paramInt1, paramInt2); } } } public void setNestedScrollingEnabled(boolean paramBoolean) { z.a(paramBoolean); } public boolean shouldDelayChildPressedState() { return true; } public boolean startNestedScroll(int paramInt) { return z.a(paramInt); } public void stopNestedScroll() { z.b(); } } /* Location: * Qualified Name: kpi * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
reverseengineeringer/com.google.android.youtube
src/kpi.java
248,083
import android.content.Context; import android.content.res.Resources; import android.graphics.Paint; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.os.Build.VERSION; import android.util.DisplayMetrics; import android.view.animation.Animation.AnimationListener; import android.widget.ImageView; final class vx extends ImageView { Animation.AnimationListener a; int b; public vx(Context paramContext) { super(paramContext); float f = getContextgetResourcesgetDisplayMetricsdensity; int i = (int)(20.0F * f * 2.0F); int j = (int)(1.75F * f); int k = (int)(0.0F * f); b = ((int)(3.5F * f)); if (a()) { paramContext = new ShapeDrawable(new OvalShape()); rg.f(this, f * 4.0F); } for (;;) { paramContext.getPaint().setColor(-328966); setBackgroundDrawable(paramContext); return; paramContext = new ShapeDrawable(new vy(this, b, i)); rg.a(this, 1, paramContext.getPaint()); paramContext.getPaint().setShadowLayer(b, k, j, 503316480); i = b; setPadding(i, i, i, i); } } private static boolean a() { return Build.VERSION.SDK_INT >= 21; } public final void onAnimationEnd() { super.onAnimationEnd(); if (a != null) { a.onAnimationEnd(getAnimation()); } } public final void onAnimationStart() { super.onAnimationStart(); if (a != null) { a.onAnimationStart(getAnimation()); } } protected final void onMeasure(int paramInt1, int paramInt2) { super.onMeasure(paramInt1, paramInt2); if (!a()) { setMeasuredDimension(getMeasuredWidth() + b * 2, getMeasuredHeight() + b * 2); } } public final void setBackgroundColor(int paramInt) { if ((getBackground() instanceof ShapeDrawable)) { ((ShapeDrawable)getBackground()).getPaint().setColor(paramInt); } } } /* Location: * Qualified Name: vx * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
reverseengineeringer/com.google.android.gm
src/vx.java
248,085
import android.animation.ObjectAnimator; import android.os.Build.VERSION; import android.view.View; import android.view.View.MeasureSpec; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AccelerateInterpolator; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.FrameLayout; import com.google.android.gms.people.accountswitcherview.ExpanderView; import com.google.android.gms.people.accountswitcherview.SelectedAccountNavigationView; import com.google.android.gms.people.accountswitcherview.ShrinkingItem; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; public final class frx extends FrameLayout implements View.OnClickListener, AdapterView.OnItemClickListener, fth, ftk { public fsy a; private fry b; private fsa c; private frz d; private fyb e; private List<fyb> f; private FrameLayout g; private SelectedAccountNavigationView h; private fsl i; private ShrinkingItem j; private boolean k; private ViewGroup l; private ExpanderView m; private fsb n; private boolean o; private int p; private int q; private boolean r; private View s; private final void a(View paramView, int paramInt) { paramView.offsetTopAndBottom(paramInt); p = paramView.getTop(); } private final void a(fyb paramfyb, boolean paramBoolean) { Object localObject1 = e; e = paramfyb; if (f != null) { f = fsl.a(f, (fyb)localObject1, e); if (!paramBoolean) { h.a(e); } paramfyb = i; localObject1 = f; if ((d) || ((localObject1 != null) && (((List)localObject1).size() <= 1))) { if (b == null) { b = new ArrayList(); } b.clear(); if (localObject1 != null) { localObject1 = ((List)localObject1).iterator(); while (((Iterator)localObject1).hasNext()) { localObject2 = (fyb)((Iterator)localObject1).next(); b.add(localObject2); } } paramfyb.notifyDataSetChanged(); return; } f = true; Object localObject2 = e; if (e != null) { if (f != null) { f.cancel(true); f = null; } if ((localObject1 != null) && (!((List)localObject1).isEmpty())) { break label229; } e.a(null); } for (;;) { paramfyb.notifyDataSetChanged(); return; label229: b = ((List)localObject1); c.addAll((Collection)localObject1); f = new frw((fru)localObject2); f.execute(new Void[0]); } } h.a(null); } private final void a(boolean paramBoolean, Interpolator paramInterpolator) { int i1; if (paramBoolean) { i1 = 1; } for (int i2 = 0; a(11); i2 = 1) { ObjectAnimator localObjectAnimator = ObjectAnimator.ofFloat(j, "animatedHeightFraction", new float[] { i2, i1 }); localObjectAnimator.setDuration(200L); localObjectAnimator.setInterpolator(paramInterpolator); localObjectAnimator.start(); return; i1 = 0; } paramInterpolator = j; a = i1; paramInterpolator.requestLayout(); } public static boolean a(int paramInt) { return Build.VERSION.SDK_INT >= paramInt; } private final void b(int paramInt) { g.offsetTopAndBottom(paramInt); q = g.getTop(); } private final void c(int paramInt) { l.setPadding(l.getPaddingLeft(), paramInt, l.getPaddingRight(), l.getPaddingBottom()); a.a = paramInt; h.a(paramInt); } public final void a(SelectedAccountNavigationView paramSelectedAccountNavigationView) { switch (h.b) { default: return; case 0: paramSelectedAccountNavigationView = new AlphaAnimation(0.0F, 1.0F); paramSelectedAccountNavigationView.setDuration(200L); g.setAnimation(paramSelectedAccountNavigationView); a(false, new AccelerateInterpolator(0.8F)); g.setVisibility(0); j.setVisibility(8); return; } paramSelectedAccountNavigationView = new AlphaAnimation(1.0F, 0.0F); paramSelectedAccountNavigationView.setDuration(200L); paramSelectedAccountNavigationView.setStartOffset(133L); a(true, new DecelerateInterpolator(0.8F)); g.setVisibility(8); j.setVisibility(0); } public final void a(fyb paramfyb) { a(paramfyb, true); } public final int getNestedScrollAxes() { return 2; } public final void onClick(View paramView) { boolean bool = true; if (paramView == l) { if (n == null) {} } while (paramView != m) { return; } int i1; if (h.b == 1) { i1 = 0; h.c(i1); paramView = m; if (h.b != 1) { break label82; } } for (;;) { paramView.a(bool); a(h); return; i1 = 1; break; label82: bool = false; } } protected final void onDetachedFromWindow() { super.onDetachedFromWindow(); if (s != null) { s.setOnApplyWindowInsetsListener(null); s = null; } } public final void onItemClick(AdapterView<?> paramAdapterView, View paramView, int paramInt, long paramLong) { if (i.getItemViewType(paramInt) == 0) { if (d != null) { paramAdapterView = d; i.a(paramInt); if (!paramAdapterView.a()) {} } } do { do { return; a(i.a(paramInt), false); } while (b == null); return; if (i.getItemViewType(paramInt) != 1) { break; } } while (c == null); return; i.getItemViewType(paramInt); } protected final void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { super.onLayout(paramBoolean, paramInt1, paramInt2, paramInt3, paramInt4); if (k) {} for (Object localObject = l;; localObject = h) { if (p != ((View)localObject).getTop()) { ((View)localObject).offsetTopAndBottom(p - ((View)localObject).getTop()); } if (q != g.getTop()) { g.offsetTopAndBottom(q - g.getTop()); } return; } } public final void onMeasure(int paramInt1, int paramInt2) { super.onMeasure(paramInt1, paramInt2); paramInt2 = 0; for (;;) { if (paramInt2 < getChildCount()) { if (!getChildAt(paramInt2).equals(g)) { break label119; } if (!k) { break label103; } paramInt2 = l.getMeasuredHeight(); g.setPadding(g.getPaddingLeft(), paramInt2, g.getPaddingRight(), g.getPaddingBottom()); if (!o) { break label114; } } for (;;) { g.measure(paramInt1, paramInt2 + View.MeasureSpec.makeMeasureSpec(getMeasuredHeight(), 1073741824)); return; label103: paramInt2 = h.getMeasuredHeight(); break; label114: paramInt2 = 0; } label119: paramInt2 += 1; } } public final boolean onNestedFling(View paramView, float paramFloat1, float paramFloat2, boolean paramBoolean) { if (k) {} for (paramView = l; (!paramBoolean) && (paramFloat2 < 0.0F) && (paramView.getBottom() < 0); paramView = h) { a(paramView, -paramView.getTop()); b(-paramView.getTop()); return true; } if ((paramBoolean) && (paramFloat2 > 0.0F)) { if (paramView.getTop() > -paramView.getMeasuredHeight()) { a(paramView, -paramView.getMeasuredHeight() - paramView.getTop()); } if (g.getTop() > -paramView.getMeasuredHeight()) { b(-paramView.getMeasuredHeight() - g.getTop()); } } return false; } public final void onNestedPreScroll(View paramView, int paramInt1, int paramInt2, int[] paramArrayOfInt) { if (k) { paramView = l; if (h.b != 1) { break label32; } } for (;;) { return; paramView = h; break; label32: if ((paramInt2 > 0) && (paramView.getBottom() > 0)) { if (paramView.getBottom() > paramInt2) { paramInt1 = -paramInt2; } } while (paramInt1 != 0) { if (paramView.getTop() + paramInt1 < -paramView.getMeasuredHeight()) { a(paramView, -paramView.getMeasuredHeight() - paramView.getTop()); label87: if (g.getTop() + paramInt1 >= -paramView.getMeasuredHeight()) { break label150; } b(-paramView.getMeasuredHeight() - g.getTop()); } for (;;) { paramArrayOfInt[0] = 0; paramArrayOfInt[1] = paramInt1; return; paramInt1 = -paramView.getBottom(); break; a(paramView, paramInt1); break label87; label150: b(paramInt1); } paramInt1 = 0; } } } public final void onNestedScroll(View paramView, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { if (k) { paramView = l; if ((paramInt4 >= 0) || (paramView.getTop() >= 0)) { break label122; } paramInt1 = paramInt4; if (paramInt4 > paramView.getTop()) {} } label105: label115: label122: for (paramInt1 = paramView.getTop();; paramInt1 = 0) { if (paramInt1 != 0) { if (paramView.getTop() - paramInt1 <= 0) { break label105; } a(paramView, -paramView.getTop()); } for (;;) { if (g.getTop() - paramInt1 <= paramView.getMeasuredHeight()) { break label115; } b(paramView.getMeasuredHeight() - g.getTop()); return; paramView = h; break; a(paramView, -paramInt1); } b(-paramInt1); return; } } public final boolean onStartNestedScroll(View paramView1, View paramView2, int paramInt) { return o; } public final void setPadding(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { int i1 = paramInt2; if (r) { c(paramInt2); i1 = 0; } super.setPadding(paramInt1, i1, paramInt3, paramInt4); } public final void setPaddingRelative(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { int i1 = paramInt2; if (r) { c(paramInt2); i1 = 0; } super.setPaddingRelative(paramInt1, i1, paramInt3, paramInt4); } } /* Location: * Qualified Name: frx * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
reverseengineeringer/com.google.android.gm
src/frx.java
248,086
import android.content.Context; import android.graphics.Bitmap; import android.util.AttributeSet; import android.widget.RatingBar; public final class agw extends RatingBar { private agv a = new agv(this, b); private agj b = agj.a(); public agw(Context paramContext, AttributeSet paramAttributeSet) { this(paramContext, paramAttributeSet, aca.J); } private agw(Context paramContext, AttributeSet paramAttributeSet, int paramInt) { super(paramContext, paramAttributeSet, paramInt); a.a(paramAttributeSet, paramInt); } protected final void onMeasure(int paramInt1, int paramInt2) { try { super.onMeasure(paramInt1, paramInt2); Bitmap localBitmap = a.b; if (localBitmap != null) { setMeasuredDimension(rg.a(localBitmap.getWidth() * getNumStars(), paramInt1, 0), getMeasuredHeight()); } return; } finally {} } } /* Location: * Qualified Name: agw * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
reverseengineeringer/com.google.android.gm
src/agw.java
248,087
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Scanner; import java.awt.*; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class Start { public static void main(String[] args) { System.out.println(); Scanner in = new Scanner(System.in); String sat_file = "C:" + "\\" + "Users" + "\\" + "nicpalme" + "\\" + "Documents" + "\\" + "SATtest" + "\\" + in.nextLine(); List<String> sat_text = new ArrayList<>(); List<variable> vList = new ArrayList<>(); List<clause> listOfClauses = new ArrayList<>(); int varNum; List<variable> givenL = new ArrayList<>(); try { ReadFile file = new ReadFile(sat_file); String[] lines = file.OpenFile(); int space1 = lines[0].indexOf(" "); String line0a = lines[0].substring(space1+1, lines[0].length()); int space2 = line0a.indexOf(" "); String line0b = line0a.substring(space2+1, line0a.length()); int space3 = line0b.indexOf(" "); String line0c = line0b.substring(0, space3); // System.out.println(lines[0]); // System.out.println(line0a); // System.out.println(line0b); // System.out.println(line0c); varNum = Integer.parseInt(line0c); int k = 0; while(k < varNum) { vList.add(new variable(Integer.toString(k+1))); k++; } // System.out.println(varNum); int i; for (i=0; i<lines.length; i++) { sat_text.add(lines[i]); if(i != 0) { listOfClauses.add(new clause(getVars(lines[i]))); // System.out.println(listOfClauses.get(i-1).cToString()); } System.out.println(sat_text.get(i)); } int j = 0; while(j < listOfClauses.size()) { String c = clauseToString(listOfClauses, j); // System.out.println("line " + (j+1) + " is: " + c); // System.out.println(listOfClauses.get(j).cToString()); j++; } } catch(IOException e) { System.out.println(e.getMessage()); } /* List<String> test = new ArrayList<>(); test.add("1"); test.add("2"); test.add("3"); clause c = new clause(test); System.out.println(c.cToString()); */ // System.out.println("Line 1 is " + v); // System.out.println(sat_text.get(3)); System.out.println(""); System.out.println(""); System.out.println(""); System.out.println("Possible Solution"); System.out.println(""); checkNeg(listOfClauses); givens(listOfClauses, vList, givenL); entering(listOfClauses, vList); //verifyLC(listOfClauses); showVList(vList); boolean x; x = changing(listOfClauses, vList, givenL, 0); //System.out.println(x); if (x == false) System.out.println("NO"); System.out.println("----------- "); /*verifyLC(listOfClauses); verifySAT(listOfClauses); System.out.println("----------- "); showVList(vList); if(verifySAT(listOfClauses)) { showVList(vList); } else { System.out.println("No"); } System.out.println("Second check: "); givens(listOfClauses, vList, givenL); showVList(vList); System.out.println("Third check: "); assignBool(listOfClauses, vList); checkNeg(listOfClauses); System.out.println("Fourth check: "); simplify(listOfClauses, vList); check(listOfClauses); System.out.println("Fifth check: "); verifyLC(listOfClauses); verifySAT(listOfClauses); // variable v = new variable("1"); */ } public static List<variable> getVars(String s) { List<variable> listOfVars = new ArrayList<>(); while(!s.equals("0")) { int space = s.indexOf(" "); // System.out.println(s); // System.out.println("space - " + space); listOfVars.add(new variable(s.substring(0, space))); s = s.substring(space+1, s.length()); } return listOfVars; } /*public static String varsToString(List<String> listOfVars) { String vars = ""; int i=0; while(i < listOfVars.size()) { vars = vars + " " + listOfVars.get(i); i++; } return vars; }*/ public static void entering(List<clause> listOfClauses, List<variable> vList) { int i = 0; while (i < listOfClauses.size()) { int j = 0; while (j < listOfClauses.get(i).size()) { int m = 0; while (m < vList.size()) { if(listOfClauses.get(i).get(j).naming().equals(vList.get(m).naming())) { listOfClauses.get(i).get(j).chngbool(vList.get(m).getbool()); listOfClauses.get(i).get(j).negative(); } m++; } j++; } i++; } } public static String clauseToString(List<clause> listOfClauses, int num) { String clause = ""; int i=0; while(i < listOfClauses.size()) { listOfClauses.get(num).cToString(); i++; } return clause; } public static List<clause> assignBool(List<clause> listOfClauses, List<variable> vList) { int i = 0; while(i < listOfClauses.size()) { int j = 0; while(j < listOfClauses.get(i).size()) { int k = 0; while(k < vList.size()) { if(listOfClauses.get(i).get(j).naming().equals(vList.get(k).naming())) { if(!vList.get(k).getbool()) { listOfClauses.get(i).get(j).False(); } else { listOfClauses.get(i).get(j).True(); } } k++; } j++; } i++; } return listOfClauses; } public static List<clause> checkNeg(List<clause> listOfClauses) { int i = 0; while(i < listOfClauses.size()) { int j = 0; while(j < listOfClauses.get(i).size()) { listOfClauses.get(i).get(j).negative(); //System.out.println(listOfClauses.get(i).get(j).toString()); j++; } i++; } return listOfClauses; } public static void check(List<clause> listOfClauses) { int i = 0; while(i < listOfClauses.size()) { System.out.println(listOfClauses.get(i).viewC()); i++; } } public static List<variable> assignV(List<variable> vList, String s, boolean b) { int i = 0; while(i < vList.size()) { if(vList.get(i).naming().equals(s)) { if(b) { vList.get(i).True(); } else { vList.get(i).False(); } } i++; } return vList; } public static void showVList(List<variable> vList) { int i = 0; while(i < vList.size()) { System.out.println(vList.get(i).toString()); i++; } } public static List<clause> givens(List<clause> listOfClauses, List<variable> vList, List<variable> givenL) { int i = 0; while(i < listOfClauses.size()) { if(listOfClauses.get(i).size() == 1) { givenL.add(listOfClauses.get(i).get(0)); String s = listOfClauses.get(i).get(0).naming(); boolean b = listOfClauses.get(i).get(0).getbool(); assignV(vList, s, !b); } i++; } return listOfClauses; } public static List<clause> simplify(List<clause> listOfClauses, List<variable> vList) { List<clause> tempC = new ArrayList<>(); int i = 0; while(i < listOfClauses.size()) { int j = 0; while(j < listOfClauses.get(i).size()) { int k = 0; while(k < vList.size()) { if(listOfClauses.get(i).get(j).naming().equals(vList.get(k).naming()) && vList.get(k).getbool()) { List<variable> temp = new ArrayList<>(); if(!listOfClauses.get(i).get(j).getbool()) { temp.add(listOfClauses.get(i).get(j)); tempC.add(new clause(temp)); } } k++; } j++; } i++; } listOfClauses = tempC; return listOfClauses; } public static void verifyLC(List<clause> listOfClauses) { int i = 0; while(i < listOfClauses.size()) { System.out.println(listOfClauses.get(i).verifyC()); i++; } } public static boolean verifySAT(List<clause> listOfClauses) { boolean b = true; int i = 0; while(i < listOfClauses.size()) { if(!listOfClauses.get(i).solvedC()) { b = false; } i++; } //System.out.println("SAT solved? " + b); return b; } public static boolean changing(List<clause> listOfClauses, List<variable> vList, List<variable> givenL, int pos) { /* int i = 0; while(i < vList.size() && !verifySAT(listOfClauses)) { String g = ""; int j = 0; while(j < givenL.size()) { if(vList.get(i).naming().equals(givenL.get(j).naming())) { g = g + givenL.get(j).naming(); } j++; } if(!vList.get(i).naming().equals(g)) { if(!vList.get(i).getbool()) { vList.get(i).True(); } else { vList.get(i).False(); } } listOfClauses = assignBool(listOfClauses, vList); i++; } return vList;*/ entering(listOfClauses, vList); if (verifySAT(listOfClauses)) { List<variable> zList = new ArrayList<>(); int i = 0; while(i < vList.size()) { zList.add(vList.get(i)); i++; } showVList(zList); verifyLC(listOfClauses); return true; } else if (vList.size() <= pos+1) { return false; } else { int j = 0; int x = 0; while (j < givenL.size()) { if(vList.get(pos).naming().equals(givenL.get(j).naming())) { pos++; x++; changing(listOfClauses, vList, givenL, pos); } j++; } if(x == 0){ //showVList(vList); //verifyLC(listOfClauses); List<variable> lList = new ArrayList<>(); int i = 0; while(i < vList.size()) { lList.add(vList.get(i)); i++; } if(!lList.get(pos).getbool()) { lList.get(pos).True(); } else { lList.get(pos).False(); } pos++; return changing(listOfClauses, vList, givenL, pos) || changing(listOfClauses, lList, givenL, pos); } else return false; } } }
hpmsora/Project---Java-SAT-Solver
Start.java
248,094
public class arr21 { public static int removeDuplicateElements(int arr[], int n){ if (n==0 || n==1){ return n; } int[] temp = new int[n]; int j = 0; for (int i=0; i<n-1; i++){ if (arr[i] != arr[i+1]){ temp[j++] = arr[i]; } } temp[j++] = arr[n-1]; // Changing original array for (int i=0; i<j; i++){ arr[i] = temp[i]; } return j; } public static void main (String[] args) { int arr[] = {10,20,20,30,30,40,50,50}; int length = arr.length; length = removeDuplicateElements(arr, length); //printing array elements for (int i=0; i<length; i++) System.out.print(arr[i]+" "); } }
MainakRepositor/Java-Fantasy
arr21.java
248,096
public class Remove{ public static int removeDuplicateElements(int arr[], int n){ if (n==0 || n==1){ return n; } int[] temp = new int[n]; int j = 0; for (int i=0; i<n-1; i++){ if (arr[i] != arr[i+1]){ temp[j++] = arr[i]; } } temp[j++] = arr[n-1]; // Changing original array for (int i=0; i<j; i++){ arr[i] = temp[i]; } return j; } public static void main (String[] args) { int arr[] = {10,20,20,30,30,40,50,50}; int length = arr.length; length = removeDuplicateElements(arr, length); //printing array elements for (int i=0; i<length; i++) System.out.print(arr[i]+" "); } }
LogicDecode/hactoberfest2023
Remove.java
248,099
import java.io.*; class service { public void menu()throws Exception { while(true) { System.out.println("Enter 1 to Create New Account."); System.out.println("Enter 2 for Deposit."); System.out.println("Enter 3 for Withdrawl."); System.out.println("Enter 4 for MiniStatement"); System.out.println("Enter 5 for Balance Enquiry."); System.out.println("Enter 6 for Changing Password."); System.out.println("Enter 7 for Account Details."); System.out.println("Enter 8 to Exit."); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter your Choice."); int choice=Integer.parseInt(br.readLine()); UserAccount uc=new UserAccount(); Transaction t=new Transaction(); switch(choice) { case 1: uc.createAccount(); break; case 2: t.deposit(); break; case 3: t.withdrawal(); break; case 4: t.ministatement(); break; case 5: t.balcheck(); break; case 6: uc.changepass(); break; case 7: uc.AccDetails(); break; case 8: System.exit(0); } } } }
kumarcodes/Banking-Management-System
service.java
248,100
404: Not Found
Mohitraj27/Consistency
Day_4.java
248,105
package com.example.thecasino; import android.app.Activity; import java.util.*; //import com.example.theblackjackapp.*; public class Hand { private Vector<Card> hand; public Hand() { hand = new Vector<Card>(); } public int size() { return hand.size(); } public void addCard( Card card ) { hand.add(card); } public Card getCard(int position) { // Get the card from the hand in given position, where positions // are numbered starting from 0. If the specified position is // not the position number of a card in the hand, then null // is returned. Card selectedCard = null; if( position >= 0 || position < hand.size()) { selectedCard = hand.get(position); } return selectedCard; } public int value() { // Returns the value of this hand for the // game of Blackjack. int handValue = 0; // The value computed for the hand. boolean hasAce = false; // This will be set to true if the // hand contains an ace. Iterator<Card> iter = hand.iterator(); while( iter.hasNext() ) { Card card = iter.next(); if( card.rank() == Card.Rank.ACE) { hasAce = true; } handValue += card.value(); } // Now, handValue is the value of the hand, counting any ace as 1. // If there is an ace, and if changing its value from 1 to // 11 would leave the score less than or equal to 21, // then do so by adding the extra 10 points to handValue. if (hasAce == true && handValue + 10 <= 21) { handValue += 10; } return handValue; } }
dmrodger/BUS-498-Android-Final-Project-Casino
Hand.java
248,107
public class string { public static void main(String[] args) { String s = "GeeksforGeeks"; System.out.println("String length = " + s.length()); System.out.println("Character at 3rd position = " + s.charAt(3)); System.out.println("Substring " + s.substring(3)); System.out.println("Substring = " + s.substring(2, 5)); String s1 = "Geeks"; String s2 = "forGeeks"; System.out.println("Concatenated string = " + s1.concat(s2)); String s4 = "Learn Share Learn"; System.out.println("Index of Share " + s4.indexOf("Share")); System.out.println("Index of a = " + s4.indexOf('a', 3)); Boolean out = "Geeks".equals("geeks"); System.out.println("Checking Equality " + out); out = "Geeks".equals("Geeks"); System.out.println("Checking Equality " + out); out = "Geeks".equalsIgnoreCase("gEeks "); System.out.println("Checking Equality " + out); int out1 = s1.compareTo(s2); System.out.println("the difference between ASCII value is=" + out1); String word1 = "GeeKyMe"; System.out.println("Changing to lower Case " + word1.toLowerCase()); String word2 = "GeekyME"; System.out.println("Changing to UPPER Case " + word2.toUpperCase()); String word4 = " Learn Share Learn "; System.out.println("Trim the word " + word4.trim()); String str1 = "feeksforfeeks"; System.out.println("Original String " + str1); String str2 = "feeksforfeeks".replace('f', 'g'); System.out.println("Replaced f with g -> " + str2); } }
Rohan-San/Java-Lab
string.java
248,109
/** A simple interface (simpler than List) for accessing random-access objects without changing their size. Adhered to by Bag, IntBag, and DoubleBag */ public interface Indexed { /** Should return the base component type for this Indexed object, or null if the component type should be queried via getValue(index).getClass.getComponentType() */ public Class componentType(); public int size(); /** Throws an IndexOutOfBoundsException if index is inappropriate, and IllegalArgumentException if the value is inappropriate. Not called set() in order to be consistent with getValue(...)*/ public Object setValue(final int index, final Object value) throws IndexOutOfBoundsException, IllegalArgumentException; /** Throws an IndexOutOfBoundsException if index is inappropriate. Not called get() because this would conflict with get() methods in IntBag etc. which don't return objects. */ public Object getValue(final int index); }
MathOnco/PCASim
Indexed.java
248,118
/* 2370. Longest Ideal Subsequence You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied: t is a subsequence of the string s. The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k. Return the length of the longest ideal string. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25, not 1. Example 1: Input: s = "acfgbd", k = 2 Output: 4 Explanation: The longest ideal string is "acbd". The length of this string is 4, so 4 is returned. Note that "acfgbd" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order. Example 2: Input: s = "abcd", k = 3 Output: 4 Explanation: The longest ideal string is "abcd". The length of this string is 4, so 4 is returned. Constraints: 1 <= s.length <= 105 0 <= k <= 25 s consists of lowercase English letters. */ class Solution { public int longestIdealString(String s, int k) { // dp[i] := the longest subsequence that ends in ('a' + i) int[] dp = new int[26]; for (final char c : s.toCharArray()) { final int i = c - 'a'; dp[i] = 1 + getMaxReachable(dp, i, k); } return Arrays.stream(dp).max().getAsInt(); } private int getMaxReachable(int[] dp, int i, int k) { final int first = Math.max(0, i - k); final int last = Math.min(25, i + k); int maxReachable = 0; for (int j = first; j <= last; ++j) maxReachable = Math.max(maxReachable, dp[j]); return maxReachable; } }
sugaryeuphoria/LeetCode-100-Days-of-Code
Day114.java
248,119
/*1208. Get Equal Substrings Within Budget * You are given two strings s and t of the same length and an integer maxCost. You want to change s to t. Changing the ith character of s to ith character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters). Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0. Example 1: Input: s = "abcd", t = "bcdf", maxCost = 3 Output: 3 Explanation: "abc" of s can change to "bcd". That costs 3, so the maximum length is 3. Example 2: Input: s = "abcd", t = "cdef", maxCost = 3 Output: 1 Explanation: Each character in s costs 2 to change to character in t, so the maximum length is 1. Example 3: Input: s = "abcd", t = "acde", maxCost = 0 Output: 1 Explanation: You cannot make any change, so the maximum length is 1. Constraints: 1 <= s.length <= 105 t.length == s.length 0 <= maxCost <= 106 s and t consist of only lowercase English letters. */ class Solution { public int equalSubstring(String s, String t, int maxCost) { int j = 0; for (int i = 0; i < s.length(); ++i) { maxCost -= Math.abs(s.charAt(i) - t.charAt(i)); if (maxCost < 0) maxCost += Math.abs(s.charAt(j) - t.charAt(j++)); } return s.length() - j; } }
sugaryeuphoria/LeetCode-100-Days-of-Code
Day140.java
248,121
404: Not Found
Tusharnagpal18/Coding22
LC#1323.java
248,136
import processing.core.PApplet; public class Sketch extends PApplet { /** * A code that prints a screen covered in spiders with various sizes * @author: T. Chhor * */ public void settings() { // put your size call here size(400, 400); } public void setup() { background(210, 255, 173); } public void draw() { // Initializing variables float floatXCoord; float floatYCoord; float floatSize = 20; int intSpiderColour = 0; // The for loop that prints the spider in various locations for (floatXCoord = 40; floatXCoord < 400; floatXCoord += 40) { for (floatYCoord = 40; floatYCoord < 400; floatYCoord += 40) { intSpiderColour += 3; floatSize += 1; // If the mouse is pressed, then the colour will print differently if (mousePressed) { drawSpider(floatXCoord, floatYCoord, floatSize, changingColour(floatXCoord, floatYCoord)); } else { drawSpider(floatXCoord, floatYCoord, floatSize, intSpiderColour); } fill(250, 20, 90); } } // Drawing the dot for (floatXCoord = 40; floatXCoord < 400; floatXCoord += 40) { for (floatYCoord = 40; floatYCoord < 400; floatYCoord += 40) { drawDot(floatXCoord + 5, floatYCoord + 15); } } } /** * Draws a spider based on inputs on location, size and colour * * @param floatSpiderX The X value of where the Spider will be printed * @param floatSpiderY The Y value of where the Spider will be printed * @param floatSpiderSize The size of the Spider * @param intSpiderColour The colour of the Spider */ private void drawSpider(float floatSpiderX, float floatSpiderY, float floatSpiderSize, int intSpiderColour) { // Head fill(intSpiderColour); ellipse(floatSpiderX,floatSpiderY, floatSpiderSize, (float) (floatSpiderSize / 1.5)); // Eyes fill(255, 255, 255); ellipse(floatSpiderX - floatSpiderSize / 5, floatSpiderY - floatSpiderY / 30, floatSpiderSize / 10, floatSpiderSize / 10); ellipse(floatSpiderX + floatSpiderSize / 5, floatSpiderY - floatSpiderY / 30, floatSpiderSize / 10, floatSpiderSize / 10); ellipse(floatSpiderX - floatSpiderSize / 10, floatSpiderY - floatSpiderY / 30, floatSpiderSize / 10, floatSpiderSize / 10); ellipse(floatSpiderX + floatSpiderSize / 10, floatSpiderY - floatSpiderY / 30, floatSpiderSize / 10, floatSpiderSize / 10); // Legs fill(intSpiderColour); line(floatSpiderX + floatSpiderSize / 2, floatSpiderY, floatSpiderX + floatSpiderSize, floatSpiderY + floatSpiderSize); line(floatSpiderX - floatSpiderSize / 2, floatSpiderY, floatSpiderX - floatSpiderSize, floatSpiderY + floatSpiderSize); line(floatSpiderX + floatSpiderSize / 4, floatSpiderY + floatSpiderSize / 4, floatSpiderX + floatSpiderSize / 2, floatSpiderY + floatSpiderSize); line(floatSpiderX - floatSpiderSize / 4, floatSpiderY + floatSpiderSize / 4, floatSpiderX - floatSpiderSize / 2, floatSpiderY + floatSpiderSize); } /** * Draws a series of dots based on location inputs * * @param floatDotX The X coordinate of the dot * @param floatDotY The Y coordinate of the dot */ private void drawDot(float floatDotX, float floatDotY){ ellipse(floatDotX, floatDotY, 5, 5); ellipse(floatDotX + 3, floatDotY, 5, 5); ellipse(floatDotX + 3/2, floatDotY + 3/2, 5, 5); ellipse(floatDotX, floatDotY + 3, 5, 5); ellipse(floatDotX - 3/2, floatDotY + 3/2, 5, 5); ellipse(floatDotX - 3, floatDotY, 5, 5); ellipse(floatDotX - 3/2, floatDotY - 3/2, 5, 5); ellipse(floatDotX, floatDotY - 3, 5, 5); ellipse(floatDotX + 3/2, floatDotY - 3/2, 5, 5); } /** * Given the X and Y coordinate, returns a value that is the addition of the two of them divided by 2 * * @param floatFirstQuality The X Coordinate * @param floatSecondQuality The Y Coordinate * @return The new value */ private int changingColour(float floatFirstQuality, float floatSecondQuality){ int newColourValue = (int)(floatFirstQuality / 2) + (int)(floatSecondQuality / 2); return newColourValue; } }
SACHSTech/processing-task-6-creatingmethods-Tim-o-c
Sketch.java
248,142
package warehouse; import java.util.*; /** * @author Mouna Elkeurti * Bin class moves bins with the order from the picker to the packer then * from the packer to the dock location to get it shipped */ public class Belt implements Event{ boolean moving; double speed = 0.0; private Bin bin; int tick =0; Order order; public Belt(){} /** * @author Mouna Elkeurti * @param x is the speed of which the belt is moving with * pausing, starting and changing the speed of the belt */ void changeSpeed(double x){ speed = x; } /** * @author Mouna Elkeurti * pausing the belt to leave time for the picker to add bin on the bell then restart it */ void pause(){ speed = 0; } void start(double x){ speed = x; } boolean ismoving(){ tick++; moving = true; } ArrayList<Bin> binOnBelt = new ArrayList<>(); /** * @author Mouna Elkeurti * @param bins are added to the belt * the picker add bins to the belt to the packer */ void add(Bin bin){ tick =0; pause(); binOnBelt.add(bin); ismoving(); } /** * @author Mouna Elkeurti * @param bins are removed from the belt * bin is removed from the belt once it arrives to the dock location */ void remove(Bin bin){ tick =0; binOnBelt.remove(binOnBelt.size()-1); ismoving(); } ArrayList<Order> orderOnBelt = new ArrayList<>(); /** * @author Mouna Elkeurti * @param orders are added to the belt * method can be used by order to add a new order in the belt or romove it to go to the dock */ void addOrder(Order order){ orderOnBelt.add(order); } /** * @author Mouna Elkeurti * Order arrives the to the shipping dock */ void removeOrder(Order order){ orderOnBelt.remove(orderOnBelt.size()-1); } void scan(){ tick =0; pause(); getOrderID(); } void pack(){ pause(); tick =0; order_belt = true; } } /** * @author Mouna Elkeurti * bins are tracked, when they are in the belt when the bins arrives to the end of belt */ class Bin { int binNum; boolean onBelt = false; boolean order_Belt = false; Order order; public Bin(){ Bin bin = new Bin(); } /** * @author Mouna Elkeurti * Order are put on the belt */ public boolean bin_full(){ return order_Belt = true; } }
hekemp/Warehouse
Belt.java
248,154
import javax.swing.*; import java.awt.*; import java.awt.event.*; class TimerWindow extends JFrame implements ActionListener{ //creation of an window using JFrame private int start = 1; private JButton jbtn; //creation of button inside the JFrame window private Timer swingtimer; //swing timer instance TimerWindow(int tm) { start += tm; setTitle("Timer Window"); setLayout(new FlowLayout()); setTimer(); setSize(700,350); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private void setTimer() { jbtn = new JButton("Staring Timer..."); add(jbtn); swingtimer = new Timer(2222,this); swingtimer.start(); } public void actionPerformed(ActionEvent evnt) { start--; if(start>=1) { jbtn.setText("Time : "+start); //changing the label of button as the timer decrases }else{ jbtn.setText("Timeout... Now,Close the Window"); swingtimer.stop(); } } } public class timer { static public void main(String[] args) { TimerWindow tw = new TimerWindow(5); } }
anirbang324/java-programs
timer.java
248,156
package com.lud.root.jetfighter; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Rect; import java.util.Random; public class Enemy { private int x; private int y; private int speed = -1; private int radius = 20; private int maxX, minX; private int maxY, minY; //Create a rect object to detect collision private Rect detectCollision; public Enemy(Context context, int screenX, int screenY){ maxX = screenX; maxY = screenY; minX = 0; minY = 0; // Randomly generating enemy position Random generator = new Random(); speed = 25; radius = 35; x = screenX; y = generator.nextInt(maxY) + 10 - radius; } public Enemy(Context context, int screenX, int screenY, int prevY, int prevRad){ maxX = screenX; maxY = screenY; minX = 0; minY = 0; // Randomly generating enemy position Random generator = new Random(); speed = 25; radius = 35; x = screenX; do{ y = generator.nextInt(maxY) + 10 - radius; }while ((y - prevY) < (prevRad + radius + 60)); } public void update(int playerSpeed){ // As the enemy moves from right to left x -= playerSpeed; x -= speed; Random generator = new Random(); if(x < minX - this.getRadius()){ speed = generator.nextInt(10) + 10; radius = generator.nextInt(20) + 30; x = maxX; y = generator.nextInt(maxY) - radius; } } //This setter is used for changing the x coordinate after collision public void setX(int x) { this.x = x; } public Rect getDetectCollision() { return detectCollision; } public int getSpeed() { return speed; } public int getY() { return y; } public int getX() { return x; } public int getRadius() { return radius; } }
LuD1161/AndroidGame-CrashyBall
Enemy.java
248,157
public class tut_32 { static void foo() { System.out.println("Good morning broo!"); } static void foo(int a) { System.out.println("Good morning " + a + " broo!"); } static void foo(int a, int b) { System.out.println("Good morning " + a + " broo!"); System.out.println("Good morning " + b + " broo!"); } static void change(int a) { a = 98; } static void change2(int[] arr) { arr[0] = 98; } static void telljoke() { System.out.println("I invented a new word!\n" + "Plagiarism!"); } public static void main(String[] args) { // telljoke(); // int[] marks = { 77, 86, 95, 78, 87, 75 }; // Case 1: Changing the Integer // int x = 45; // change(x); // System.out.println("The value of x after running is: " + x); // Case 2: Changing the Array // int[] marks = { 77, 86, 95, 78, 87, 75 }; // change2(marks); // System.out.println("The value of marks after running is: " + marks[0]); // METHOD OVERLOADING foo(); foo(5); foo(5, 6); } }
piyush168713/Core-Java
tut_32.java
248,159
/* PROBLEM STATEMENT * A lot of people are snooping on you and reading your texts. You plan to encrypt it using a transposition cipher. Write a program that can both encrypt and decrypt the messages. It will accept a string, and a choice of whether to encrypt or decrypt it. * * Transposition cipher works by changing the position of the letters in the sentence. Break down the sentence into a square [Floor value. For 9 characters it is 3x3, for 12 it is 3x3 + 3, for 14 it is 3x3 + 5] (If there are extra characters, add them to the bottom of the square and convert them to *) and use the algorithm to get the encrypted and decrypted text. * * For Example: * “lets go geocaching” can be broken into : * * l e t s * g o g e * o c a c * h i n g * * The encrypted text will be lgoheocitgansecg. * * HRUNDOEDGEWYOD*AOIU* can be broken into : * * H R U N D * O E D G E * W Y O D * * A O I U * * * The decrypted text will be HOWAREYOUDOINGDUDE. * */ public class Answer { public static void main(String[] args){ //Create a GUI for the problem where the user decides GuiFrame frame = new GuiFrame(); //call the createWindow method in the gui class frame.createWindow(); } }
laszer25/Cipher-Texts
Answer.java
248,163
import java.io.*; // Java code to demonstrate right star triangle public class pattern { // Function to demonstrate printing pattern public static void StarRightTriangle(int n) { int a, b; // outer loop to handle number of rows // k in this case for (a = 0; a < n; a++) { // inner loop to handle number of columns // values changing acc. to outer loop for (b = 0; b <= a; b++) { // printing stars System.out.print("* "); } // end-line System.out.println(); } } // Driver Function public static void main(String args[]) { int k = 5; StarRightTriangle(k); } }
Abhay69/DSA-problems-and-algo
pattern.java
248,164
import java.util.Scanner; abstract class Student implements getDetails{ protected String name; protected int Roll; protected int year; protected String branch; Student(String name, int roll_no, int year, String branch) { this.name = name; this.Roll = roll_no; this.year = year; this.branch = branch; } public void show_Details() { System.out.println("Name : \t" + this.name); System.out.println("Roll : \t" + this.Roll); System.out.println("Year : \t" + this.year); System.out.println("Branch : \t" + this.branch); System.out.println(); System.out.println(); } public void update_Details() { System.out.println("Availaible Choices: "); System.out.println("0. Exit"); System.out.println("1. Name"); System.out.println("2. Roll"); System.out.println("3. Year"); System.out.println("4. Branch"); Scanner sc = new Scanner(System.in); boolean changing_details = true; while (changing_details) { System.out.print("Choice : "); int choice = sc.nextInt(); sc.nextLine(); if (choice == 0) { changing_details = false; System.out.println(); sc.close(); } else { System.out.print("Enter Detail: "); if (choice == 1) { String name = sc.nextLine(); this.name = name; } else if (choice == 2) { int Roll = sc.nextInt(); sc.nextLine(); this.Roll = Roll; } else if (choice == 3) { int year = sc.nextInt(); sc.nextLine(); this.year = year; } else if (choice == 4) { String branch = sc.nextLine(); this.branch = branch; } else { System.out.println("Error! enter correct choice. "); } } } } }
ChaudharyAnsh/MA104-java-Project
Student.java
248,170
import java.awt.*; import java.awt.event.*; import java.awt.print.*; import java.io.BufferedWriter; import java.io.IOException; import java.util.*; import javax.swing.*; import java.awt.FontMetrics; // Written by: Michael Zimmer - [email protected] /* Copyright 2007 Zimmer Design Services This file is part of Fizzim. Fizzim 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 3 of the License, or (at your option) any later version. Fizzim 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, see <http://www.gnu.org/licenses/>. */ public class DrawArea extends JPanel implements MouseListener, MouseMotionListener, ActionListener,Printable { //holds all objects to be currently drawn private Vector<Object> objList; //holds previous lists of objects private Vector<Vector<Object>> undoList; //temp lists private Vector<Object> tempList; //keeps track of current position in undo array private int currUndoIndex; //triggered when undo needs to be committed private boolean toCommit = false; // hold right click position private int rXTemp, rYTemp; //hold clicked state private GeneralObj tempObj; private GeneralObj tempOld; private GeneralObj tempClone; //for multiple object select private boolean multipleSelect = false; private boolean objsSelected = false; private int mXTemp = 0; private int mYTemp = 0; private int mX0,mY0,mX1,mY1; private LinkedList<Integer> selectedIndices = new LinkedList<Integer>(); private boolean ctrlDown = false; //font private Font currFont = new Font("Arial",Font.PLAIN,11); private Font tableFont = new Font("Arial",Font.PLAIN,11); //global color chooser private JColorChooser colorChooser = new JColorChooser(); private boolean loading = false; private boolean Redraw = false; //default settings for global table private boolean tableVis = true; private Color tableColor = Color.black; private Color defSC = Color.black; private Color defSTC = Color.black; private Color defLTC = Color.black; //state size private int StateW = 130; private int StateH = 130; // line widths private int LineWidth = 1; //list of global lists private LinkedList<LinkedList<ObjAttribute>> globalList; //parent frame private JFrame frame; //keeps track if file is modified since last opening/saving private boolean fileModified = false; // used for auto generation of state and transition names private int createSCounter = 0, createTCounter = 0; // pages private int currPage = 1; //double click settings private int dClickTime = 200; // double click speed in ms private long lastClick = 0; //lock to grid settings private boolean grid = false; private int gridS = 25; // global table, default tab settings private int space = 20; public DrawArea(LinkedList<LinkedList<ObjAttribute>> globals) { globalList = globals; //create arrays to store created objects objList = new Vector<Object>(); undoList = new Vector<Vector<Object>>(); tempList = new Vector<Object>(); this.setFocusable(true); this.requestFocus(); currUndoIndex = -1; //global attributes stored at index 0 of object array objList.add(globalList); TextObj globalTable = new TextObj(10,10,globalList,tableFont); objList.add(globalTable); undoList.add(objList); currUndoIndex++; setBackground(Color.blue); addMouseListener(this); addMouseMotionListener(this); } public void paintComponent(Graphics g) { Graphics2D g2D = (Graphics2D) g; super.paintComponent(g2D); g2D.setFont(currFont); g2D.setStroke(new BasicStroke(getLineWidth())); g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); //paint all objects if(objList != null) { for (int i = 1; i < objList.size(); i++) { GeneralObj s = (GeneralObj) objList.elementAt(i); s.paintComponent(g2D,currPage); } } if(multipleSelect) { g2D.setColor(Color.RED); g2D.drawRect(mX0, mY0, mX1-mX0, mY1-mY0); } if(loading) { updateGlobalTable(); loading = false; repaint(); } } public boolean canUndo() { if (currUndoIndex >= 0) return true; else return false; } @SuppressWarnings("unchecked") public void undo() { //store current array on undo list if it isn't already there if(currUndoIndex + 1 == undoList.size()) undoList.add(objList); //replace objlist with a previous list if(currUndoIndex > 0) { objList = (Vector<Object>) undoList.elementAt(currUndoIndex); currUndoIndex--; } //unselect all states for (int i = 1; i < objList.size(); i++) { GeneralObj s = (GeneralObj) objList.elementAt(i); s.unselect(); } objsSelected = false; //update globalList = (LinkedList<LinkedList<ObjAttribute>>) objList.get(0); updateStates(); updateTrans(); updateGlobalTable(); FizzimGui fgui = (FizzimGui) frame; fgui.updateGlobal(globalList); repaint(); } public boolean canRedo() { if(currUndoIndex < undoList.size() - 2) return true; else return false; } @SuppressWarnings("unchecked") public void redo() { //if redo is possible, replace objlist with wanted list if(currUndoIndex < undoList.size() - 2) { objList = (Vector<Object>) undoList.elementAt(currUndoIndex + 2); currUndoIndex++; } globalList = (LinkedList<LinkedList<ObjAttribute>>) objList.get(0); updateStates(); updateTrans(); updateGlobalTable(); FizzimGui fgui = (FizzimGui) frame; fgui.updateGlobal(globalList); repaint(); } /* The following two methods create an undo point. It is not committed to undo list yet * because an undo point is not needed if the user is just clicking to select an * object (this method is triggered on mouse down) * In this method, a temp list is created to hold all the pointers to objects * before any modification occurs. The objects to be modified, and all objects connected * to them, are then cloned, and their clones are pointed to by objlist. */ @SuppressWarnings("unchecked") //this method is called whenever a global attribute is about to be modified public LinkedList<LinkedList<ObjAttribute>> setUndoPoint() { tempList = null; tempList = (Vector<Object>) objList.clone(); LinkedList<LinkedList<ObjAttribute>> oldGlobal = (LinkedList<LinkedList<ObjAttribute>>) objList.get(0); LinkedList<LinkedList<ObjAttribute>> newGlobal = (LinkedList<LinkedList<ObjAttribute>>) oldGlobal.clone(); objList.set(0,newGlobal); globalList = newGlobal; for(int i = 0; i < oldGlobal.size(); i++) { LinkedList<ObjAttribute> oldList = (LinkedList<ObjAttribute>)oldGlobal.get(i); LinkedList<ObjAttribute> newList = (LinkedList<ObjAttribute>)oldList.clone(); for(int j = 0; j < oldList.size(); j++) { try { newList.set(j,(ObjAttribute)oldList.get(j).clone()); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } newGlobal.set(i,newList); } return (LinkedList<LinkedList<ObjAttribute>>) objList.get(0); } //for multiple select, clone all selected objects private void setUndoPointMultiple() { tempList = null; tempList = (Vector<Object>) objList.clone(); //go through all selected objects and clone for(int i = 0; i < selectedIndices.size(); i++) { GeneralObj oldObj = (GeneralObj) tempList.get(selectedIndices.get(i).intValue()); GeneralObj clonedObj = null; try { clonedObj = (GeneralObj) oldObj.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } //if a state, create clone of children transitions if(oldObj.getType() == 0) { for(int j = 1; j < objList.size(); j++) { GeneralObj s = (GeneralObj) objList.elementAt(j); //check all objects that have to be modified state as a parent if(s.getType() != 0 && s.containsParent(oldObj)) { GeneralObj clonedObj2 = null; try { clonedObj2 = (GeneralObj) s.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } //replace old obj link in trans obj with new cloned one clonedObj2.notifyChange(oldObj, clonedObj); clonedObj2.setParentModified(true); //add cloned child to object list int objListIndex = objList.indexOf(s); objList.set(objListIndex,clonedObj2); } } } objList.set(selectedIndices.get(i).intValue(),clonedObj); } } @SuppressWarnings("unchecked") private void setUndoPoint(int index, int type) { tempList = null; tempList = (Vector<Object>) objList.clone(); if(index != -1) { GeneralObj oldObj = (GeneralObj) tempList.elementAt(index); GeneralObj clonedObj = null; try { clonedObj = (GeneralObj) oldObj.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } tempOld = oldObj; tempClone = clonedObj; //if a state, create clone of children transitions if(type == 0) { FizzimGui fgui = (FizzimGui) frame; fgui.updateGlobal(setUndoPoint()); for(int i = 1; i < objList.size(); i++) { GeneralObj s = (GeneralObj) objList.elementAt(i); //check all objects that have to be modified state as a parent if(s.getType() != 0 && s.containsParent(oldObj)) { GeneralObj clonedObj2 = null; try { clonedObj2 = (GeneralObj) s.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } //replace old obj link in trans obj with new cloned one clonedObj2.notifyChange(oldObj, clonedObj); clonedObj2.setParentModified(true); //add cloned child to object list int objListIndex = objList.indexOf(s); objList.set(objListIndex,clonedObj2); } } } objList.set(index,clonedObj); } } //used when properties is cancelled public void cancel() { objList = tempList; } // If a modification actually occurred, // the temp list is stored to the undo list array public void commitUndo() { int size = undoList.size(); // clears redo points ahead of current position if (currUndoIndex < size - 1) { for (int i = size - 1; i > currUndoIndex; i--) undoList.remove(i); } undoList.add(tempList); currUndoIndex++; fileModified = true; repaint(); } public void mouseClicked(MouseEvent e) { //System.out.println("mouseClicked:" + " Button:" + e.getButton() + " Modifiers:" + e.getModifiers() + " Popup Trigger:" + e.isPopupTrigger() + " ControlDown:" + e.isControlDown()); } public void mouseEntered(MouseEvent e) { //System.out.println("mouseEntered:" + " Button:" + e.getButton() + " Modifiers:" + e.getModifiers() + " Popup Trigger:" + e.isPopupTrigger() + " ControlDown:" + e.isControlDown()); } public void mouseExited(MouseEvent e) { //System.out.println("mouseeExited:" + " Button:" + e.getButton() + " Modifiers:" + e.getModifiers() + " Popup Trigger:" + e.isPopupTrigger() + " ControlDown:" + e.isControlDown()); } public void mouseHandle(MouseEvent e) { } public void mousePressed(MouseEvent e) { //System.out.println("mousePressed:" + " Button:" + e.getButton() + " Modifiers:" + e.getModifiers() + " Popup Trigger:" + e.isPopupTrigger() + " ControlDown:" + e.isControlDown()); GeneralObj bestMatch = null; boolean doubleClick = false; //check for double click if(e.getWhen() - lastClick < dClickTime && e.getButton() == MouseEvent.BUTTON1 && e.getModifiers() != 20) doubleClick = true; lastClick = e.getWhen(); //check for ctrl click to select multiple if(e.isControlDown() && e.getButton() == MouseEvent.BUTTON1) { //store selected objects and their indices int numbSel = 0; LinkedList<Integer> tempIndices = new LinkedList<Integer>(); for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj) objList.get(i); if(obj.getType() == 0 || obj.getType() == 3) { if(obj.getSelectStatus() != 0) { // deselect if clicked on when selected if(obj.setSelectStatus(e.getX(),e.getY())) { obj.unselect(); } else { obj.setSelectStatus(true); numbSel++; tempIndices.add(new Integer(i)); } } else if(obj.setSelectStatus(e.getX(),e.getY())) { numbSel++; tempIndices.add(new Integer(i)); } } else obj.unselect(); } //if multiple items selected so far, update global selection list. if(numbSel > 1) { selectedIndices = tempIndices; objsSelected = true; } } //if multiple object selected else if(objsSelected) { setUndoPointMultiple(); if(e.getButton() == MouseEvent.BUTTON1 && e.getModifiers() != 20) { boolean move = false; for(int i = 0; i < selectedIndices.size(); i++) { GeneralObj obj = (GeneralObj) objList.get(selectedIndices.get(i).intValue()); if((obj.getType() == 0 || obj.getType() == 3) && obj.setBoxSelectStatus(e.getX(),e.getY())) { move = true; } } //if click outside, unselect all if(!move) { objsSelected = false; unselectObjs(); } } else if(e.getButton() == MouseEvent.BUTTON3 || e.getModifiers() == 20) { createPopup(null,e); } } else { //if object already selected for (int i = 1; i < objList.size(); i++) { GeneralObj s = (GeneralObj) objList.elementAt(i); if(s.getSelectStatus() != 0 && s.setSelectStatus(e.getX(),e.getY())) { bestMatch = s; if(!doubleClick) { //if right click, create popup menu if(e.getButton() == MouseEvent.BUTTON3 || e.getModifiers() == 20) { setUndoPoint(i,s.getType()); createPopup(s,e); } else setUndoPoint(i,s.getType()); break; } else { if(s.getType() == 0) { new StateProperties(this,frame, true, (StateObj) s) .setVisible(true); } else if(s.getType() == 1) { Vector<StateObj> stateObjs = new Vector<StateObj>(); for(int j = 1; j < objList.size(); j++) { GeneralObj obj = (GeneralObj)objList.get(j); if(obj.getType() == 0) stateObjs.add((StateObj)obj); } new TransProperties(this,frame, true, (StateTransitionObj) s,stateObjs,false,null) .setVisible(true); } else if(s.getType() == 2) { Vector<StateObj> stateObjs = new Vector<StateObj>(); for(int j = 1; j < objList.size(); j++) { GeneralObj obj = (GeneralObj)objList.get(j); if(obj.getType() == 0) stateObjs.add((StateObj)obj); } new TransProperties(this,frame, true, (LoopbackTransitionObj) s,stateObjs,true,null) .setVisible(true); } else if(s.getType() == 3) { editText((TextObj) s); } } } } //check for text at mouse location if(bestMatch == null) { for (int i = 1; i < objList.size(); i++) { GeneralObj s = (GeneralObj) objList.elementAt(i); if(s.getType() == 3 && s.setSelectStatus(e.getX(),e.getY())) { bestMatch = s; if(e.getButton() == MouseEvent.BUTTON3 || e.getModifiers() == 20) { setUndoPoint(i,3); createPopup(s,e); } else setUndoPoint(i,3); break; } } } //check for transition at mouse position if(bestMatch == null) { for (int i = 1; i < objList.size(); i++) { GeneralObj s = (GeneralObj) objList.elementAt(i); if((s.getType() == 1 || s.getType() == 2) && s.setSelectStatus(e.getX(),e.getY())) { bestMatch = s; int type = s.getType(); if(e.getButton() == MouseEvent.BUTTON3 || e.getModifiers() == 20) { setUndoPoint(i,type); createPopup(s,e); } else setUndoPoint(i,type); break; } } } //if no transitions found at that position, look through state objects if(bestMatch == null) { for (int i = 1; i < objList.size(); i++) { GeneralObj s = (GeneralObj) objList.elementAt(i); if(s.getType() == 0 && s.setSelectStatus(e.getX(),e.getY())) { bestMatch = s; if(e.getButton() == MouseEvent.BUTTON3 || e.getModifiers() == 20) { setUndoPoint(i,0); createPopup(s,e); } else setUndoPoint(i,0); break; } } } //if nothing is clicked on, and right click if(bestMatch == null && (e.getButton() == MouseEvent.BUTTON3 || e.getModifiers() == 20)) { createPopup(e); setUndoPoint(-1,-1); } //now do multiple select if still nothing found if(bestMatch == null && e.getButton() == MouseEvent.BUTTON1 && e.getModifiers() != 20) { mXTemp = e.getX(); mYTemp = e.getY(); mX0 = 0; mY0 = 0; mX1 = 0; mY1 = 0; multipleSelect = true; objsSelected = false; selectedIndices.clear(); } repaint(); } } public void mouseReleased(MouseEvent e) { //System.out.println("mouseReleased:" + " Button:" + e.getButton() + " Modifiers:" + e.getModifiers() + " Popup Trigger:" + e.isPopupTrigger() + " ControlDown:" + e.isControlDown()); multipleSelect = false; if(!objsSelected) { selectedIndices.clear(); } //done modifying all objects, so notify state objects that they are done changing //this means transition object won't have to re-calculate connection points toCommit = false; for (int i = 1; i < objList.size(); i++) { GeneralObj t = (GeneralObj) objList.elementAt(i); //check for modified state if (t.isModified() && t.getType() == 0) { toCommit = true; for(int j = 1; j < objList.size(); j++) { GeneralObj obj = (GeneralObj) objList.elementAt(j); if(obj.getType() != 0 && obj.isParentModified()) obj.updateObj(); obj.setParentModified(false); } } //check for modified line or text box if((t.getType() == 1 || t.getType() == 2) && t.isModified()) { toCommit = true; for(int j = 1; j < objList.size(); j++) { GeneralObj obj = (GeneralObj) objList.elementAt(j); if((obj.getType() == 3) && obj.isParentModified()) obj.updateObj(); obj.setParentModified(false); } } if(t.getType() == 3 && t.isModified()) { toCommit = true; } t.setModified(false); } if(toCommit) commitUndo(); repaint(); } public void updateTransitions() { for(int j = 1; j < objList.size(); j++) { GeneralObj obj = (GeneralObj) objList.elementAt(j); if(obj.getType() != 0 && obj.isParentModified()) obj.updateObj(); } } public void mouseDragged(MouseEvent arg0) { //keep movement within page int x = arg0.getX(); int y = arg0.getY(); if(x<0) x=0; if(y<0) y=0; FizzimGui fgui = (FizzimGui) frame; if(x>fgui.maxW) x=fgui.maxW; if(y>fgui.maxH) y=fgui.maxH; // move object if multiple select is off if(!multipleSelect && !arg0.isControlDown() && arg0.getModifiers() == 16) { for (int i = 1; i < objList.size(); i++) { GeneralObj s = (GeneralObj) objList.elementAt(i); if(s.getSelectStatus() != 0) { s.adjustShapeOrPosition(x,y); for(int j = 1; j < objList.size(); j++) { GeneralObj obj = (GeneralObj) objList.elementAt(j); if(obj.getType() != 0 && obj.isParentModified()) obj.updateObj(); } //break; } } repaint(); } //if multiple select is on, then check if any objects inside yet else if(!arg0.isControlDown() && arg0.getModifiers() == 16) { // correct box coordinates if(x<mXTemp) { mX0 = x; mX1 = mXTemp; } else { mX0 = mXTemp; mX1 = x; } if(y<mYTemp) { mY0 = y; mY1 = mYTemp; } else { mY0 = mYTemp; mY1 = y; } int tempNumb = 0; objsSelected = false; selectedIndices.clear(); for (int i = 1; i < objList.size(); i++) { GeneralObj s = (GeneralObj) objList.elementAt(i); if((s.getType() == 0 || s.getType() == 3) && s.setBoxSelectStatus(mX0,mY0,mX1,mY1)) { tempNumb++; selectedIndices.add(new Integer(i)); } } if(tempNumb > 1) objsSelected = true; else selectedIndices.clear(); repaint(); } } public void mouseMoved(MouseEvent arg0) { } public void createPopup(GeneralObj obj, MouseEvent e) { // store location of click and object that is clicked on rXTemp = e.getX(); rYTemp = e.getY(); tempObj = obj; JMenuItem menuItem; //Create the popup menu. JPopupMenu popup = new JPopupMenu(); //create submenu for moving pages JMenu pages = new JMenu("Move to Page..."); FizzimGui fgui = (FizzimGui) frame; for(int i = 1; i < fgui.getPages(); i++) { if(i != currPage) { menuItem = new JMenuItem(fgui.getPageName(i)); menuItem.addActionListener(this); pages.add(menuItem); } } if(obj == null) popup.add(pages); if(obj != null && obj.getType() == 0) { menuItem = new JMenuItem("Add Loopback Transition"); menuItem.setMnemonic(KeyEvent.VK_L); menuItem.addActionListener(this); popup.add(menuItem); JMenu states = new JMenu("Add State Transition to..."); states.setMnemonic(KeyEvent.VK_T); states.setDisplayedMnemonicIndex(10); for(int j = 1; j < objList.size(); j++) { GeneralObj obj1 = (GeneralObj)objList.get(j); if(obj1.getType() == 0 && !obj.getName().equals(obj1.getName())) { menuItem = new JMenuItem(obj1.getName()); menuItem.addActionListener(this); states.add(menuItem); } } popup.add(states); menuItem = new JMenuItem("Edit State Properties"); menuItem.setMnemonic(KeyEvent.VK_E); menuItem.addActionListener(this); popup.add(menuItem); popup.add(pages); } if(obj != null && obj.getType() == 1) { menuItem = new JMenuItem("Edit State Transition Properties"); menuItem.setMnemonic(KeyEvent.VK_E); menuItem.addActionListener(this); popup.add(menuItem); if(obj.getSelectStatus() == StateTransitionObj.TXT) { JMenu pages2 = new JMenu("Move to Page..."); StateTransitionObj sobj = (StateTransitionObj) obj; for(int i = 1; i < fgui.getPages(); i++) { if(i != currPage && (i == sobj.getEPage() || i == sobj.getSPage())) { menuItem = new JMenuItem(fgui.getPageName(i)); menuItem.addActionListener(this); pages2.add(menuItem); } } popup.add(pages2); } } if(obj != null && obj.getType() == 2) { menuItem = new JMenuItem("Edit Loopback Transition Properties"); menuItem.setMnemonic(KeyEvent.VK_E); menuItem.addActionListener(this); popup.add(menuItem); } if(obj != null && obj.getType() == 3) { menuItem = new JMenuItem("Edit Text"); menuItem.setMnemonic(KeyEvent.VK_E); menuItem.addActionListener(this); popup.add(menuItem); popup.add(pages); } popup.show(e.getComponent(), e.getX(),e.getY()); } public void createPopup(MouseEvent e) { rXTemp = e.getX(); rYTemp = e.getY(); tempObj = null; JMenuItem menuItem; //Create the popup menu. JPopupMenu popup = new JPopupMenu(); menuItem = new JMenuItem("Quick New State"); menuItem.setMnemonic(KeyEvent.VK_Q); menuItem.addActionListener(this); popup.add(menuItem); menuItem = new JMenuItem("New State"); menuItem.setMnemonic(KeyEvent.VK_S); menuItem.addActionListener(this); popup.add(menuItem); menuItem = new JMenuItem("New State Transition"); menuItem.setMnemonic(KeyEvent.VK_T); menuItem.setDisplayedMnemonicIndex(10); menuItem.addActionListener(this); popup.add(menuItem); menuItem = new JMenuItem("New Loopback Transition"); menuItem.setMnemonic(KeyEvent.VK_L); menuItem.addActionListener(this); popup.add(menuItem); menuItem = new JMenuItem("New Free Text"); menuItem.setMnemonic(KeyEvent.VK_F); menuItem.addActionListener(this); popup.add(menuItem); popup.show(e.getComponent(), e.getX(),e.getY()); } // called when item on popup menu is selected public void actionPerformed(ActionEvent e) { JMenuItem source = (JMenuItem)(e.getSource()); //if cloned for undo if(tempObj == tempOld) tempObj = tempClone; String input = source.getText(); if(input == "Edit Text") { editText((TextObj) tempObj); } else if(input == "Edit State Properties") { new StateProperties(this,frame, true, (StateObj) tempObj) .setVisible(true); } else if(input == "Edit Loopback Transition Properties") { Vector<StateObj> stateObjs = new Vector<StateObj>(); for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj)objList.get(i); if(obj.getType() == 0) stateObjs.add((StateObj)obj); } new TransProperties(this,frame, true, (LoopbackTransitionObj) tempObj,stateObjs,true,null) .setVisible(true); } else if(input == "Edit State Transition Properties") { Vector<StateObj> stateObjs = new Vector<StateObj>(); for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj)objList.get(i); if(obj.getType() == 0) stateObjs.add((StateObj)obj); } new TransProperties(this,frame, true, (StateTransitionObj) tempObj,stateObjs,false,null) .setVisible(true); } else if(input == "Quick New State") { GeneralObj state = new StateObj(rXTemp-StateW/2,rYTemp-StateH/2,rXTemp+StateW/2,rYTemp+StateH/2,createSCounter, currPage, defSC,grid, gridS); createSCounter++; objList.add(state); state.updateAttrib(globalList,3); commitUndo(); } else if(input == "New State") { GeneralObj state = new StateObj(rXTemp-StateW/2,rYTemp-StateH/2,rXTemp+StateW/2,rYTemp+StateH/2,createSCounter, currPage, defSC,grid,gridS); createSCounter++; objList.add(state); state.updateAttrib(globalList,3); new StateProperties(this,frame, true, (StateObj) state) .setVisible(true); } else if(input == "New State Transition") { Vector<StateObj> stateObjs = new Vector<StateObj>(); for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj)objList.get(i); if(obj.getType() == 0) { stateObjs.add((StateObj)obj); } } if(stateObjs.size() > 1) { GeneralObj trans = new StateTransitionObj(createTCounter,currPage,this, defSTC); createTCounter++; objList.add(trans); trans.updateAttrib(globalList,4); new TransProperties(this,frame, true, (TransitionObj) trans, stateObjs,false,null) .setVisible(true); } else { JOptionPane.showMessageDialog(this, "Must be more than 2 states before a transition can be created", "error", JOptionPane.ERROR_MESSAGE); } } else if(input == "Add Loopback Transition") { Vector<StateObj> stateObjs = new Vector<StateObj>(); for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj)objList.get(i); if(obj.getType() == 0) { stateObjs.add((StateObj)obj); } } if(stateObjs.size() > 0) { GeneralObj trans = new LoopbackTransitionObj(rXTemp,rYTemp,createTCounter,currPage, defLTC); createTCounter++; objList.add(trans); trans.updateAttrib(globalList,4); new TransProperties(this,frame, true, (TransitionObj) trans, stateObjs,true,(StateObj)tempObj) .setVisible(true); } else { JOptionPane.showMessageDialog(this, "Must be more than 1 states before a loopback transition can be created", "error", JOptionPane.ERROR_MESSAGE); } } else if(input == "New Loopback Transition") { Vector<StateObj> stateObjs = new Vector<StateObj>(); for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj)objList.get(i); if(obj.getType() == 0) { stateObjs.add((StateObj)obj); } } if(stateObjs.size() > 0) { GeneralObj trans = new LoopbackTransitionObj(rXTemp,rYTemp,createTCounter,currPage, defLTC); createTCounter++; objList.add(trans); trans.updateAttrib(globalList,4); new TransProperties(this,frame, true, (TransitionObj) trans, stateObjs,true,null) .setVisible(true); } else { JOptionPane.showMessageDialog(this, "Must be more than 1 states before a loopback transition can be created", "error", JOptionPane.ERROR_MESSAGE); } } else if(input == "New Free Text") { GeneralObj text = new TextObj("",rXTemp,rYTemp,currPage); objList.add(text); editText((TextObj) text); } else if(checkStateName(input)) { GeneralObj trans = new StateTransitionObj(createTCounter,currPage,this,(StateObj)tempObj,getStateObj(input), defSTC); createTCounter++; objList.add(trans); StateTransitionObj sTrans = (StateTransitionObj) trans; sTrans.initTrans((StateObj)tempObj,getStateObj(input)); trans.updateAttrib(globalList,4); commitUndo(); } else if(getPageIndex(input) > -1) { int page = getPageIndex(input); if(page != currPage) { if(!objsSelected) { tempObj.setPage(page); for(int j = 1; j < objList.size(); j++) { GeneralObj obj = (GeneralObj) objList.elementAt(j); if(obj.getType() != 0 && obj.isParentModified()) obj.updateObj(); obj.setParentModified(false); } tempObj.setModified(false); tempObj.updateObj(); commitUndo(); unselectObjs(); } else { //move all states for(int i = 0; i < selectedIndices.size(); i++) { GeneralObj obj = (GeneralObj) objList.get(selectedIndices.get(i).intValue()); if(obj.getType() == 0 || obj.getType() == 3) { obj.setPage(page); if(obj.getType() == 0) obj.setModified(true); } } for(int j = 1; j <objList.size(); j++) { GeneralObj obj = (GeneralObj) objList.elementAt(j); if(obj.getType() != 0 && obj.isParentModified()) { TransitionObj trans = (TransitionObj) obj; trans.updateObjPages(page); } obj.setParentModified(false); } for(int k = 0; k < selectedIndices.size(); k++) { GeneralObj obj = (GeneralObj) objList.get(selectedIndices.get(k).intValue()); if(obj.getType() == 0) { obj.setModified(false); } } unselectObjs(); objsSelected = false; multipleSelect = false; selectedIndices.clear(); commitUndo(); } } } repaint(); } private int getPageIndex(String input) { FizzimGui fgui = (FizzimGui) frame; return fgui.getPageIndex(input); } private StateObj getStateObj(String name) { for(int j = 1; j < objList.size(); j++) { GeneralObj obj1 = (GeneralObj)objList.get(j); if(obj1.getType() == 0 && obj1.getName().equals(name)) return (StateObj) obj1; } return null; } private boolean checkStateName(String input) { for(int j = 1; j < objList.size(); j++) { GeneralObj obj1 = (GeneralObj)objList.get(j); if(obj1.getType() == 0 && obj1.getName().equals(input)) return true; } return false; } // update state attribute lists when global list is updated public void updateStates() { String resetName = null; for(int j = 0; j < globalList.get(0).size(); j++) { if(globalList.get(0).get(j).getName().equals("reset_state")) resetName = globalList.get(0).get(j).getValue(); } for(int i = 1; i < objList.size(); i++) { GeneralObj o = (GeneralObj) objList.elementAt(i); if(o.getType() == 0) { StateObj s = (StateObj) o; s.updateAttrib(globalList,3); if(s.getName().equals(resetName)) s.setReset(true); else s.setReset(false); } } } // update transition attribute lists when global list is updated public void updateTrans() { for(int i = 1; i < objList.size(); i++) { GeneralObj o = (GeneralObj) objList.elementAt(i); if(o.getType() == 1 || o.getType() == 2) { TransitionObj s = (TransitionObj) o; s.updateAttrib(globalList,4); } } } public void editText(TextObj obj) { //ColorChooserIcon icon = new ColorChooserIcon(obj.getColor(),colorChooser); //addMouseListener(icon); String s = (String)JOptionPane.showInputDialog( frame, "Edit Text:\n", "Edit Text Properties", JOptionPane.PLAIN_MESSAGE, null, null, obj.getText()); if(s != null) { obj.setText(s); commitUndo(); } } public void setJFrame(FizzimGui fizzimGui) { frame = fizzimGui; } //check for duplicate names public boolean checkStateNames() { TreeSet<String> stateSet = new TreeSet<String>(); int stateCounter = 0; for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj)objList.get(i); if(obj.getType() == 0) { stateSet.add(obj.getName()); stateCounter++; } } if(stateSet.size() == stateCounter) return true; else return false; } //check for duplicate names public boolean checkTransNames() { TreeSet<String> transSet = new TreeSet<String>(); int transCounter = 0; for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj)objList.get(i); if(obj.getType() == 1 || obj.getType() == 2) { transSet.add(obj.getName()); transCounter++; } } if(transSet.size() == transCounter) return true; else return false; } public void save(BufferedWriter writer) throws IOException { writer.write("## START PREFERENCES\n"); writer.write("<SCounter>\n" + createSCounter + "\n</SCounter>\n"); writer.write("<TCounter>\n" + createTCounter + "\n</TCounter>\n"); writer.write("<TableVis>\n" + tableVis + "\n</TableVis>\n"); writer.write("<TableSpace>\n" + space + "\n</TableSpace>\n"); writer.write("<TableFont>\n" + tableFont.getFontName() + "\n" + tableFont.getSize() + "\n</TableFont>\n"); writer.write("<TableColor>\n" + tableColor.getRGB() + "\n</TableColor>\n"); writer.write("<Font>\n" + currFont.getFontName() + "\n" + currFont.getSize() + "\n</Font>\n"); writer.write("<Grid>\n" + grid + "\n" + gridS + "\n</Grid>\n"); writer.write("<PageSizeW>\n" + getMaxW() + "\n</PageSizeW>\n"); writer.write("<PageSizeH>\n" + getMaxH() + "\n</PageSizeH>\n"); writer.write("<StateW>\n" + getStateW() + "\n</StateW>\n"); writer.write("<StateH>\n" + getStateH() + "\n</StateH>\n"); writer.write("<LineWidth>\n" + getLineWidth() + "\n</LineWidth>\n"); writer.write("## END PREFERENCES\n"); writer.write("## START OBJECTS\n"); // tell every object to save itself for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj) objList.get(i); obj.save(writer); } writer.write("## END OBJECTS\n"); } public void delete() { setUndoPoint(-1,-1); //indices of transitions to delete LinkedList<Integer> trans = new LinkedList<Integer>(); // find indices of all transitions to delete for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj) objList.get(i); // for deleteing multiple selected objects, find transitions boolean toDel = false; if((obj.getType() == 1 || obj.getType() == 2) && objsSelected) { for(int j = 0; j < selectedIndices.size(); j++) { GeneralObj state = (GeneralObj) objList.get(selectedIndices.get(j).intValue()); if(obj.containsParent(state)) toDel = true; } } // make sure global table isnt removed if(obj.getType() == 3 && objsSelected) { TextObj txt = (TextObj) obj; if(txt.getGlobalTable() && txt.getSelectStatus() != 0) { String error = "To remove global table, go to 'File->Preferences'"; JOptionPane.showMessageDialog(frame, error, "error", JOptionPane.ERROR_MESSAGE); } // remove from selected indices for(int j = 0; j < selectedIndices.size(); j++) { Integer tempInt = selectedIndices.get(j); if(tempInt.intValue() == i) { selectedIndices.remove(j); break; } } } //for delteing single object, if it is a state remove the transitions if(!objsSelected && obj.getSelectStatus() != 0) { //if transition, just delete if((obj.getType() == 1 || obj.getType() == 2)) { objList.remove(i); commitUndo(); break; } // stop delete of global table, otherwise delete if(obj.getType() == 3) { TextObj txt = (TextObj) obj; if(txt.getGlobalTable() && txt.getSelectStatus() != 0) { String error = "To remove global table, go to 'File->Preferences'"; JOptionPane.showMessageDialog(frame, error, "error", JOptionPane.ERROR_MESSAGE); } else { objList.remove(i); commitUndo(); break; } } //if state, add transitions to delete if(obj.getType() == 0) { for(int j = 1; j < objList.size(); j++) { GeneralObj t = (GeneralObj) objList.elementAt(j); if(t.getType() == 1 || t.getType() == 2) { TransitionObj tran = (TransitionObj) t; if(tran.containsParent(obj)) trans.add(new Integer(j)); } } // make sure state gets deleted at correct time selectedIndices.add(new Integer(i)); } } if(toDel) trans.add(new Integer(i)); } //delete all selected while(selectedIndices.size() > 0 || trans.size() > 0) { int i1 = -1; int i2 = -1; if(selectedIndices.size() > 0) i1 = selectedIndices.get((selectedIndices.size()-1)).intValue(); if(trans.size() > 0) i2 = trans.get((trans.size()-1)).intValue(); if(i1>i2) { objList.remove(i1); selectedIndices.removeLast(); } else { objList.remove(i2); trans.removeLast(); } } commitUndo(); objsSelected = false; } public static void disableDoubleBuffering(Component c) { RepaintManager currentManager = RepaintManager.currentManager(c); currentManager.setDoubleBufferingEnabled(false); } public static void enableDoubleBuffering(Component c) { RepaintManager currentManager = RepaintManager.currentManager(c); currentManager.setDoubleBufferingEnabled(true); } public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException { if (pageIndex > 0) { return(NO_SUCH_PAGE); } else { for (int i = 1; i < objList.size(); i++) { GeneralObj s = (GeneralObj) objList.elementAt(i); s.unselect(); } Graphics2D g2d = (Graphics2D)g; g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); g2d.scale(pageFormat.getImageableWidth()/this.getWidth(),pageFormat.getImageableHeight()/this.getHeight()); disableDoubleBuffering((Component)this); this.paint(g2d); enableDoubleBuffering((Component)this); return(PAGE_EXISTS); } } public void open(Vector<Object> objList2) { loading = true; currPage = 1; objList = objList2; undoList.clear(); tempList.clear(); currUndoIndex = 0; undoList.add(objList); toCommit = false; tempObj = null; tempOld = null; tempClone = null; fileModified = false; for (int i = 1; i < objList.size(); i++) { GeneralObj s = (GeneralObj) objList.elementAt(i); if(s.getType() == 1 || s.getType() == 2) { TransitionObj t = (TransitionObj) s; t.makeConnections(objList); } if(s.getType() == 3) { TextObj textObj = (TextObj) s; if(textObj.getGlobalTable()) { textObj.loadGlobalTable(tableFont); } } } updateStates(); updateTrans(); // Added by pz, but no sure why (initial paint of flags is incorrect without it) setGrid(grid,gridS); repaint(); } public void open(LinkedList<LinkedList<ObjAttribute>> global) { loading = true; currPage = 1; globalList = global; objList.clear(); objList.add(globalList); TextObj globalTable = new TextObj(10,10,globalList,tableFont); objList.add(globalTable); undoList.clear(); undoList.add(objList); tempList.clear(); currUndoIndex = 0; toCommit = false; tempObj = null; tempOld = null; tempClone = null; fileModified = false; createSCounter = 0; createTCounter = 0; updateStates(); updateTrans(); // Added by pz, but no sure why (initial paint of flags is incorrect without it) repaint(); } public void setSCounter(String readLine) { createSCounter = Integer.parseInt(readLine); } public void setTCounter(String readLine) { createTCounter = Integer.parseInt(readLine); } public void updateGlobal(LinkedList<LinkedList<ObjAttribute>> globalList2) { globalList = globalList2; } public LinkedList<LinkedList<ObjAttribute>> getGlobalList() { return globalList; } public void setFileModifed(boolean b) { fileModified = b; } public boolean getFileModifed() { return fileModified; } public String[] getStateNames() { ArrayList<String> names = new ArrayList<String>(); names.add("null"); for(int i = 1; i < objList.size(); i++) { GeneralObj s = (GeneralObj) objList.get(i); if(s.getType() == 0) names.add(s.getName()); } String names1[] = names.toArray(new String[names.size()]); return names1; } public void setCurrPage(int i) { currPage = i; } public int getMaxH() { FizzimGui fgui = (FizzimGui) frame; return fgui.getMaxH(); } public int getMaxW() { FizzimGui fgui = (FizzimGui) frame; return fgui.getMaxW(); } public void removePage(int tab) { for(int i = objList.size()-1; i > 0; i--) { GeneralObj obj = (GeneralObj) objList.get(i); if(obj.getType() != 1) { if(obj.getPage() == tab) { objList.remove(i); } if(obj.getPage() > tab) obj.decrementPage(); } else { StateTransitionObj obj1 = (StateTransitionObj) obj; if(obj1.getSPage() == tab || obj1.getEPage() == tab) objList.remove(i); if(obj1.getSPage() > tab) obj1.decrementSPage(); if(obj1.getEPage() > tab) obj1.decrementEPage(); } } } public void unselectObjs() { for (int i = 1; i < objList.size(); i++) { GeneralObj s = (GeneralObj) objList.elementAt(i); s.unselect(); } } public void resetUndo() { undoList.clear(); undoList.add(objList); tempList.clear(); currUndoIndex = 0; } public String getPageName(int page) { FizzimGui fgui = (FizzimGui) frame; return fgui.getPageName(page); } public void updateGlobalTable() { for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj) objList.get(i); if(obj.getType() == 3) { TextObj textObj = (TextObj) obj; if(textObj.getGlobalTable()) textObj.updateGlobalText(globalList,tableFont,tableVis,space,tableColor); } } repaint(); } public void setFont(Font font) { currFont = font; } public Font getFont() { return currFont; } public void setTableFont(Font font) { tableFont = font; } public Font getTableFont() { return tableFont; } public void setSpace(int i) { space = i; } public int getSpace() { return space; } public boolean getTableVis() { return tableVis; } public void setTableVis(boolean b) { tableVis = b; } public Color getTableColor() { return tableColor; } public void setTableColor(Color c) { tableColor = c; } public void setGrid(boolean b, int i) { grid = b; gridS = i; for(int j = 1; j < objList.size(); j++) { GeneralObj obj = (GeneralObj) objList.get(j); if(obj.getType() == 0) { StateObj obj1 = (StateObj) obj; obj1.setGrid(b,i); } } } public boolean getGrid() { return grid; } public int getGridSpace() { return gridS; } //generate pixel offset for page connectors public int getOffset(int page, StateObj startState, StateTransitionObj transObj, String type) { int totalNumb = 0; int numb = 0; for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj) objList.get(i); // find number that transition is out of total number if(obj.getType() == 1) { StateTransitionObj trans = (StateTransitionObj) obj; if(trans.pageConnectorExists(page,startState,type)) { totalNumb++; if(trans.equals(transObj)) numb = totalNumb; } } } //find number for cener position int avg; if(totalNumb % 2 != 0) avg = (int)((totalNumb+1)/2); else avg = (int)(totalNumb/2); int finalOffset = (numb-avg)*40; return finalOffset; } public void pageConnUpdate(StateObj startState, StateObj endState) { for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj) objList.get(i); if(obj.getType() == 1) { StateTransitionObj trans = (StateTransitionObj) obj; if(trans.pageConnectorExists(startState.getPage(),startState,"start") || trans.pageConnectorExists(endState.getPage(),endState,"end")) { trans.setEndPts(); } } } } //for redrawing all page connectors when page is resized public void updatePageConn() { for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj) objList.get(i); if(obj.getType() == 1) { StateTransitionObj trans = (StateTransitionObj) obj; if(trans.getSPage() != trans.getEPage()) trans.setEndPts(); } } } public void moveOnResize(int maxW, int maxH) { for(int i = 1; i < objList.size(); i++) { GeneralObj obj = (GeneralObj) objList.get(i); //move text objects onto page if(obj.getType() == 3) { TextObj text = (TextObj) obj; text.moveIfNeeded(maxW,maxH); } if(obj.getType() == 0) { StateObj state = (StateObj) obj; state.moveIfNeeded(maxW,maxH); } } } public Color getDefSC() { return defSC; } public void setDefSC(Color defSC) { this.defSC = defSC; } public Color getDefSTC() { return defSTC; } public void setDefSTC(Color defSTC) { this.defSTC = defSTC; } public Color getDefLTC() { return defLTC; } public void setDefLTC(Color defLTC) { this.defLTC = defLTC; } public JColorChooser getColorChooser() { return colorChooser; } public int getStateW() { return StateW; } public int getStateH() { return StateH; } public int getLineWidth() { return LineWidth; } public void setStateW(int w) { StateW = w; } public void setStateH(int h) { StateH = h; } public void setLineWidth(int w) { LineWidth = w; } public boolean getRedraw() { return Redraw; } } /* class ColorChooserIcon implements Icon, MouseListener { private Color color; private JColorChooser colorChooser; public ColorChooserIcon(Color color, JColorChooser colorChooser) { this.color = color; this.colorChooser = colorChooser; } public void paintIcon(Component c, Graphics g, int x, int y) { Color old_color = g.getColor(); g.setColor(color); g.fillRect(x,y,15,15); g.setColor(old_color); } public int getIconWidth() { return 15; } public int getIconHeight() { return 15; } public void mouseClicked(MouseEvent e) { System.out.println("test"); color = JColorChooser.showDialog(null, "Choose Color", color); } public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } } */
zimmerdesignservices/fizzim
DrawArea.java
248,172
public class Car extends Vehicle implements Driveable { public Car(int speed, float weight) { super(speed, weight); } @Override public void accelerate() { System.out.println("accelerating"); } @Override public void brake() { System.out.println("braking"); } @Override public void changeGear() { System.out.println("changing gear"); } }
mariannesnoodijk/backend-lesopdracht-fly-and-drive
Car.java
248,177
// 873. Length of Longest Fibonacci Subsequence // // A sequence x1, x2, ..., xn is Fibonacci-like if: // // n >= 3 // xi + xi+1 == xi+2 for all i + 2 <= n // Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0. // // A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8]. // // // // Example 1: // // Input: arr = [1,2,3,4,5,6,7,8] // Output: 5 // Explanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8]. // Example 2: // // Input: arr = [1,3,7,11,12,14,18] // Output: 3 // Explanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18]. // // // Constraints: // // 3 <= arr.length <= 1000 // 1 <= arr[i] < arr[i + 1] <= 109 // // Runtime 280 ms Beats 13.17% // Memory 44.7 MB Beats 50.90% class Solution { public int lenLongestFibSubseq(int[] arr) { int max = 0; Set<Integer> nums = new HashSet<>(); for (int num: arr) { nums.add(num); } for (int i = 0; i < arr.length - 2; i++) { for (int j = i + 1; j < arr.length - 1; j++) { max = Math.max(max, find(arr[i], arr[j], nums)); } } return max; } private int find(int prev, int cur, Set<Integer> nums) { int count = 0; while (nums.contains(prev + cur)) { if (count == 0) { count = 2; } int sum = prev + cur; prev = cur; cur = sum; count++; } return count; } } // Runtime 73 ms Beats 88.2% // Memory 54.7 MB Beats 5.39% class Solution { public int lenLongestFibSubseq(int[] arr) { int max = 0; int len = arr.length; int[][] matrix = new int[len][len]; for (int i = 2; i < len; i++) { int first = 0; int second = i - 1; while (first < second) { int sum = arr[first] + arr[second]; if (sum < arr[i]) { first++; } else if (sum > arr[i]) { second--; } else { matrix[second][i] = matrix[first][second] + 1; max = Math.max(max, matrix[second][i]); first++; second--; } } } return max > 0 ? max + 2: 0; } }
ishuen/leetcode
873.java
248,181
/** * Generates program7 class that implements a while loop. * @author Fanni Kertesz * CS322 Assignment3 gen7 */ import static utils.Utilities.writeFile; import org.objectweb.asm.*; public class gen7{ public static void main(String[] args){ //Write class "program7" ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC,"program7", null, "java/lang/Object",null); //Constructor { MethodVisitor mv=cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); //load the first local variable: this mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V",false); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(1,1); mv.visitEnd(); } //Main method { //VISIT METHOD MethodVisitor mv=cw.visitMethod(Opcodes.ACC_PUBLIC+Opcodes.ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null); mv.visitCode(); //WHILE LOOP //Variables for while loop mv.visitLdcInsn((int) 2); mv.visitVarInsn(Opcodes.ISTORE, 1);//changing variable mv.visitLdcInsn((int) 1); mv.visitVarInsn(Opcodes.ISTORE, 3);//incrementing variable - will keep adding 1 to var1 mv.visitLdcInsn((int) 3141); mv.visitVarInsn(Opcodes.ISTORE, 5);//condition variable - var1=<var7 for loop to run //Create labels for start and end of loop Label start = new Label(); Label end = new Label(); //start of loop mv.visitLabel(start); //Load changing variable and condition variable and check if CV>VR (loop breaks then) mv.visitVarInsn(Opcodes.ILOAD, 1); mv.visitVarInsn(Opcodes.ILOAD, 5); mv.visitJumpInsn(Opcodes.IF_ICMPGT, end); //Print var1 inside loop mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitVarInsn(Opcodes.ILOAD, 1); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(I)V", false); //Multiply var1*(var1+var3) and assign this new value to var1 inside loop mv.visitVarInsn(Opcodes.ILOAD, 1); mv.visitVarInsn(Opcodes.ILOAD, 3); mv.visitInsn(Opcodes.IADD); mv.visitVarInsn(Opcodes.ISTORE, 9);//temp variable=(var1+1) mv.visitVarInsn(Opcodes.ILOAD, 1); mv.visitVarInsn(Opcodes.ILOAD, 9); mv.visitInsn(Opcodes.IMUL); mv.visitVarInsn(Opcodes.ISTORE, 1);//store new var1=var1*var9 //jump to beginning to check if new number is ok mv.visitJumpInsn(Opcodes.GOTO, start); //end of loop if condition wasn't met mv.visitLabel(end); //Print ending mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn("Loop ended."); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); //END VISIT mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(0,0); mv.visitEnd(); } cw.visitEnd(); byte[] b = cw.toByteArray(); writeFile(b,"program7.class"); System.out.println("Done!"); }//end main }//end class
fkertesz/ASMBytecode_FK
gen7.java
248,184
public class Cell { //constants for ease of changing out what is stored in each spot private final String EMOJI = "🦠"; private final String EMPTY = "🔲"; //boardSpace is the current status of each space, whether it be an EMOJI or EMPTY private String boardSpace; private boolean isAlive; public Cell(boolean isAlive) { setIsAlive(isAlive); } public void setIsAlive(boolean isAlive) { this.isAlive = isAlive; setEmoji(); } public boolean getIsAlive() { return isAlive; } private void setEmoji() { if (this.isAlive) { boardSpace = EMOJI; } else { boardSpace = EMPTY; } } public String toString() { return boardSpace; } }
columbiaprep/apcsa-gameoflife
Cell.java
248,190
// Test whether the person is eligible to give vote using // (if-else) // Name : lokesh chaudhari // date : 11-10-22 package lokesh; public class votes { public static void main(String[] args) { // TODO Auto-generated method stub java.util.Scanner sc = new java.util.Scanner(System.in); System.out.println("Enter your age : "); int x = sc.nextInt(); if(x>=18) { System.out.println("You are Eligible to vote "); } else { System.out.println("Your are not Eligible to vote "); } } { } }
LOKESHCHAUDHARii/MY-java
HANDSON/votes.java
248,191
import java.io.Serializable; import java.util.List; public class Token implements Serializable { String request; Integer sender; Integer receiver; @Override public String toString() { return request; } public void setReceiver(Integer receiver) { this.receiver = receiver; } public void setSender(Integer sender) { this.sender = sender; } class Join extends Token { final int port; public Join(int port){ this.port = port; this.request = joinRequest(port); } private String joinRequest(int port) { StringBuilder req = new StringBuilder(); req.append("JOIN ").append(port); return req.toString(); } } class Details extends Token { final List<Integer> ports; // List of port number (aka. identifiers) public Details(List<Integer> ports){ this.ports = ports; this.request = detailsRequest(ports); } private String detailsRequest(List<Integer> ports) { StringBuilder req = new StringBuilder(); req.append("DETAILS "); ports.forEach(p -> req.append(p).append(" ")); return req.toString(); } } class VoteOptions extends Token { final List<String> voteOptions; // List of voting options for the consensus protocol VoteOptions(List<String> voteOptions) { this.voteOptions = voteOptions; this.request = voteOptionsRequest(voteOptions); } private String voteOptionsRequest(List<String> voteOptions) { StringBuilder req = new StringBuilder(); req.append("VOTE_OPTIONS "); voteOptions.forEach(v -> req.append(v).append(" ")); return req.toString(); } } class Votes extends Token { final List<SingleVote> votes; Votes(List<SingleVote> votes) { this.votes = votes; this.request = voteRequest(votes); } private String voteRequest(List<SingleVote> votes) { StringBuilder req = new StringBuilder(); req.append("VOTE "); //VOTE port i vote 1 port 2 vote 2 ...port n vote n votes.forEach(vote -> req.append(vote.getParticipantPort()).append(" ").append(vote.getVote()).append(" ")); return req.toString(); } } class Outcome extends Token { final String outcome; final List<Integer> participants; Outcome(String outcome, List<Integer> participants) { this.outcome = outcome; this.participants = participants; this.request = outcomeRequest(outcome, participants); } //OUTCOME A 12346 12347 12348 private String outcomeRequest(String outcome, List<Integer> participants) { StringBuilder req = new StringBuilder(); req.append("OUTCOME ").append(outcome).append(" "); participants.forEach(p -> req.append(p).append(" ")); return req.toString(); } } public static void sleep(long millis){ try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } public static void log(Object o){ System.out.println(o.toString()); } } class SingleVote implements Serializable { private final int participantPort; private final String vote; public SingleVote(int participantPort, String vote) { this.participantPort = participantPort; this.vote = vote; } public int getParticipantPort() { return participantPort; } public String getVote() { return vote; } @Override public String toString() { return "<" + participantPort + ", " + vote + ">"; } }
ejupialked/consensus-protocol
src/Token.java
248,192
import java.util.Random; public class Q28 { public static void main(String[] args) throws InterruptedException{ int votes[] = new int[240]; for (int i = 0; i < 240; i++) { int n = 20; int randomNum = (int) (Math.random() * 3 + 1); votes[i] = randomNum; } // Create four threads Votes V = new Votes(votes); VoteCountThread t1 = new VoteCountThread(0,60, V); VoteCountThread t2 = new VoteCountThread(60, 120, V); VoteCountThread t3 = new VoteCountThread(120, 180, V); VoteCountThread t4 = new VoteCountThread(180, 240, V); t1.start(); t2.start(); t3.start(); t4.start(); // Wait for all threads to finish the counting t1.join(); t2.join(); t3.join(); t4.join(); // Now print the counted votes V.print(); } } // Create a Votes class class Votes{ int votesA, votesB, votesC; int votes[]; Votes(int votes[]) { this.votes=votes; this.votesA = votesA; this.votesB = votesB; this.votesC = votesC; } synchronized public void countVotes(int start, int end) { for(int i=start; i<end; i++) { if(this.votes[i] == 1) this.votesA++; else if(this.votes[i]==2) this.votesB++; else if(this.votes[i] == 3) this.votesC++; } } void print() { System.out.println("Votes for A: " + this.votesA); System.out.println("Votes for B: "+this.votesB); System.out.println("Votes for C: "+this.votesC); } } // Create a custom thread class VoteCountThread extends Thread{ int start, end; Votes v; VoteCountThread(int s, int f, Votes v) { this.start = s; this.end = f; this.v = v; } public void run() { this.v.countVotes(this.start, this.end); } }
bikash-789/Java
src/Q28.java
248,193
public class Votes { private int firstVotes; private int secondVotes; private int thirdVotes; public Votes(int first, int second, int third) { this.firstVotes = first; this.secondVotes = second; this.thirdVotes = third; } public Votes(Votes v) { this.firstVotes = v.firstVotes; this.secondVotes = v.secondVotes; this.thirdVotes = v.thirdVotes; } public int getFirstVotes() { return this.firstVotes; } public int getSecondVotes() { return this.secondVotes; } public int getThirdVotes() { return this.thirdVotes; } public void voteFirst() { this.firstVotes++; } public void voteSecond() { this.secondVotes++; } public void voteThird() { this.thirdVotes++; } }
ryan-griffin/cs2102-hw
hw6/Votes.java
248,194
import java.util.Scanner; public class Voting { public void votes(int count[],int ballot[],int n,int a){ int i,sb=0; for(i=0; i<a; i++){ switch(ballot[i]){ case 1:count[1]++; break; case 2:count[2]++; break; case 3:count[3]++; break; case 4:count[4]++; break; case 5:count[5]++; break; default: sb++; } } for(i=1; i<=n; i++){ System.out.println("\nNo. of Votes of candidate "+i+"= "+count[i]);} System.out.println("\nNo. of Spoilt ballots = "+sb); } public static void main(String[] args){ int n=5,i,a; //System.out.println("Enter the number of candidates: "); Scanner sc=new Scanner(System.in); //n=sc.nextInt(); int count[]=new int[n+1]; for(i=0; i<=n; i++){ count[i]=0; } System.out.println("Enter the total no. of votings: "); a=sc.nextInt(); int ballot[]=new int[a]; System.out.println("Enter the ballot numbers: "); for(i=0; i<a; i++){ ballot[i]=sc.nextInt(); } Voting v=new Voting(); v.votes(count,ballot,n,a); } }
CodeMysticX/cuddly-giggle
Voting.java
248,196
import java.util.ArrayList; public class Participant implements Comparable<Participant> { private int points; private String name; private ArrayList<Integer> jumpLengths; public Participant(String name) { jumpLengths = new ArrayList<Integer>(); this.name = name; } public String toString() { return this.name + " (" + this.points + " points)"; } public int jump() { return (int) (Math.random() * 61 + 60); } public void addJumpLength(int len) { jumpLengths.add(len); } public String getName() { return this.name; } public ArrayList<Integer> votes() { ArrayList<Integer> roundVotes = new ArrayList<Integer>(); for (int i = 0; i < 5; i++) { roundVotes.add((int) (Math.random() * 11 + 10)); } return roundVotes; } public void addPoints(ArrayList<Integer> nums, int jumpLength) { int max = nums.get(0); for (int num : nums) { if (num > max) { max = num; } } nums.remove(nums.indexOf(max)); int min = nums.get(0); for (int num : nums) { if (num < min) { min = num; } } nums.remove(nums.indexOf(min)); for (int num : nums) { this.points += num; } this.points += jumpLength; } public String jumpLengths() { String ret = ""; for (int i = 0; i < jumpLengths.size() - 1; i++) { ret += jumpLengths.get(i) + " m,"; } int last = jumpLengths.size() - 1; ret += jumpLengths.get(last) + " m"; return ret; } @Override public int compareTo(Participant o) { return this.points - o.points; } }
j1m-ryan/SkiJumpJava
Participant.java
248,198
/* * Copyright 2012 The Play! Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package models; import be.objectify.deadbolt.models.Permission; import be.objectify.deadbolt.models.Role; import be.objectify.deadbolt.models.RoleHolder; import com.avaje.ebean.Ebean; import security.RoleDefinitions; import javax.persistence.*; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * @author Steve Chaloner ([email protected]) */ @Entity @Table(name = "MPO_USER") public class User extends AbstractModel implements RoleHolder { @Column(nullable = false, length = 40, unique = true) public String userName; @Column(nullable = false, length = 100) public String displayName; @Column(nullable = true, length = 2500) public String avatarUrl; @Column(nullable = false) public Boolean accountActive; @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) public List<UserRole> roles; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) public List<Vote> votes; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) public List<Rate> rates; public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, User.class); public static int count() { return FIND.findRowCount(); } public static List<User> all() { return FIND.where() .order().asc("displayName") .findList(); } public static User getByUserName(String userName) { return FIND.where() .eq("userName", userName.trim()) .findUnique(); } public static List<User> getAdmins() { UserRole adminRole = UserRole.findByRoleName(RoleDefinitions.ADMIN); return FIND.where() .in("roles", adminRole) .findList(); } @Override public List<? extends Role> getRoles() { return roles; } public boolean isAdmin() { boolean result = false; for (Iterator<UserRole> iterator = roles.iterator(); !result && iterator.hasNext(); ) { result = RoleDefinitions.ADMIN.equals(iterator.next().roleName); } return result; } @Override public List<? extends Permission> getPermissions() { // for now, let's go with role-based security. I don't think we need any fine-grained control. return Collections.emptyList(); } public void giveAdminRights() { UserRole adminRole = UserRole.findByRoleName(RoleDefinitions.ADMIN); roles.add(adminRole); save(); Ebean.saveAssociation(this, "roles"); } public void removeAdminRights() { if(isAdmin()) { UserRole adminRole = UserRole.findByRoleName(RoleDefinitions.ADMIN); roles.remove(adminRole); save(); Ebean.saveAssociation(this, "roles"); } } }
play-modules/modules.playframework.org
app/models/User.java
248,199
package game; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.boss.BarStyle; import org.bukkit.boss.BossBar; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import amongUs.Main; import amongUs.Messages; import managers.InvManager; public class Vote { private Game game; private boolean active = false; private BossBar bar; public int timeVote = 60; private Map<PlayerGame, PlayerGame> votes = new HashMap<PlayerGame, PlayerGame>(); private List<PlayerGame> skipping = new ArrayList<PlayerGame>(); private Inventory invVote; public Vote(Game game) { this.game = game; timeVote = game.time_voting; bar = Bukkit.createBossBar(Messages.vote, BarColor.GREEN, BarStyle.SOLID); Bukkit.getScheduler().runTaskTimer(Main.plugin, new Runnable() {@Override public void run() {tick();}}, 20, 20); Bukkit.getPluginManager().registerEvents(new Listener() { @EventHandler void playerClickInv(InventoryClickEvent e) { ItemStack item = e.getCurrentItem(); if(item == null || !e.getClickedInventory().equals(invVote)) return; if(!item.getItemMeta().getDisplayName().equalsIgnoreCase(Messages.skipVote)) Bukkit.dispatchCommand(e.getWhoClicked(), "among v " + item.getItemMeta().getDisplayName()); else Bukkit.dispatchCommand(e.getWhoClicked(), "among v skip"); e.getWhoClicked().closeInventory(); } }, Main.plugin); } public void tick() { if(active) timeVote--; else timeVote = game.time_voting; bar.setProgress(((double)timeVote)/game.time_voting); if(timeVote < 1) result(); } public String vote(Player player1, String player2) { if(!active) return Messages.voteNotFound; PlayerGame whoVoting = game.getPlayer(player1); if(whoVoting == null) return Messages.plNotInGame; if(!whoVoting.isLive()) return Messages.youDied; if(votes.containsKey(whoVoting) || skipping.contains(whoVoting)) return Messages.youYetVoted; PlayerGame player = game.getPlayer(Bukkit.getPlayer(player2)); if(player == null) return Messages.playerNotFound; if(!player.isLive()) return Messages.plDied; votes.put(whoVoting, player); if(votes.size() + skipping.size() + 1 > game.getLivePlayers().size()) result(); return "true"; } public void start() { if(active) return; skipping.clear(); votes.clear(); active = true; timeVote = game.time_voting; invVote = Bukkit.createInventory(null, 36, Messages.vote); for(PlayerGame player: game.getPlayers()) { Kits.vote(player.getPlayer()); Kits.colorArmor(player.getPlayer(), player.color); bar.addPlayer(player.getPlayer()); invVote.addItem(InvManager.genItem(Material.SKULL_ITEM, player.getPlayer().getName(), 3)); } invVote.setItem(35, InvManager.genItem(Material.BARRIER, Messages.skipVote)); } public String openInv(Player player) { if(!active) return Messages.voteNotFound; PlayerGame whoVoting = game.getPlayer(player); if(whoVoting == null) return Messages.plNotInGame; if(!whoVoting.isLive()) return Messages.youDied; if(votes.containsKey(whoVoting) || skipping.contains(whoVoting)) return Messages.youYetVoted; player.openInventory(invVote); return "true"; } public String skip(Player player) { if(!active) return Messages.voteNotFound; PlayerGame whoVoting = game.getPlayer(player); if(whoVoting == null) return Messages.plNotInGame; if(!whoVoting.isLive()) return Messages.youDied; if(votes.containsKey(whoVoting) || skipping.contains(whoVoting)) return Messages.youYetVoted; skipping.add(whoVoting); if(votes.size() + skipping.size() + 1 > game.getLivePlayers().size()) result(); return "true"; } public boolean isActive() { return active; } public void result() { if(!active) return; for(PlayerGame player: game.getPlayers()) { if(player.impostor) { Kits.imposter(player.getPlayer()); if(player.isLive()) player.timeoutKill = game.timeout_kill; } else { Kits.crewmate(player.getPlayer()); } Kits.colorArmor(player.getPlayer(), player.color); if(!(votes.containsKey(player) || skipping.contains(player))) skip(player.getPlayer()); } bar.removeAll(); active = false; game.timeoutMeeting = game.timeout_metting; if(skipping.size() > votes.size()) { for(PlayerGame player: game.getPlayers()) player.sendTitle(Messages.voteSkipped, ""); } else if(skipping.size() == votes.size()) { for(PlayerGame player: game.getPlayers()) player.sendTitle(Messages.notSingleDesition, ""); } else { Map<PlayerGame, List<PlayerGame>> votes = new HashMap<PlayerGame, List<PlayerGame>>(); PlayerGame player = null; for(PlayerGame _player: this.votes.keySet()) { List<PlayerGame> list; if(votes.containsKey(this.votes.get(_player))) list = votes.get(this.votes.get(_player)); else list = new ArrayList<PlayerGame>(); list.add(_player); votes.put(this.votes.get(_player), list); } int lastVotes = 0; for(PlayerGame _player: votes.keySet()) if(votes.get(_player).size() > lastVotes) { player = _player; lastVotes = votes.get(_player).size(); } for(PlayerGame list: votes.keySet()) if(list != player && votes.get(list).size() == lastVotes) { player.sendTitle(Messages.notSingleDesition, ""); return; } game.killPlayer(player); for(PlayerGame _player: game.getPlayers()) _player.sendTitle(player.getPlayer().getDisplayName() + (game.confirm_eject ? (player.impostor ? Messages.beImpostor : Messages.notBeImpostor) : Messages.beEject), ""); } } }
Dseym/amongUsMinecraft
src/game/Vote.java
248,201
public class Party { private int id, coalition, votes; private String name; private String logo; private VotingScheme handler; public Party(VotingScheme handler, Coalition coalition, String name, String logo, int votes) { this.handler = handler; this.id = handler.regParty(this); this.coalition = coalition.getId(); this.name = name; this.logo = logo; this.votes = votes; coalition.addParty(this); } public int getId() { return id; } public int getCoalition() { return coalition; } public int getVotes() { return votes; } public String getName() { return name; } public String getLogo() { return logo; } public double getPercentage() { return handler.getPercentage(this); } public void setVotes(int votes) { this.votes = votes; } public void incrVotes() { votes++; } }
FrancescoBorzi/Exit-Poll-Generator
src/Party.java
248,204
import java.util.ArrayList; import java.util.LinkedList; import javax.swing.JOptionPane; /** * @author * */ public class Election { //<Unit> citizens; ArrayList<Unit> candidates; String[] votes; /** * @param candidates */ public Election() { } /** * @return */ public Unit electionVote(ArrayList<Candidate> candidates, ArrayList<Unit> citizens) { Candidate winner = null; String[] options = new String[candidates.size()]; for(int i=0; i<options.length; i++) { options[i] = candidates.get(i).u.playerName; } for(int i=0; i<citizens.size(); i++) { String thisVote = (String) JOptionPane.showInputDialog(null, "Select the name of your vote:", citizens.get(i).playerName + " Vote Now", JOptionPane.PLAIN_MESSAGE, null, options, options[0]); for(Candidate c : candidates) { if(c.u.playerName.equalsIgnoreCase(thisVote)) c.votedFor(); } } for(Candidate c : candidates) { if(winner == null) winner = c; else if(c.getVotesFor() > winner.getVotesFor()) winner = c; } JOptionPane.showMessageDialog(null, "" + winner.u.playerName + " is now governor", "Governor", JOptionPane.INFORMATION_MESSAGE); return winner.u; } /** * @return */ public boolean yay_nayVote(Region r, ArrayList<Unit> citizens, Unit initiator) { LinkedList<Unit> yayVotes = new LinkedList<Unit>(); LinkedList<Unit> nayVotes = new LinkedList<Unit>(); System.out.println("Beginning YAY NAY Vote."); for(Unit u : citizens) { System.out.println("Taking Vote From: " + u.playerName); String thisVote = (String) JOptionPane.showInputDialog(null, u.playerName + " enter your vote (yay/nay/don't care):", JOptionPane.PLAIN_MESSAGE); if(thisVote.equalsIgnoreCase("yay")) yayVotes.add(u); else if(thisVote.equalsIgnoreCase("nay")) nayVotes.add(u); else System.out.println("Don't Care Vote"); } if(yayVotes.size() > nayVotes.size()) { r.founderRow = initiator.row; r.founderCol = initiator.col; JOptionPane.showMessageDialog(null, "Majority vote achieved", "Country Created", JOptionPane.INFORMATION_MESSAGE); return true; } else { JOptionPane.showMessageDialog(null, "Majority vote not achieved", "Country not created", JOptionPane.ERROR_MESSAGE); return false; } } }
JordanPorter/CS3716-Game
Election.java
248,205
/* VoteTec * Copyright (C) 2009 Eric Cederstrand, Carsten Schuermann * and Kenneth Sjøholm * * This file is part of VoteTec. * * VoteTec 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 3 of the License, or * (at your option) any later version. * * VoteTec 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 VoteTec. If not, see <http://www.gnu.org/licenses/>. */ package model; /* Represents the voter's choice, as recorded when the program * leaves confirm state and enters end state. There is one ballot * object for every candidate. */ public class Ballot { private final int votes; // Number of votes for this candidate private final String id; private final String value; /* Converts a choice object to a ballot object. */ public Ballot(Choice c) { this.id = c.getId(); this.value = c.getValue(); this.votes = c.getVotes(); } public String getId() { return id; } public String getValue() { return value; } public int getVotes() { return votes; } public String toString() { return "Ballot ID: "+id+" Value: "+value+" Vote count: "+votes; } }
demtech/votetec
model/Ballot.java
248,207
public class branch { private String id; private static int votes; public branch(String id) { this.id = id; votes=0; } public void setName(String id) { this.id = id; } public static void incrementVoteCount() { votes++; } public String getid() { return id; } public int getNumberOfVotes() { return votes; } public static void castVote() { // TODO Auto-generated method stub } }
crouge/uogTeamM5
src/branch.java
248,208
public class Review { private User user; private int userID; private int id; private String text; private double votes; private Boolean hide; private double difficulty; private double helpfulness; private double engagement; private double overall; public Review(User u, int id, String text, double d, double h, double e, double o) { this.user = u; this.userID = u.getID(); this.id = id; this.text = text; this.votes = 0.0; ranking = 0.0; hide = false; this.difficulty = d; this.helpfulness = h; this.engagement = e; this.overall = o; } //Getters / Setters public int hashCode() { return this.id; } public boolean equals(Review r) { return ((this.id == r.getID()) && this.userID = r.getUserID()) } public double getDifficulty() { return this.difficulty; } public double getHelpfulness() { return this.helpfulness; } public double getEngagement() { return this.engagement; } public double getOverall() { return this.overall; } public getUser() { return user; } public getUserID() { return userID; } //returns Review ID public getID() { return this.id; } public String getText() { return text; } public double getAggVotes() { return votes; } public void voteRank(Boolean positive) { if (positive) { votes += 1.0; } else { votes -= 1.0; } } public void hide() { this.hide = true; } public String toString() { return text; } }
niveditasankar/nets213
src/Review.java
248,211
import java.util.ArrayList; import java.util.Collection; import java.util.Date; public class Post { public int postNumber; public String posterName; public String flags; private Date date; private ArrayList<Vote> votes = new ArrayList<Vote>(); private boolean fishy = false; private boolean edited = false; private boolean duplicate = false; private boolean doublevote = false; private static int expectedVoteCount = 6; public Post(int postNumber, String posterName, String flags, Date date) { this.postNumber = postNumber; this.posterName = posterName; this.flags = flags; this.date = date; if (flags.contains("E")) edited = true; } public void add(Vote vote) { for (Vote v : votes) { if (v.getUser().getName().equals(vote.getUser().getName())) duplicate = true; if (v.getValue() == vote.getValue()) duplicate = true; } if (!votes.contains(vote)) { vote.post = this; votes.add(vote); } } public void add(Collection<Vote> votez) { for (Vote v : votez) { if (!votes.contains(v)) { v.post = this; votes.add(v); } } } public void clear() { votes.clear(); } public ArrayList<Vote> getVotes() { return votes; } public int getNumber() { return postNumber; } public String toString() { return "#" + postNumber + ", " + posterName + votes; } public boolean equals(Object o) { if (o instanceof Post) return (postNumber == ((Post) o).getNumber() && posterName .equals(((Post) o).posterName)); return false; } public int hashCode() { return posterName.hashCode() + postNumber; } public Date getDate() { return date; } public boolean isFishy() { return fishy; } public boolean isEdited() { return edited; } public boolean isDuplicate() { return duplicate; } public boolean isBadVotecount(){ return !(votes.size() == expectedVoteCount); } public void setFishy(boolean fishy) { this.fishy = fishy; } public boolean isDouble() { return doublevote; } public void setDouble(boolean doub){ this.doublevote = doub; } public static int getExpectedVoteCount() { return expectedVoteCount; } public static void setExpectedVoteCount(int expectedCount) { expectedVoteCount = expectedCount; } }
foolmoron/UotYmatic
src/Post.java
248,214
/** * File: Course.java * This class represents an individual Course and its characteristics * @author Tarek Solamy (Alsolame) * @version 1.0 5/4/2022 */ public class Course{ private String name; private String title; private int students; private int votes; /**Default Constructor for the Course class */ public Course(){} /**parametrized Constructor for the Course class */ public Course (String name, String title, int students, int votes){ this.name=name; this.title=title; this.students=students; this.votes=votes; } /** getter method for the name of the course *@return the name of the course *Time Complexity: O(1) */ public String getName(){ return name; } /** getter method for the title of the course *@return the title of the course *Time Complexity: O(1) */ public String getTitle(){ return title; } /** getter method for the number of students in the course *@return the number of students in the course *Time Complexity: O(1) */ public int getStudents(){ return students; } /** getter method for the votes of the course *@return the positive votes of the students *Time Complexity: O(1) */ public int getVotes(){ return votes; } /** setter method for the name of the course *@param the name of the course *Time Complexity: O(1) */ public void setName(String name){ this.name=name; } /** setter method for the title of the course *@param the title of the course *Time Complexity: O(1) */ public void setTitle(String title){ this.title=title; } /** setter method for the number of students in the course *@param the number of students in the course *Time Complexity: O(1) */ public void setStudents(int students){ this.students=students; } /** setter method for the votes of the course *@param the positive recommendation votes *Time Complexity: O(1) */ public void setVotes(int votes){ this.votes=votes; } /**This method calculates and return the recommendation score, the percentage * of students who recommend the course * @return the recommendation score percentage value *Time Complexity: O(1) */ public double getScore(){ return (((double) votes/(double)students)*100); } /* This method creates a string of the description of the course * @return a String representation of a full course description *Time Complexity: O(1) */ public String description(){ String courseDetails= getName() + ": " + getTitle() + " has been taken by " + getStudents() + " students and has a " + (int) getScore() + " % recommendation score."; return courseDetails; } /** *This method creates a string of the name and the sccore of the course *@return a String representation consisting of the course name and the recommendation score * Time Complexity: O(1) */ public String toString(){ String courseDetails= getName() + ": " + (int) getScore() + " %. "; return courseDetails; } }
tarek-debug/Course-Statistics
Course.java
248,215
/* * 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. */ package student.government.election.system; /** * * @author Lynford */ public class Winner { private String lastname,firstname,position; private int no_of_votes; public Winner(){ } public Winner(String lastname, String firstname, String position, int no_of_votes) { this.lastname = lastname; this.firstname = firstname; this.position = position; this.no_of_votes = no_of_votes; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public int getNo_of_votes() { return no_of_votes; } public void setNo_of_votes(int no_of_votes) { this.no_of_votes = no_of_votes; } }
lynfordlagondi828/Election-System-Using-Java
Winner.java
248,216
//Program P2.5 import java.util.*; import java.io.*; public class P2_5Voting { final static int MaxCandidates = 7; public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("votes.txt")); PrintWriter out = new PrintWriter(new FileWriter("results.txt")); Person[] candidate = new Person[MaxCandidates+1]; //get the names and set the scores to 0 for (int h = 1; h <= MaxCandidates; h++) candidate[h] = new Person(in.nextLine(), 0); VoteCount count = processVotes(candidate, MaxCandidates, in, out); printResults(out, candidate, MaxCandidates, count); in.close(); out.close(); } //end main public static VoteCount processVotes(Person[] list, int max, Scanner in, PrintWriter out) { VoteCount votes = new VoteCount(0, 0); //set valid, spoilt counts to 0 int v = in.nextInt(); while (v != 0) { if (v < 1 || v > max) { out.printf("Invalid vote: %d\n", v); ++votes.spoilt; } else { ++list[v].numVotes; ++votes.valid; } v = in.nextInt(); } //end while return votes; } //end processVotes public static void printResults(PrintWriter out, Person[] list, int max, VoteCount votes) { out.printf("\nNumber of voters: %d\n", votes.valid + votes.spoilt); out.printf("Number of valid votes: %d\n", votes.valid); out.printf("Number of spoilt votes: %d\n", votes.spoilt); out.printf("\nCandidate Score\n\n"); for (int h = 1; h <= MaxCandidates; h++) out.printf("%-18s %3d\n", list[h].name, list[h].numVotes); out.printf("\nThe winner(s)\n"); int win = getLargest(list, 1, MaxCandidates); int winningVote = list[win].numVotes; for (int h = 1; h <= MaxCandidates; h++) if (list[h].numVotes == winningVote) out.printf(" %s\n", list[h].name); } //end printResults public static int getLargest(Person[] list, int lo, int hi) { int big = lo; for (int h = lo + 1; h <= hi; h++) if (list[h].numVotes > list[big].numVotes) big = h; return big; } //end getLargest } //end class P2_5Voting class Person { String name; int numVotes; Person(String s, int n) { name = s; numVotes = n; } } //end class Person class VoteCount { int valid, spoilt; VoteCount(int v, int s) { valid = v; spoilt = s; } } //end class VoteCount
Apress/adv-topics-in-java
P2_5Voting.java
248,217
//Program P2.5 import java.util.*; import java.io.*; public class P2_5aVoting { final static int MaxCandidates = 7; public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("votes.txt")); PrintWriter out = new PrintWriter(new FileWriter("results.txt")); Person[] candidate = new Person[MaxCandidates+1]; //get the names and set the scores to 0 for (int h = 1; h <= MaxCandidates; h++) candidate[h] = new Person(in.nextLine(), 0); VoteCount count = processVotes(candidate, MaxCandidates, in, out); sortByVote(candidate, 1, MaxCandidates); printResults(out, candidate, MaxCandidates, count); in.close(); out.close(); } //end main public static VoteCount processVotes(Person[] list, int max, Scanner in, PrintWriter out) { VoteCount votes = new VoteCount(0, 0); //set valid, spoilt counts to 0 int v = in.nextInt(); while (v != 0) { if (v < 1 || v > max) { out.printf("Invalid vote: %d\n", v); ++votes.spoilt; } else { ++list[v].numVotes; ++votes.valid; } v = in.nextInt(); } //end while return votes; } //end processVotes public static void printResults(PrintWriter out, Person[] list, int max, VoteCount votes) { out.printf("\nNumber of voters: %d\n", votes.valid + votes.spoilt); out.printf("Number of valid votes: %d\n", votes.valid); out.printf("Number of spoilt votes: %d\n", votes.spoilt); out.printf("\nCandidate Score\n\n"); for (int h = 1; h <= MaxCandidates; h++) out.printf("%-18s %3d\n", list[h].name, list[h].numVotes); out.printf("\nThe winner(s)\n"); int win = getLargest(list, 1, MaxCandidates); int winningVote = list[win].numVotes; for (int h = 1; h <= MaxCandidates; h++) if (list[h].numVotes == winningVote) out.printf(" %s\n", list[h].name); } //end printResults public static void sortByVote(Person[] list, int lo, int hi) { //sort list[lo] to list[hi] in descending order by numVotes for (int h = lo + 1; h <= hi; h++) { Person hold = list[h]; int k = h - 1; //start comparing with previous item while (k >= lo && hold.numVotes > list[k].numVotes) { list[k + 1] = list[k]; --k; } list[k + 1] = hold; } //end for } //end sortByVote public static int getLargest(Person[] list, int lo, int hi) { int big = lo; for (int h = lo + 1; h <= hi; h++) if (list[h].numVotes > list[big].numVotes) big = h; return big; } //end getLargest } //end class P2_5aVoting class Person { String name; int numVotes; Person(String s, int n) { name = s; numVotes = n; } } //end class Person class VoteCount { int valid, spoilt; VoteCount(int v, int s) { valid = v; spoilt = s; } } //end class VoteCount
Apress/adv-topics-in-java
P2_5aVoting.java
248,218
/** * This class stores 2020 presidential election results by state. */ public class VotesByState { private String state; private int trumpVotes; private int bidenVotes; /** * Initializes the member variables to the respective arguments. * * @param state 2-letter code for the state * @param trumpVotes number of electoral votes won by Trump * @param bidenVotes number of electoral votes won by Biden */ public VotesByState(String state, int trumpVotes, int bidenVotes) { this.state = state; this.trumpVotes = trumpVotes; this.bidenVotes = bidenVotes; } /** * Returns the name of the state. * * @return a 2-letter state code */ public String getState() { return state; } /** * Returns the number of electoral votes won by Trump. * * @return number of electoral votes won by Trump */ public int getTrumpVotes() { return trumpVotes; } /** * Returns the number of electoral votes won by Biden. * * @return number of electoral votes won by Biden */ public int getBidenVotes(){ return bidenVotes; } /** * Constructs a string representation of the object * * @return A string representing the state, votes won by Trump, and votes won by Biden */ public String toString(){ return "(" + state + ", " + trumpVotes + ", " + bidenVotes + ")"; } public int getTotalVotes() { return trumpVotes + bidenVotes; } }
akwaed/laeti
VotesByState.java
248,220
package com.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Entity @Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString @Data public class Candidate { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(unique = true) private String candidate; private int votes; }
Azad12198/VotingApplicationCode
Candidate.java
248,221
/* *This class represents a wedding cake design and has a code, name, and a list of votes. */ import java.util.ArrayList; import java.util.List; public class Design { private int code; private String name; private List<Long> votes; public Design(int code, String name) { this.code = code; this.name = name; this.votes = new ArrayList<>(); } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Long> getVotes() { return votes; } public void setVotes(List<Long> votes) { this.votes = votes; } }
GRISONRF/multithread-studies
src/Design.java
248,222
import java.util.ArrayList; import java.util.Iterator; import java.util.Objects; /** * The type Person. * As the role of each player. * * @author Erfanm5152 * @version 0.1 */ public abstract class Person implements Runnable { // for check mute of role. private boolean isMuted; // for check that the role is alive. private boolean isAlive; // for check the ability of psychologist private boolean isPsychologicalSilence; // health of each role (use in night) private int health; // side of the role private Side side; // list of voters private ArrayList<Vote> votes; // handler of this role private Handler handler; /** * Instantiates a new Person. * * @param side the side of the role */ public Person(Side side) { this.side = side; this.health = 1; this.votes = new ArrayList<>(); this.isMuted = false; this.isAlive = true; this.isPsychologicalSilence = false; this.handler = null; } /** * Sets health. * * @param health the health */ public void setHealth(int health) { this.health = health; } /** * Increase health. */ public synchronized void increaseHealth() { this.health++; } /** * Decrease health. */ public synchronized void decreaseHealth() { this.health--; } /** * Is psychological silence boolean. * * @return the boolean */ public boolean isPsychologicalSilence() { return isPsychologicalSilence; } /** * Sets psychological silence. * * @param psychologicalSilence the psychological silence */ public void setPsychologicalSilence(boolean psychologicalSilence) { isPsychologicalSilence = psychologicalSilence; } /** * Gets health. * * @return the health */ public int getHealth() { return health; } /** * Gets side. * * @return the side */ public Side getSide() { return side; } /** * Add vote. * * @param voterName the voter name */ public synchronized void addVote(String voterName) { votes.add(new Vote(voterName)); } /** * Remove vote. * * @param voterName the voter name */ public void removeVote(String voterName) { Iterator<Vote> iterator = votes.iterator(); while (iterator.hasNext()) { Vote vote = iterator.next(); if (vote.getVoterName().equals(voterName)) { iterator.remove(); } } } /** * Gets votes. * * @return the votes */ public ArrayList<Vote> getVotes() { return votes; } /** * Size of votes int. * * @return the int */ public int sizeOfVotes() { return votes.size(); } /** * Refresh votes. */ public void refreshVotes() { Iterator<Vote> iterator = votes.iterator(); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } } /** * Gets handler. * * @return the handler */ public Handler getHandler() { return handler; } /** * check equality of two person * @param o second person * @return true or false */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return health == person.health && side == person.side; } @Override public int hashCode() { return Objects.hash(health, side); } /** * Sets handler. * * @param handler the handler */ public void setHandler(Handler handler) { this.handler = handler; } /** * Sets alive. * * @param alive the alive */ public synchronized void setAlive(boolean alive) { isAlive = alive; } /** * Number of votes int. * * @return the int */ public int numberOfVotes() { return votes.size(); } /** * Is muted boolean. * * @return the boolean */ public boolean isMuted() { return isMuted; } /** * Is alive boolean. * * @return the boolean */ public boolean isAlive() { return isAlive; } /** * Sets muted. * * @param muted the muted */ public void setMuted(boolean muted) { isMuted = muted; } }
erfanm5152/Mafia
src/Person.java
248,223
import java.util.*; class Admin extends LogIn { Scanner scanner = new Scanner(System.in); // constructor Admin(String username, String password) { super(username, password); } private ArrayList<String[]> elections = new ArrayList<>(); private ArrayList<Double> votingstatistics = new ArrayList<>(); private ArrayList<String> winnereslist = new ArrayList<>(); // method for adding new elections public void addnewElections(String name, String date) { String[] newElection = { name, date }; elections.add(newElection); votingstatistics.add(0.0); winnereslist.add("temp"); System.out.println("\n--- " + name + " Election added successfully ---"); } // method for accessing particular election public String[] getElection(int index) { if (index >= 0 && index < elections.size()) { return elections.get(index); } else { System.out.println("Invalid index!"); return null; } } // print the details of the all election public void showelections() { if (elections.size() == 0) { System.out.println("\n --- No election scheduled yet ---"); } else { for (int i = 0; i < elections.size(); i++) { String[] election = getElection(i); if (election != null) { System.out.println("\n ----Election " + (i + 1) + " details---- "); System.out.println(" Name: " + election[0]); System.out.println(" End Date: " + election[1]); } } System.out.println("\n ---------- End ----------"); } } // to access elections size in for loop in main code public ArrayList<String[]> getElections() { return elections; } public ArrayList<Double> getVotingStatistics() { return votingstatistics; } public ArrayList<String> getWinners() { return winnereslist; } // -------------- for adding candidates ------------// private ArrayList<String[]> candidates = new ArrayList<>(); private ArrayList<Integer> votes = new ArrayList<>(); // method for adding new candidate public void addnewCandidates(int inputchoice, String candidateName, String partyName, String gender, String mo_no, String city, String state) { int choice = inputchoice - 1; // getting election name from String array as per candidate choice String electionName = getElection(choice)[0]; String[] newCandidate = { electionName, candidateName, partyName, gender, mo_no, city, state }; votes.add(0); candidates.add(newCandidate); System.out.println("\n --- Candidate " + candidateName + " added successfully ---"); } // method to access a particular candidate public String[] getCandidate(int index) { if (index >= 0 && index < candidates.size()) { return candidates.get(index); } else { System.out.println("\n --- Invalid index! ---"); return null; } } // to access candidates size in for loop in main code public ArrayList<String[]> getCandidates() { return candidates; } public ArrayList<Integer> getVotes() { return votes; } // delete a candidate public void deleteCandidate() { boolean isdeleted = false; showcandidates(); if (candidates.size() != 0) { while (!isdeleted) { int candidateChoice = 0; try { System.out.print("\nEnter Your Choice: "); candidateChoice = scanner.nextInt(); scanner.nextLine(); } catch (InputMismatchException e) { System.out.println("\n --> Invalid input. Please enter an integer.\n" + "-->Exception: " + e); scanner.nextLine(); continue; } if (candidateChoice < 1 || candidateChoice > candidates.size()) { System.out.println("\n --- Invalid candidate choosen! --- \n"); } else { candidates.remove(candidateChoice - 1); System.out.println("\n --- Candidate removed successfully ---"); isdeleted = true; } } } } // print details of all candidates void showcandidates() { if (candidates.size() == 0) { System.out.println("\n --- No candidates registered yet ---\n"); } else { for (int i = 0; i < candidates.size(); i++) { String[] candidate = getCandidate(i); if (candidate != null) { System.out.println("\n ---- Candidate " + (i + 1) + " details----"); System.out.println("Election: " + candidate[0]); System.out.println("Candidate Name: " + candidate[1]); System.out.println("Party Name: " + candidate[2]); System.out.println("Gender: " + candidate[3]); System.out.println("Mobile Number: " + candidate[4]); System.out.println("City: " + candidate[5]); System.out.println("State: " + candidate[6]); System.out.println(); } } System.out.println("\n ----------------- End -----------------"); } } // method for approving voter public static void approveVoter(int index, Voter[] voters) { if (index == 0) { System.out.println("\n --- No voter has registered ---"); } else { boolean allApproved = true; for (int i = 0; i < index; i++) { if (voters[i] != null && !voters[i].isApproved()) { allApproved = false; System.out.println("\n-----Voter " + (i + 1) + " details------"); voters[i].showdetails(); int choice3 = 0; while (choice3 != 1 && choice3 != 2) { System.out.println("\n--- Enter 1 to approve ---"); System.out.println("--- Enter 2 to disapprove ---"); Scanner sc = new Scanner(System.in); try { System.out.print("\nEnter Your Choice: "); choice3 = sc.nextInt(); sc.nextLine(); } catch (InputMismatchException e) { System.out.println("\n --> Invalid input. Please enter an integer.\n" + "-->Exception: " + e); sc.nextLine(); continue; } if (choice3 == 1) { voters[i].setApprovedStatus(true); System.out.println("\n ------ Voter " + (i + 1) + " approved ------"); } else if (choice3 == 2) { voters[i].setApprovedStatus(false); System.out.println( "\n --- Voter " + (i + 1) + " is not approved due to incorrect details ---"); } else { System.out.println("\n ---- Invalid choice ----"); } } } } if (allApproved) { System.out.println("\n--- All voters are already approved ---"); } } } // method for voting a candidate public void voteForCandidate(int index) { if (index >= 0 && index < candidates.size()) { String[] candidate = candidates.get(index); if (candidate != null) { int currentVotes = votes.get(index); // increment vote votes.set(index, currentVotes + 1); System.out.println("\n ---- Vote registered successfully for " + candidate[1] + " ----"); } else { System.out.println("\n ---- Invalid candidate index ----"); } } } private ArrayList<Integer> NOTAvotecount = new ArrayList<>(100); { for (int i = 0; i < 100; i++) { NOTAvotecount.add(0); } } public ArrayList<Integer> getNOTAVotes() { return NOTAvotecount; } public void voteForNOTA(int index) { try { if (index >= 0 && index < elections.size()) { int currentnotaVotes = NOTAvotecount.get(index); // increment vote NOTAvotecount.set(index, currentnotaVotes + 1); }else { System.out.println("\n ---- Invalid Election index ----"); } } catch (Exception e) { System.out.println("Exception: " + e); } } // method to show election details public void showresult() { showelections(); if (elections.size() != 0) { int choice5=0; do { try { System.out.print("\nChoose election:"); choice5 = scanner.nextInt(); scanner.nextLine(); } catch (InputMismatchException e) { System.out.println("\n --> Invalid input. Please enter an integer.\n" + "-->Exception: " + e); scanner.nextLine(); continue; } if (choice5 < 1 || choice5 > elections.size()) { System.out.print("\n---Invalid choice. Please choose again---\n "); } } while (choice5 < 1 || choice5 > elections.size()); String chosenElection = getElection(choice5 - 1)[0]; if (candidates.size() == 0) { System.out.println("\n ---- No candidates registered yet ----"); } else { System.out.println("\n ------ Election Results for " + chosenElection + " ---------\n"); int maxVotes = Integer.MIN_VALUE; System.out.println("---------------------------------"); ArrayList<String[]> tiedCandidates = new ArrayList<>(); for (int j = 0; j < candidates.size(); j++) { String[] candidate = getCandidate(j); if (candidate != null && candidate[0].equals(chosenElection)) { System.out.println("----Candidate " + (j + 1) + " details----"); System.out.println("Name : " + candidate[1]); System.out.println("Party : " + candidate[2]); int candidateVotes = votes.get(j); System.out.println("Votes : " + candidateVotes); System.out.println(); if (candidateVotes == maxVotes) { tiedCandidates.add(candidate); } else if (candidateVotes > maxVotes) { maxVotes = candidateVotes; tiedCandidates.clear(); tiedCandidates.add(candidate); } } } System.out.println("---------------------------------"); // Display winner details if (tiedCandidates.isEmpty()) { System.out.println("\n----- No votes cast yet -----"); } else if (tiedCandidates.size() == 1) { String[] winner = tiedCandidates.get(0); if (winner != null) { System.out.println("\n-------------------------"); System.out.println("| Winner |"); System.out.println("-------------------------"); System.out.println("| Name: " + winner[1] + " |"); System.out.println("| Party: " + winner[2] + " |"); System.out.println("| Votes: " + maxVotes + " |"); System.out.println("-------------------------"); winnereslist.set(choice5 - 1 ,winner[1]); } } else { // show all tied candidates. System.out.println("\n ---- There is a tie between the following candidates ----"); for (int i = 0; i < tiedCandidates.size(); i++) { String[] tiedCandidate = tiedCandidates.get(i); if (tiedCandidate != null) { System.out.println( "--> " + (i + 1) + ". Name: " + tiedCandidate[1] + ", Party: " + tiedCandidate[2]); } } int adminVoteIndex=0; try { System.out.println("\n----> Admin, please vote to break the tie."); System.out.print("----> Enter the index of the candidate you want to vote for: "); adminVoteIndex = scanner.nextInt(); scanner.nextLine(); } catch (InputMismatchException e) { System.out.println("\n --> Invalid input. Please enter an integer.\n" + "-->Exception: " + e); scanner.nextLine(); } // Increment the vote count for the chosen candidate if (adminVoteIndex >= 1 && adminVoteIndex <= tiedCandidates.size()) { String[] winner = tiedCandidates.get(adminVoteIndex - 1); if (winner != null) { System.out.println("\n-------------------------"); System.out.println("| Winner |"); System.out.println("-------------------------"); System.out.println("| Name: " + winner[1] + " |"); System.out.println("| Party: " + winner[2] + " |"); System.out.println("| Votes: " + (maxVotes + 1) + " |"); System.out.println("-------------------------"); winnereslist.set(choice5 - 1 ,winner[1]); for (int j = 0; j < candidates.size(); j++) { String[] candidate = getCandidate(j); if (candidate != null && candidate[1].equals(winner[1])) { int candidateVotes = votes.get(j); votes.set(j,candidateVotes+1); } } } } else { System.out.println("\n --- Invalid candidate index ---"); } } } } } // method to show statistics of election public void showstatistics(int index, Voter[] voters) { showelections(); if (elections.size() != 0) { int choice6=0; do { try { System.out.print("\nChoose election:"); choice6 = scanner.nextInt(); scanner.nextLine(); } catch (InputMismatchException e) { System.out.println("\n --> Invalid input. Please enter an integer.\n" + "-->Exception: " + e); scanner.nextLine(); continue; } if (choice6 < 1 || choice6 > elections.size()) { System.out.print("\n---Invalid choice. Please choose again---\n "); } } while (choice6 < 1 || choice6 > elections.size()); String chosenElection = getElection(choice6 - 1)[0]; if (index == 0) { System.out.println("\n --- No voter has registered ---"); } else { int totalVoters = 0; for (int i = 0; i < index; i++) { if (voters[i].isApproved()) { totalVoters++; } } int totalVotesCast = 0; for (int i = 0; i < index; i++) { if (voters[i].hasVotedForElection(choice6 - 1)) { totalVotesCast++; } } double percentageVotingDone = ((double) totalVotesCast / totalVoters) * 100; votingstatistics.set(choice6-1,percentageVotingDone); System.out.println("\n ---- Percentage of voting done for " + chosenElection + ": " + String.format("%.2f%%", percentageVotingDone) + " ----\n"); System.out.println("Number of NOTA votes for "+ chosenElection + " is: " + NOTAvotecount.get(choice6 - 1)); } } } }
utsav2110/Online-Election-System
Code/Admin.java
248,224
import java.util.*; public class Tally { private String name; private static int numItems = 0; private int[] ranks; private int sumRanks; private int votes; private static int totalVotes; //some of these instance variables are not used, I was going to use them for additional methods, edge cases, etc. but ran out of time. //Will add this to the long list of things I will do if I ever come back to modify this public Tally(String name, int numOptions) { this.name = name; ranks = new int[numOptions]; numItems++; } public int getNumRank(int place) { return ranks[place]; } public String toString() { String toString = name + Arrays.toString(ranks); return toString; } public void raiseTally(int i) { ranks[i]++; sumRanks += (i + 1); votes++; totalVotes++; } public int getSumRanks() { return sumRanks; } public String getName() { return name; } public int getTotalVotes() { return totalVotes; } public int getVotes() { return votes; } }
tolympia/seminar2023
unit0/Tally.java
248,225
import java.util.ArrayList; public class Student { private String name; private String matr; private ArrayList<Integer> votes; public Student(String name, String matr) { setName(name); setMatr(matr); setVotes(new ArrayList<>()); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMatr() { return matr; } public void setMatr(String matr) { this.matr = matr; } public ArrayList<Integer> getVotes() { return votes; } public void setVotes(ArrayList<Integer> votes) { this.votes = votes; } // Method of adding votes public void addVotes(int vote) throws Exception { if (vote < 18 || vote > 30) { throw new Exception("Il voto deve essere compreso tra 18 e 30"); } getVotes().add(vote); } // Average calculation method public double mediaVotes() { if (getVotes().isEmpty()) { return 0.0; } int sum = 0; for (int vote : getVotes()) { sum += vote; } return (double) sum / getVotes().size(); } // Student details public String getDetails() { return "Studente: " + getName() + " - " + " Matricola: " + getMatr() + " - " + "Votes: " + getVotes() + " - " + "Media: " + mediaVotes(); } @Override public String toString() { return getDetails(); } }
mattiamurgia/2024-06-26-java-end-1
src/Student.java
248,227
//**** Classe Principale **** //****************************************************** //**** email de l'autheur : [email protected] //****************************************************** //**** date : du 10 au 12 2017 //**** projet Ihm Application de statistiques de Vote //**** nom de l'application : Vote Stat //******************************************* import javax.swing.JFrame ; import javax.swing.JPanel ; import javax.swing.JButton ; import javax.swing.JMenuBar ; import javax.swing.Timer ; import java.awt.Image ; import java.awt.event.ActionEvent; import java.awt.event.ActionListener ; import java.awt.Toolkit ; import java.awt.EventQueue ; import interfaces.VotePane ; import sql_connection.* ; public class VoteStat extends JFrame { public static VotePane p ; private Timer t ; private int i = 0 ; public VoteStat() { VoteCreateDb vb = new VoteCreateDb("vote") ; //setSize(getHeight(),getWidth()) ; setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ; setExtendedState(JFrame.MAXIMIZED_BOTH) ; setTitle("Vote Stats") ; VoteScreenSave vs = new VoteScreenSave() ; add(vs) ; p = new VotePane() ; p.repaint() ; p.revalidate() ; t = new Timer(100,new ActionListener() { public void actionPerformed( ActionEvent e) { if(i>10) { vs.setVisible(false) ; add(p) ; t.stop() ; } System.out.println(i) ; i++ ; } }) ; t.start() ; setJMenuBar(new VoteMenuBar()) ; java.net.URL url = ClassLoader.getSystemResource("img/statistics-market-icon26.png");//new URL("img/camera.png"); Toolkit kit = Toolkit.getDefaultToolkit(); Image img = kit.createImage(url); //getFrames(). setIconImage(img); } public static void main(String [] args) { EventQueue.invokeLater(new Runnable() { public void run() { VoteStat e = new VoteStat() ; e.setVisible(true) ; } }) ; } }
nassim-fox/VoteStat
src/VoteStat.java
248,228
import java.util.ArrayList; public class Candidate { String name; String surname; ArrayList<DateInterval> votes_of_interval; public Candidate(String name, String surname , ArrayList<DateInterval> votes_of_interval){ this.name=name; this.surname=surname; this.votes_of_interval=votes_of_interval; } public void setName(String name){ this.name=name; } public String getName(){ return name; } public void setSurname(String surname){ this.surname=surname; } public String getSurname(){ return surname; } public void setVotes_of_interval(ArrayList<DateInterval> votes_of_interval){ this.votes_of_interval=votes_of_interval; } public ArrayList<DateInterval> getVotes_of_interval(){ return votes_of_interval; } }
JohnIpsi/VotingSystem_App
src/Candidate.java