file_id
int64
1
250k
content
stringlengths
0
562k
repo
stringlengths
6
115
path
stringlengths
1
147
249,614
public class Cube extends Square { private int depth; public void setDepth(int d) { depth = d; } public void computeSurfaceArea() { int area = 2*getHeight()*getWidth() + 2*getWidth()*depth + 2*getHeight()*depth; setSurfaceArea(area); } }
melmar12/MISJavaCode
Cube.java
249,618
public class Post{ private String mainText; private int id; static int count = 1; private int posterId; private int childOfId; private String title; private int depth; private String posterName; public Post(String mainText, String title){ this.mainText = mainText; id = count; posterId = 0; id = count; this.title = title; childOfId = 0; count++; } public Post(String mainText, String title, int childOfId){ this.mainText = mainText; id = count; count++; } public Post(String mainText, int childOfId, int depth, String posterName){ this.mainText = mainText; this.childOfId = childOfId; this.depth = depth; this.id = count; if(posterName.equals("(0 children)")){ posterName = "[deleted]"; } this.posterName = posterName; count++; } public Post(String mainText){ this.mainText = mainText; } public String toString(){ return "Poster name " + posterName + "\nReply id: " + id + " Reply to: " + childOfId + "\n" + mainText; } public String getName(){ return posterName; } public String getTitle(){ return title; } public String getMainText(){ return mainText; } public int getId(){ return id; } public int getParent(){ return childOfId; } }
Admiral-Arch/Freddit
Post.java
249,620
// Evolve deep random projection neural network class class ENet { final int vecLen; final int density; final int depth; final int precision; final long hash; float parentCost; float[][][] weights; float[][][] mWeights; float[] workA; float[] workB; float[] workC; float[] workD; RP rp; Xor128 rnd; // vecLen must be 2,4,8,16,32..... ENet(int vecLen, int density, int depth,int precision) { this.vecLen=vecLen; this.density=density; this.depth=depth; this.precision=precision; parentCost=Float.POSITIVE_INFINITY; weights=new float[depth][density][vecLen]; mWeights=new float[depth][density][vecLen]; workA=new float[vecLen]; workB=new float[vecLen]; workC=new float[vecLen]; workD=new float[vecLen]; rp=new RP(); rnd=new Xor128(); hash=rnd.nextLong(); for (int i=0; i<depth; i++) { for (int j=0; j<density; j++) { for (int k=0; k<vecLen; k++) { weights[i][j][k]=rnd.nextFloatSym(); } } } float sc=1f/(float)Math.sqrt(density); for (int j=0; j<density; j++) { rp.scale(weights[depth-1][j], weights[depth-1][j], sc); } } void recall(float[] resultVec, float[] inVec) { rp.adjust(workA, inVec); long h=hash; for (int i=0; true; i++) { System.arraycopy(workA, 0, workB, 0, vecLen); java.util.Arrays.fill(resultVec, 0f); for (int j=0; j<density; j++) { rp.fastRP(workA, h++); rp.fastRP(workB, h++); rp.multiply(workC, workA, workB); rp.fastRP(workC, h++); rp.multiplyAddTo(resultVec, workC, weights[i][j]); } if (i==depth-1) break; rp.adjust(workA, resultVec); } } // the elements of targetVecs should have a magnitude of around 0 to 1. void train(float[][] targetVecs, float[][] inputVecs) { for (int i=0; i<depth; i++) { // create mutated weights for (int j=0; j<density; j++) { for (int k=0; k<vecLen; k++) { mWeights[i][j][k]=rnd.mutateXSym(weights[i][j][k], precision); } } } float[][][] t=weights; // swap the weights with the mutated weights weights=mWeights; mWeights=t; float cCost=0f; //evaluate the cost of the mutated weights. for (int i=0; i<targetVecs.length; i++) { recall(workD, inputVecs[i]); rp.subtract(workD, targetVecs[i], workD); cCost+=rp.sumSq(workD); } if (cCost<=parentCost) { parentCost=cCost; // keep the mutated weights as new parent } else { // else swap back the old unmutated parent weights t=weights; weights=mWeights; mWeights=t; } } float getCost(){ return parentCost; } }
hyperdrive/EvoNet
ENet.java
249,628
//Program to find out the volume of a box by user given input. import java.util.*;; class Box { int width; int height; int depth; } // This class declares an object of type Box. class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; Scanner sc = new Scanner(System.in); System.out.print("Length: "); mybox.width = sc.nextInt(); System.out.print("Breadth: "); mybox.depth = sc.nextInt(); System.out.print("Height: "); mybox.height = sc.nextInt(); vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol); } }
anxkhn/Java-Lab
Box.java
249,630
class Box { double width; double height; double depth; } // This class declares an object of type Box. class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; // assign values to mybox's instance variables mybox.width = 10; mybox.height = 20; mybox.depth = 15; // compute volume of box vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol); } }
vranda0108/Java-Programming
Box.java
249,636
package com.java; public class Box { double width,depth,height; Box(double width,double depth,double height){ this.width = width; this.depth = depth; this.height = height; } double volume(){ return (this.height * this.depth * this.width); } }
shambhav199/JavaCode
Box.java
249,640
public class Box { double length; double width; double depth; Box(){ this.length = 10; this.width = 10; this.depth = 10; } Box(double l, double w, double d) { this.length = l; this.width = w; this.depth = d; } Box(double l){ this.width = this.depth = this.length = l; } Box(double l, double w){ this.length = l; this.width = w; this.depth = 10; } void setDimension(double l, double w, double d){ this.length = l; this.width = w; this.depth = d; return; } double computeVolume() { return length*width*depth; } void volume() { double vol; vol = length*width*depth; System.out.println("Volume of Box : " + vol ); return; } }
Prakhar29Sharma/100DaysCodingChallenge
Box.java
249,644
/* * Class: CMSC203 * Instructor: Khandan Vahabzadeh Monshi * Description: Method descriptions are provided above their respective headers * Due: 10/25/2021 * Platform/compiler: Eclipse IDE * I pledge that I have completed the programming assignment independently. I have not copied the code from a student or any source. I have not given my code to any student. Print your Name here: Frank Deegbe */ /** * Represents a plot object * @author Frank * */ public class Plot { //Fields private int x; private int y; private int width; private int depth; //Constructors /** * Copy Constructor, creates a new object using the information of the object passed to it. * @param p */ public Plot(Plot p) { // Copy x = p.x; y = p.y; width = p.width; depth = p.depth; } /** * No-arg Constructor, creates a default Plot with args x=0, y=0, width=1, depth=1 */ public Plot() { // No-arg x = 0; y = 0; width = 1; depth = 1; } /** * Parameterized Constructor * @param x * @param y * @param width * @param depth */ public Plot(int x, int y, int width, int depth) { //Parameterized this.x = x; this.y = y; this.width = width; this.depth = depth; } //Methods /** * takes a Plot instance and determines if the current plot contains it. Note that the determination should be inclusive, in other words, if an edge lies on the edge of the current plot, this is acceptable. * @param r * @return Returns true if this plot encompasses the parameter, false otherwise */ public boolean overlaps(Plot r) { boolean u = true; if (x >= r.x + r.width || y >= r.y + r.depth || x + width <= r.x || y + depth <= r.y) u = false; return u; } /** * takes a Plot instance and determines if the current plot contains it. Note that the determination should be inclusive, in other words, if an edge lies on the edge of the current plot, this is acceptable. * @param p * @return Returns true if this plot encompasses the parameter, false otherwise */ public boolean encompasses(Plot p) { if (x <= p.getX() && y <= p.getY() && x + width >= p.getX() + p.getWidth() && y + depth >= p.getY() + p.getDepth()) { return true; } return false; } /** * * Set the x value * @return x - the x value to set */ public int getX() { return x; } /** * Return the Y value * @return the y value */ public int getY() { return y; } /** * Set the width value * @return width - the width value to set */ public int getWidth() { return width; } /** * Sets the depth value * @return depth - the depth value to set */ public int getDepth() { return depth; } /** * Set the x value * @param x - the x value to set */ public void setX(int x) { this.x = x; } /** * Sets the y value * @param y - the y value to set */ public void setY(int y) { this.y = y; } /** * Set the width value * @param width the width value to set */ public void setWidth(int width) { this.width = width; } /** * Set the depth value * @param depth - the depth value to set */ public void setDepth(int depth) { this.depth = depth; } /** * Prints out the name, city, owner and rent amount for a property * @return the string representation of a Plot object in the following format: Upper left: (1,1); Width: 3 Depth: 3 */ public String toString() { return("Upper left: (" + x + "," + y + "); Width: " + width + " Depth: " + depth); } }
fdeegbe/Plot-Manager
Plot.java
249,646
404: Not Found
Manav-Khandurie/Practice_LeetCode
q111.java
249,648
404: Not Found
Manav-Khandurie/Practice_LeetCode
q104.java
249,649
import java.util.Queue; import java.util.LinkedList; import java.util.Stack; public class Main{ public static void main(String[] args){ Queue<TNode> Q = new LinkedList<TNode>(); BST tree = new BST(); tree.insertNode(5); tree.insertNode(4); tree.insertNode(6); tree.insertNode(3); tree.insertNode(15); tree.insertNode(35); tree.insertNode(12); tree.insertNode(13); System.out.println(); System.out.println(tree.total_number_node()); } } //node class for BST class TNode{ int data; TNode right; TNode left; TNode(){ data=0; right=null; left = null; } TNode(int value){ data = value; right = null; left = null; } } //################ class BST{ TNode root; public boolean insertNode(int v){ TNode nNode=new TNode(v); recursiveInsertNode(nNode,root); return true; } private void recursiveInsertNode(TNode node,TNode root1){ if(root== null){ root = node; return; } if(node.data < root1.data) if(root1.left == null) root1.left = node; else{ recursiveInsertNode(node, root1.left); } else if (node.data > root1.data) if(root1.right == null) root1.right = node; else recursiveInsertNode(node, root1.right); } TNode search(int v){ return recursiveSearch(root,v); } private TNode recursiveSearch(TNode node,int v){ if(node.data == v) return node; else if (node.data > v) return recursiveSearch(node.right, v); else return recursiveSearch(node.left, v); } void DFS(TNode node){ if(node != null){ Stack<TNode> s = new Stack<TNode>(); TNode n = node; s.push(n); while(!s.isEmpty()){ n = s.pop(); System.out.println(n.data); if(n.right!=null){ s.push(n.right); } if(n.left!=null){ s.push(n.left); } } } } void BFS(TNode node,Queue<TNode> Q){ // Iterative if(node != null){ TNode n = node; Q.add(n); while(!Q.isEmpty()){ n = Q.remove(); System.out.print(n.data+" "); if(n.left!=null) Q.add(n.left); if(n.right!=null) Q.add(n.right); } } } void BFS_recursive(TNode node,Queue<TNode> Q){ // Look if recursive is possible if(node!=null){ System.out.println(node); if(node.left!=null){ Q.add(node.left); } if(node.right!=null){ Q.add(node.right); } if(!Q.isEmpty()){ BFS_recursive(Q.remove(),Q); } } } void DFS_inorder(TNode node){ if(node!=null){ DFS_inorder(node.left); System.out.println(node.data); DFS_inorder(node.right); } } void DFS_preorder(TNode node){ if(node!=null){ System.out.println(node.data); DFS_preorder(node.left); DFS_preorder(node.right); } } void DFS_postorder(TNode node){ if(node!=null){ DFS_postorder(node.left); DFS_postorder(node.right); System.out.println(node.data); } } TNode Find_parent(TNode node,int value){ TNode temp = new TNode(value); if(node.left != null && node.left.data == temp.data ) return node; else if (node.right !=null && node.right.data == temp.data ) return node; else{ if(temp.data>node.data) return Find_parent(node.right, value); else if(temp.data<node.data) return Find_parent(node.left, value); else return null; } } int depth_node(int val,TNode node ){ int count = 0; if(root.data == val) return 0; else{ if(node.data>val){ count++; if(node.left != null){ count += depth_node(val, node.left); } } if(node.data<val){ count++; if(node.right !=null){ count+=depth_node(val, node.right); } } if(node.data == val){ return count++; } } return count; } int depth_tree(){ int count = 0; TNode node = root; Queue<TNode> QQ = new LinkedList<TNode>(); QQ.add(node); while(!QQ.isEmpty()){ TNode temp = QQ.remove(); if (temp.left!=null){ QQ.add(temp.left); } if(temp.right!=null){ QQ.add(temp.right); } int val = depth_node(temp.data, root); if (val>count) count= val; } return count; } boolean Full_Or_Not_Tree(){ if(root == null){ return true; } TNode node = root; Queue<TNode> QQ = new LinkedList<TNode>(); QQ.add(node); while(!QQ.isEmpty()){ TNode temp = QQ.remove(); if (temp.left!=null){ QQ.add(temp.left); } if(temp.right!=null){ QQ.add(temp.right); } if(temp.left != null && temp.right == null || temp.left == null && temp.right != null){ return false; } } return true; } boolean Same_Level(TNode node_1,TNode node_2){ int node_1_depth = depth_node(node_1.data, node_1); int node_2_depth = depth_node(node_2.data, node_2); if(node_1_depth == node_2_depth) return true; else return false; } int total_number_node(){ if(root==null) return 0; else{ int count=1; Queue<TNode> qq = new LinkedList<>(); qq.add(root); TNode temp = root; while(!qq.isEmpty()){ temp = qq.remove(); if(temp.left !=null){ qq.add(temp.left); count++; } if(temp.right !=null){ qq.add(temp.right); count++; } } return count; } } boolean check_equal(TNode node_2){ Queue<TNode> qq = new LinkedList<>(); Queue<TNode> q2 = new LinkedList<>(); qq.add(node_2); while(!qq.isEmpty()){ TNode temp = qq.remove(); // Complete this later } } }
Ahmad1015/BST-Implementation-Java
Main.java
249,654
package assignment4; public class Plot { private int x; private int y; private int width; private int depth; //creates a plot using a no-arg constructor, which sets depth and width to 1 as default public Plot() { depth = 1; width = 1; } //creates a plot using parameterized constructor public Plot(int x, int y, int width, int depth) { this.x = x; this.y = y; this.width = width; this.depth = depth; } //creates a plot by coping from another constructor public Plot(Plot copyPlot) { this(copyPlot.x, copyPlot.y, copyPlot.depth, copyPlot.width); } public int getX() { return x; } public int getY() { return y; } public int getDepth() { return depth; } public int getWidth() { return width; } public void setX(int newX) { x = newX; } public void setY(int newY) { y = newY; } public void setDepth(int newDepth) { depth = newDepth; } public void setWidth(int newWidth) { width = newWidth; } public boolean overlaps(Plot otherPlot) { //Coordinate point on lower-right int x2 = x+width; int y2 = y; int x2Other = otherPlot.x + otherPlot.width; int y2Other = otherPlot.y; //coordinate point on upper-left int x3 = x; int y3 = y+depth; int x3Other = otherPlot.x; int y3Other = otherPlot.y + otherPlot.depth; //coordinate point on upper-right int x4 = x+width; int y4 = y+depth; int x4Other = otherPlot.x + otherPlot.width; int y4Other = otherPlot.y + otherPlot.depth; //when the x-value of the point is between 2 points if(x > otherPlot.x && x< x2Other) { // if the y-value is in the middle of the plot if(y < y3Other && y > otherPlot.y) { return true; } } // when the x-value is between 2 points but its y-value is the same as the instance plot else if(x > otherPlot.x && x< x2Other) { if(y == otherPlot.y) { if(y3 > otherPlot.y && y3 < y3Other) { return true; } } } //when the y-value from the bottom has an upper-left point that overlaps the instance plot else if(y < otherPlot.y) { if(y3 > otherPlot.y) { return true; } } //when the x-value is outside but its lowerRight overlaps the instance plot else if(x < otherPlot.x) { if(x2 > x2Other) { if(y2 > otherPlot.y && y2 < y3Other) { return true; } } } return false; } public boolean encompasses(Plot otherPlot) { // if the given plot is between the y-value one the vertical axis or givenPlot's y-value is equal to that of the current plot if((otherPlot.y < (y+width) && otherPlot.y > y) || otherPlot.y == y) { // if the given plot's lower-right x-value is less than or equal to that of the current plot, //then the given plot is contained if((otherPlot.x + otherPlot.width) <= (x+width)) { return true; } } return false; } public String toString() { return x+","+y+","+width+","+depth; } }
Iftef165/CMSC203-Projects
Plot.java
249,655
import java.util.HashSet; import java.util.Hashtable; /** * Prefix-Trie. Supports linear time find() and insert(). * Should support determining whether a word is a full word in the * Trie or a prefix. * * @author */ public class Trie { TrieNode root; // sentinel node mapping to all starting chars static int depth; HashSet<String> words; // contains all inserted words public static class TrieNode { private boolean endOfWord; // indicates nodes that are end of word private Hashtable<Character, TrieNode> suffix; private int priority; // depth priority for alphSort private double priority2; // word weight, 0.0 if not endOfWord (AC) private double maxPriority; // current max priority connected to node (AC) private String prev; // null if not endOfWord node, else contains // word string public TrieNode() { priority = 0; priority2 = 0.0; maxPriority = 0.0; endOfWord = false; suffix = new Hashtable<>(); } // Temp node used for autocomplete priority DFS public TrieNode(double p2, String s) { endOfWord = true; priority2 = p2; maxPriority = p2; prev = s; } /** Getters/Setters for TrieNode */ public void changeEndOfWord() { endOfWord = true; } public boolean getEndOfWord() { return endOfWord; } public int getPriority() { return priority; } public String getPrev() { return prev; } public void setPriority(int i) { priority = i; } public double getPriority2() { return priority2; } public void setPriority2(double d) { priority2 = d; } public double getMaxPriority() { return maxPriority; } public void setMaxPriority(double d) { maxPriority = d; } // AC Priority Queue set from least to greatest // Invert max priority to order TrieNodes in PQ by // increasing priority public double getDepthPriority() { return -maxPriority; } public Hashtable<Character, TrieNode> getSuffix() { return suffix; } } public Trie() { root = new TrieNode(); words = new HashSet<>(); } /** Searches a Trie for a given string, returns true if found * else false * * Runtime: O(N) - N = length of string * @param s - inputted string * @param isFullWord - indicates if full word must be found * @return */ public boolean find(String s, boolean isFullWord) { // Illegal Arguments: s is null or empty if (s == null) { throw new IllegalArgumentException("String is null."); } if (s.equals("")) { throw new IllegalArgumentException("String is empty."); } // Iterate through the tree checking for letters TrieNode currTN = root; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); // Return false when letter is not contained if (!currTN.getSuffix().containsKey(c)) { return false; } currTN = currTN.getSuffix().get(c); } // TrieNode's endOfWord must be true if isFullWord is true if (isFullWord) { return currTN.getEndOfWord(); } return true; } /** Inserts a string into Trie - not used in AC/AS * * Runtime: O(N) amortized - N = length of string * @param s - inputted string */ public void insert(String s) { // Illegal Arguments - s is null or empty if (s == null) { throw new IllegalArgumentException("String is null."); } if (s.equals("")) { throw new IllegalArgumentException("String is empty."); } TrieNode currTN = root; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); Hashtable<Character, TrieNode> suffix = currTN.getSuffix(); // Move to specific character's tree node if already initiated // else create a new tree node for that character if (suffix.containsKey(c)) { currTN = suffix.get(c); } else { suffix.put(c, new TrieNode()); currTN = suffix.get(c); } } currTN.changeEndOfWord(); } /** Insert a string into Trie, used for Alphabet sort * gives each node a priority value to ensure priority queue DFS works * --- further down the tree = higher priority --- * * Runtime: O(N) - N = length of string * @param s - inputted string * @param priority - hashtable linking characters and priority values * @param alphLen - length of given alphabet */ public void asinsert(String s, Hashtable<Character, Integer> priority, int alphLen) { // Illegal Arguments - s is null or empty if (words.contains(s)) { return; } if (s == null) { throw new IllegalArgumentException("String is null."); } if (s.equals("")) { throw new IllegalArgumentException("String is empty."); } TrieNode currTN = root; depth = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); Hashtable<Character, TrieNode> suffix = currTN.getSuffix(); // Move to specific character's tree node if already initiated // else create a new tree node for that character if (suffix.containsKey(c)) { currTN = suffix.get(c); depth++; } else { suffix.put(c, new TrieNode()); currTN = suffix.get(c); currTN.setPriority(priority.get(c) - (depth * alphLen)); depth++; } } currTN.changeEndOfWord(); currTN.prev = s; words.add(s); } /** inserts a String with a given weight into the Trie - used for AC * priority2 - value of endNode corresponding to specific string * --- if !endOfNode, priority2 == 0.0 * maxPriority - value of highest priority string connected further down * in the Trie * * Runtime: O(N) - N = length of string * @param s - inputted string * @param weight - weight of inputted string */ public void acInsert(String s, double weight) { if (words.contains(s)) { return; } if (s == null) { throw new IllegalArgumentException("String is null."); } TrieNode currTN = root; if (root.getMaxPriority() < weight) { root.setMaxPriority(weight); root.prev = s; } depth = 1; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); Hashtable<Character, TrieNode> suffix = currTN.getSuffix(); if (suffix.containsKey(c)) { currTN = suffix.get(c); // change priority if not endOfWord if (currTN.getMaxPriority() < weight) { currTN.setMaxPriority(weight); } depth++; } else { suffix.put(c, new TrieNode()); currTN = suffix.get(c); currTN.setMaxPriority(weight); depth++; } } currTN.changeEndOfWord(); currTN.prev = s; currTN.setPriority2(weight); words.add(s); } }
jamesnghiem/String-Autocompletion
Trie.java
249,656
/* * Class: CMSC203 * Instructor: Khandan Monshi * Description: Write a Class that contains instance variables to represent the x and y coordinates of the upper left corner of the location, * and depth and width to represent the vertical and horizontal extents of the plot. It also has methods to check if the plots overlap or are encompassed by one another, * as well as a toString method to display the plot's information. * Due: 11/07/23 * Platform/compiler: Eclipse IDE * I pledge that I have completed the programming assignment * independently. I have not copied the code from a student or * any source. I have not given my code to any student. * Print your Name here: _Kevin Villegas_ */ public class Plot { private int x,y,width,depth; public Plot() { this.x = 0; this.y = 0; this.width = 1; this.depth = 1; } public Plot(int x, int y, int width, int depth) { this.x = x; this.y = y; this.width = width; this.depth = depth; } public Plot(Plot otherPlot) { this.x = otherPlot.getX(); this.y = otherPlot.getY(); this.width = otherPlot.getWidth(); this.depth = otherPlot.getDepth(); } public boolean overlaps(Plot plot) { int a = plot.getX(); int b = plot.getY(); int c = plot.getWidth(); int d = plot.getDepth(); if (this.x == a && this.y == b && this.width == c && this.depth == d) { return true; } else if ((b + d) <= (this.y + this.depth) && (this.x + this.width) >= (a + c) && this.x <= a && this.y < b) { return true; } else if ((this.x + this.width) <= (a + c) && (this.y + depth) > b) { return true; } else if ((this.x + this.width) >= (a + c) && (this.y + depth) > b) { return true; } else { return false; } } public boolean encompasses(Plot plot) { int a = plot.getX(); int b = plot.getY(); int c = plot.getWidth(); int d = plot.getDepth(); if (a > this.x + this.width || b > this.y + this.depth || (a + c) > this.x + this.width || (b + d) > this.y + this.depth) { return false; } else { return true; } } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void setWidth(int width) { this.width = width; } public void setDepth(int depth) { this.depth = depth; } public int getX() { return this.x; } public int getY() { return this.y; } public int getWidth() { return this.width; } public int getDepth() { return this.depth; } public String toString() { return this.x + "," + this.y + "," + this.width + "," + this.depth; } }
KevinVillegas1/firstrepository
Plot.java
249,660
class box{ double height; double width; double depth; // Constructor with no parameters box(){ this(0,0,0); } // Constructor with three parameters box(double height, double width, double depth) { this.height = height; this.width = width; this.depth = depth; } // Method to calculate and return the volume of the box double volume() { return height * width * depth; } } class box_new extends box { double weight; // Constructor with four parameters public box_new(double height, double width, double depth, double weight) { super(height, width, depth); // Calling the base class constructor this.weight = weight; } } public class Main { public static void main(String[] args) { // Creating an object of the base class (Box) box mybox1 = new box(5, 3, 2); // Calculating and printing the volume of the box System.out.println("Volume of Box1 : " + mybox1.volume()); // Creating an object of the derived class (BoxNew) box_new mybox2 = new box_new(5, 3, 2, 10); // Calculating and printing the volume of the box from the derived class System.out.println("Volume of Box2 : " + mybox2.volume()); // Accessing the weight variable from the derived class System.out.println("Weight of Box2 : " + mybox2.weight); } }
sjoshihypen/Java-Playlist2.0
Main.java
249,661
/** * * @author William Nicholas * */ public class Plot { private int x; private int y; private int width; private int depth; //** The No-arg Constructor with the default integers */ public Plot() { x = 0; y = 0; width = 1; depth = 1; } //** The Copied Constructor to be used in the Plot object */ public Plot(Plot p) { this.x = p.x; this.y = p.y; this.width = p.width; this.depth = p.depth; } //** The Parameterized Constructor */ public Plot(int x, int y, int width, int depth) { this.x = x; this.y = y; this.width = width; this.depth = depth; } //** Determines if the plot overlaps, returns true if two plots overlap, false otherwise */ public boolean overlaps(Plot plot) { boolean oneOverlapA = (plot.x >= x && plot.x < (x + width)) && (plot.y >= y && plot.y < (y + depth)); boolean oneOverlapB = (plot.x <= x && x < (plot.x + plot.width)) && (plot.y <= y && y < (plot.y + plot.depth)); boolean twoOverlapsA = ((plot.x + plot.width) > x && (plot.x + plot.width) < (x + width)) && (plot.y >= y && plot.y < (y + depth)); boolean twoOverlapsB = ((x + width) > plot.x && (plot.x + plot.width) > (x + width)) && (plot.y <= y && y < (plot.y + plot.depth)); boolean threeOverlapsA = (plot.x >= x && plot.x < (x + width)) && ((plot.y + plot.depth) > y && (plot.y + plot.depth) <= (y + depth)); boolean threeOverlapsB = (plot.x <= x && x < (plot.x + plot.width)) && ((y + depth) > plot.y && (plot.y + plot.depth) >= (y + depth)); boolean fourOverlapsA = ((plot.x + plot.width) > x && (plot.x + plot.width) <= (x + width)) && ((plot.y + plot.depth) > y && (plot.y + plot.depth) <= (y + depth)); boolean fourOverlapsB = ((x + width) > plot.x && (plot.x + plot.width) >= (x + width)) && ((y + depth) > plot.y && (plot.y + plot.depth) >= (y + depth)); return oneOverlapA || oneOverlapB || twoOverlapsA || twoOverlapsB || threeOverlapsA || threeOverlapsB || fourOverlapsA || fourOverlapsB; } //** Takes the Plot instance and determines if the current plot contains it */ public boolean encompasses(Plot plot) { boolean X = plot.x >= x; boolean Y = plot.y >= y; boolean Width = (plot.x + plot.width) <= (x + width); boolean Depth = (plot.y + plot.depth) <= (y + depth); return X && Y && Width && Depth; } //** Returns the x value */ public int getX() { return x; } //** Sets the x value */ public void setX(int x) { this.x = x; } //** Returns the y value */ public int getY() { return y; } //** Sets the y value */ public void setY(int y) { this.y = y; } //** Returns the width value */ public int getWidth() { return width; } //** Sets the width value */ public void setWidth(int width) { this.width = width; } //** Returns the depth value */ public int getDepth() { return depth; } //** Sets the depth value */ public void setDepth(int depth) { this.depth = depth; } //** Prints the (x, y) of the upper left corner, and the width and depth of the picture */ public java.lang.String toString() { return ("Upper: (" + x + ", " + y + "); Width: " + width + " Depth: " + depth); } }
wbnicholas1999/Property_Management
Plot.java
249,672
public class Box { double height,width,depth; Box() { height=0; width=0; depth=0; } Box(double h,double w,double d) { height=h; width=w; depth=d; } Box(double a) { height=width=depth=a; } void volume() { double vol=height*width*depth; System.out.println("Volume is "+vol); } public static void main(String args[]) { Box b1=new Box(); b1.volume(); Box b2=new Box(2.5); b2.volume(); Box b3=new Box(1.5,2,6.0); b3.volume(); } }
joystonmenezes/java-lab-programms
Box.java
249,673
public class Box { private double width; private double height; private double depth; //constructor clone of an object Box(Box ob){ width = ob.width; height = ob.height; depth = ob.depth; } //constructor when all dimensions specified Box(double w, double h, double d){ width = w; height = h; depth = d; } //default constructor Box(){ width = -1; height = -1; depth = -1; } Box(double len){ width = height = depth = len; } //display volume of a box double volume(){ return width*depth*height; } }
Elliiee/java-fundamental
Box.java
249,674
public class Box { // Instance variables or properties of class double width; double height; double depth; public static void main(String[] args) { Box ob = new Box(); ob.depth = 15; ob.height = 25; ob.width = 35; Box ob1 = new Box(); ob1.width = 17; ob1.height = 23; ob1.depth = 21; System.out.println(ob.depth); System.out.println(ob1.depth); } }
krishankansal/JavaTutorialsInDepth
Box.java
249,686
package JAVA; public class Box { double width; double depth; double height; Box(Box ob) { width=ob.width; depth=ob.depth; height=ob.height; } Box(double w,double d,double h) { width=w; depth=d; height=h; } Box() { width=-1; depth=-1; height=-1; } Box(double len) { width=depth=height=len; } double volume() { return width*depth*height; } }
Gavinilalithasri/myjava
Box.java
249,687
// naval.Iowa package naval; import java.applet.Applet; import java.awt.*; import java.awt.image.*; import java.lang.*; import sea.Coord; import sea.Sea; import naval.Ship; /** * This battleship is modeled after the USS Wisconsin - an Iowa Class * Battleship (assuming each hex is equal to 60m in height). */ public class Iowa extends Ship implements ImageObserver { /** * The images of the ship. Uses a Coord-style direction as * index. */ Image image[]; int img_width, img_height; /** * The sea this ship exists on. This variable is necessary * to make the ship able to draw itself when the image is * actually loaded. */ Sea sea; public Iowa(Coord pos, int direction, Applet app, Sea sea) { super("Iowa class Battleship", pos, direction); this.sea = sea; floating.addElement(pos); floating.addElement(pos.displaced(direction, 1)); floating.addElement(pos.displaced(direction, 2)); floating.addElement(pos.displaced(Coord.otherWay(direction), 1)); floating.addElement(pos.displaced(Coord.otherWay(direction), 2)); image = new Image[6]; image[Coord.NORTH] = app.getImage(app.getDocumentBase(), "ships/Iowa-n.gif"); image[Coord.SOUTH] = app.getImage(app.getDocumentBase(), "ships/Iowa-s.gif"); image[Coord.NORTHEAST] = app.getImage(app.getDocumentBase(), "ships/Iowa-ne.gif"); image[Coord.SOUTHEAST] = app.getImage(app.getDocumentBase(), "ships/Iowa-se.gif"); image[Coord.NORTHWEST] = app.getImage(app.getDocumentBase(), "ships/Iowa-nw.gif"); image[Coord.SOUTHWEST] = app.getImage(app.getDocumentBase(), "ships/Iowa-sw.gif"); getImgInfo(); } public void getImgInfo() { img_width = image[direction].getWidth(this); img_height = image[direction].getHeight(this); } public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { if((infoflags & ALLBITS) != 0) { System.out.println(" ...time to draw!"); draw(sea.getGraphics()); return false; } if((infoflags & WIDTH) != 0) { System.out.println(" ...the image width is known to be " + width); img_width = width; } if((infoflags & HEIGHT) != 0) { System.out.println(" ...the image height is known to be " + height); img_height = height; } return true; } public void draw(Graphics grp) { if((img_width != -1) && (img_height != -1)) grp.drawImage(image[direction], pos.x0()-img_width/2, pos.y0()-img_height/2, this); else getImgInfo(); grp.setColor(black); grp.drawOval(pos.x0()-10, pos.y0()-10, 20, 20); } }; // end of naval.Iowa
MichaelStromberg-KTH/NavalWarfare
naval/Iowa.java
249,688
package com.aca; import java.util.Scanner; public class HighSpeedInternet { public static void main(String[] args) { /* HSI = High Speed Internet Rules: 1. Today's options are HSI of 5M, 10M, 20M, or 50M 2. State options are IA, MO, and AR 3. IA that have current speed < 30M are offered free upgrade to 50M 4. AR are offered no upgrade 5. MO that have current speed < 10M are offered free upgrade to 20M IA if current speed < 30M, free upgrade to 50M MO if current speed < 10M, free upgrade to 20M if current speed < 25M and >= 10M, free upgrade to 50M AR = no upgrade */ Scanner scan = new Scanner(System.in); System.out.println("Input your state initials: "); String state = scan.next(); if (!(state.equalsIgnoreCase("IA") && !(state.equalsIgnoreCase("MO") && !(state.equals("AR"))))) { System.out.println("Not a valid state."); System.exit(0); } Scanner scanTwo = new Scanner(System.in); System.out.print("Enter your current internet speed (exclude 'M'): "); int speed = scanTwo.nextInt(); if (state.equalsIgnoreCase("IA")) { Iowa(speed); } else if (state.equalsIgnoreCase("MO")) { Missouri(speed); } else { Arkansas(speed); } } public static void Iowa(int speed){ if(speed < 30){ System.out.print("Free upgrade to 50M."); }else{ System.out.print("Sorry, no upgrade offer."); } } public static void Missouri(int speed){ if(speed < 10){ System.out.print("Free upgrade to 20M."); }else if(speed < 25){ System.out.print("Free upgrade to 50M."); }else{ System.out.print("Sorry, no upgrade offer."); } } public static void Arkansas(int speed){ System.out.print("Sorry, no upgrade offer."); } }
alexandramtrawick/Main-Repository
HighSpeedInternet.java
249,689
package common; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.NoSuchElementException; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.TimeZone; import java.util.TreeMap; import java.util.Vector; import java.util.Collections; import java.util.Map; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import predict.FoxTLE; import predict.PositionCalcException; import predict.SortedTleList; import telemetry.BitArrayLayout; import telemetry.FramePart; import telemetry.LayoutLoadException; import telemetry.SortedFramePartArrayList; import telemetry.Format.TelemFormat; import telemetry.conversion.Conversion; import telemetry.conversion.ConversionCurve; import telemetry.conversion.ConversionFormat; import telemetry.conversion.ConversionInvalidCheck; import telemetry.conversion.ConversionLegacy; import telemetry.conversion.ConversionLookUpTable; import telemetry.conversion.ConversionMathExpression; import telemetry.conversion.ConversionStringLookUpTable; import telemetry.conversion.ConversionTimestamp; import telemetry.frames.FrameLayout; import telemetry.payloads.PayloadMaxValues; import telemetry.payloads.PayloadMinValues; import telemetry.payloads.PayloadRtValues; import telemetry.uw.CanFrames; import uk.me.g4dpz.satellite.SatPos; import uk.me.g4dpz.satellite.Satellite; import uk.me.g4dpz.satellite.SatelliteFactory; import uk.me.g4dpz.satellite.TLE; public class Spacecraft implements Comparable<Spacecraft> { public Properties properties; // Java properties file for user defined values public File propertiesFile; SatelliteManager satManager; public static String SPACECRAFT_DIR = "spacecraft"; public static final int ERROR_IDX = -1; // THESE HARD CODED LOOKUPS SHOULD NOT BE USED FOR NEW SPACECRAFT // Code a paramater into the spacecraft file that might work with future hardware, e.g. hasCanBus // Or switch logic based on standard layouts defined below, or custom layouts if required e.g. camera formats @Deprecated public static final int FOX1A = 1; @Deprecated public static final int FOX1B = 2; @Deprecated public static final int FOX1C = 3; @Deprecated public static final int FOX1D = 4; public static final int FIRST_FOXID_WITH_MODE_IN_HEADER = 6; public static final int MAX_FOXID = 256; // experimentally increase this to allow other ids. Note the header is limited to 8 bits // Layout Types @Deprecated public static final String DEBUG_LAYOUT = "DEBUG"; @Deprecated public static final String REAL_TIME_LAYOUT = "rttelemetry"; @Deprecated public static final String MAX_LAYOUT = "maxtelemetry"; @Deprecated public static final String MIN_LAYOUT = "mintelemetry"; @Deprecated public static final String RAD_LAYOUT = "radtelemetry"; @Deprecated public static final String RAD2_LAYOUT = "radtelemetry2"; @Deprecated public static final String HERCI_HS_LAYOUT = "herciHSdata"; @Deprecated public static final String HERCI_HS_HEADER_LAYOUT = "herciHSheader"; @Deprecated public static final String HERCI_HS_PKT_LAYOUT = "herciHSpackets"; @Deprecated public static final String WOD_LAYOUT = "wodtelemetry"; @Deprecated public static final String WOD_RAD_LAYOUT = "wodradtelemetry"; @Deprecated public static final String WOD_RAD2_LAYOUT = "wodradtelemetry2"; @Deprecated public static final String RAD_LEPF_LAYOUT = "radtelemLEPF"; @Deprecated public static final String RAD_LEP_LAYOUT = "radtelemLEP"; @Deprecated public static final String RAD_REM_LAYOUT = "radtelemREM"; // These are the layouts @Deprecated public static final String CAN_LAYOUT = "cantelemetry"; @Deprecated public static final String WOD_CAN_LAYOUT = "wodcantelemetry"; // These are the individual CAN packets inside the layouts @Deprecated public static final String CAN_PKT_LAYOUT = "canpacket"; @Deprecated public static final String WOD_CAN_PKT_LAYOUT = "wodcanpacket"; @Deprecated public static final String RSSI_LOOKUP = "RSSI"; @Deprecated public static final String IHU_VBATT_LOOKUP = "IHU_VBATT"; @Deprecated public static final String IHU_TEMP_LOOKUP = "IHU_TEMP"; @Deprecated public static final String HUSKY_SAT_ISIS_ANT_TEMP = "HUSKY_ISIS_ANT_TEMP"; // Model Versions public static final int EM = 0; public static final int FM = 1; public static final int FS = 2; // Flattened ENUM for spacecraft name public static String[] modelNames = { "Engineering Model", "Flight Model", "Flight Spare" }; public static String[] models = { "EM", "FM", "FS" }; public int foxId = 0; public int catalogNumber = 0; public String series = "FOX"; public String description = ""; public int model; public String canFileDir = "HuskySat"; public String user_format = "DUV_FSK"; public boolean telemetryMSBfirst = true; public boolean ihuLittleEndian = true; public int numberOfLayouts = 0; public int numberOfDbLayouts = 0; // if we load additional layouts for CAN BUS then this stores the core layouts public String[] layoutFilename; public BitArrayLayout[] layout; private boolean[] sendLayoutLocally; // CURRENTLY UNUSED SO MADE PRIVATE public CanFrames canFrames; public int numberOfLookupTables = 0; public String[] lookupTableFilename; public ConversionLookUpTable[] lookupTable; public int numberOfStringLookupTables = 0; public String[] stringLookupTableFilename; public ConversionStringLookUpTable[] stringLookupTable; public int numberOfSources = 1; public String[] sourceName = {"amsat.fox-1a.ihu.duv"}; // default to 1 source DUV; public String[] sourceFormatName; public TelemFormat[] sourceFormat; public String measurementsFileName = "measurements.csv"; // theoretically it is possible to change this in the MASTER file, but it is the same for all spacecraft public String passMeasurementsFileName = "passmeasurements.csv"; public BitArrayLayout measurementLayout; public BitArrayLayout passMeasurementLayout; public static final String MEASUREMENTS = "measurements"; public static final String PASS_MEASUREMENTS = "passmeasurements"; public int numberOfFrameLayouts = 0; public String[] frameLayoutFilename; public FrameLayout[] frameLayout; // User Config public static final String USER_ = "user_"; public Properties user_properties; // Java properties file for user defined values public File userPropertiesFile; public String user_display_name = "Amsat-1"; public String user_keps_name = "Amsat-1"; public int user_priority = 9; // set to low priority so new spacecraft are not suddenly ahead of old ones public boolean user_track = true; // default is we track a satellite public double user_telemetryDownlinkFreqkHz = 145980; public double user_minFreqBoundkHz = 145970; public double user_maxFreqBoundkHz = 145990; public String user_localServer = ""; // default to blank, otherwise we try to send to the local server public int user_localServerPort = 8587; public SatPos satPos; // cache the position when it gets calculated so others can read it public double satPosErrorCode; // Store the error code when we return null for the position public boolean hasCanBus; public boolean hasFrameCrc = false; private SortedTleList tleList; // this is a list of TLEs loaded from the history file. We search this for historical TLEs public boolean useConversionCoeffs = false; private HashMap<String, Conversion> conversions; public String conversionCurvesFileName; public String conversionExpressionsFileName; public boolean hasFOXDB_V3 = false; public static final int EXP_EMPTY = 0; public static final int EXP_VANDERBILT_LEP = 1; // This is the 1A LEP experiment public static final int EXP_VT_CAMERA = 2; public static final int EXP_IOWA_HERCI = 3; public static final int EXP_RAD_FX_SAT = 4; public static final int EXP_VT_CAMERA_LOW_RES = 5; public static final int EXP_VANDERBILT_VUC = 6; // This is the controller and does not have its own telem file public static final int EXP_VANDERBILT_REM = 7; // This is the controller and does not have its own telem file public static final int EXP_VANDERBILT_LEPF = 8; // This is the controller and does not have its own telem file public static final int EXP_UW = 9; // University of Washington public static final int RAG_ADAC = 10; // Ragnaroc public static final int LBAND_DOWNSHIFTER = 11; // Downshifter public static final int EXP_UMAINE_CAMERA = 12; // University of Maine MESAT-1 Camera public static final String SAFE_MODE_IND = "SafeModeIndication"; public static final String SCIENCE_MODE_IND = "ScienceModeActive"; @Deprecated public static final String MEMS_REST_VALUE_X = "SatelliteXAxisAngularVelocity"; @Deprecated public static final String MEMS_REST_VALUE_Y = "SatelliteYAxisAngularVelocity"; @Deprecated public static final String MEMS_REST_VALUE_Z = "SatelliteZAxisAngularVelocity"; public static final int NO_MODE = 0; public static final int SAFE_MODE = 1; public static final int TRANSPONDER_MODE = 2; public static final int DATA_MODE = 3; public static final int SCIENCE_MODE = 4; public static final int HEALTH_MODE = 5; public static final int CAMERA_MODE = 6; public static final String[] modeNames = { "UNKNOWN", "SAFE", "TRANSPONDER", "DATA", "SCIENCE", "HEALTH", "CAMERA" }; public static final String[] expNames = { "Empty", "Vanderbilt LEP", "Virginia Tech Camera", "University of Iowa HERCI", "Rad FX Sat", "Virginia Tech Low-res Camera", "Vanderbilt VUC", "Vanderbilt REM", "Vanderbilt LEPF", "CAN Packet Interface", "Ragnaroc ADAC", "L-Band Downshifter", "University of Maine multi-spectral camera" }; public int IHU_SN = 0; public int[] experiments = {EXP_EMPTY, EXP_EMPTY, EXP_EMPTY, EXP_EMPTY}; public boolean hasImprovedCommandReceiver = false; public boolean hasImprovedCommandReceiverII = false; public boolean hasModeInHeader = false; @Deprecated public boolean hasMpptSettings = false; @Deprecated public boolean hasMemsRestValues = false; public boolean hasFixedReset = false; public boolean hasGPSTime = false; public boolean user_useGPSTimeForT0 = true; // User settings - Calibration @Deprecated public double user_BATTERY_CURRENT_ZERO = 0; @Deprecated public double user_mpptResistanceError = 6.58d; @Deprecated public int user_mpptSensorOffThreshold = 1600; @Deprecated public int user_memsRestValueX = 0; @Deprecated public int user_memsRestValueY = 0; @Deprecated public int user_memsRestValueZ = 0; // layout flags @Deprecated public boolean useIHUVBatt = false; ArrayList<Long> timeZero = null; SpacecraftPositionCache positionCache; public static final DateFormat timeDateFormat = new SimpleDateFormat("HH:mm:ss"); public static final DateFormat dateDateFormat = new SimpleDateFormat("dd MMM yy"); /* final String[] testTLE = { "AO-85", "1 40967U 15058D 16111.35540844 .00000590 00000-0 79740-4 0 01029", "2 40967 064.7791 061.1881 0209866 223.3946 135.0462 14.74939952014747"}; */ /** * Initialize the spacecraft settings. Load Spacecraft from disk. Load from the master file and the user file * * @param masterFileName * @param userFileName * @throws LayoutLoadException * @throws FileNotFoundException * @throws IOException */ public Spacecraft(SatelliteManager satManager, File masterFileName, File userFileName ) throws LayoutLoadException, FileNotFoundException { this.satManager = satManager; properties = new Properties(); propertiesFile = masterFileName; userPropertiesFile = userFileName; tleList = new SortedTleList(10); try { load(); // don't call load until this constructor has started and the variables have been initialized } catch (ArrayIndexOutOfBoundsException e1) { Log.errorDialog("ERROR", "Can't fully load spacecraft file: "+masterFileName+"\nPerhaps one of the files is corrupt? "+"\n"+ e1.getMessage()); e1.printStackTrace(); return; } try { loadTimeZeroSeries(null); } catch (FileNotFoundException e) { timeZero = null; } catch (IndexOutOfBoundsException e) { timeZero = null; } try { measurementLayout = new BitArrayLayout(System.getProperty("user.dir") + File.separator + Spacecraft.SPACECRAFT_DIR +File.separator + measurementsFileName); measurementLayout.name=MEASUREMENTS; if (passMeasurementsFileName != null) { passMeasurementLayout = new BitArrayLayout(System.getProperty("user.dir") + File.separator + Spacecraft.SPACECRAFT_DIR +File.separator + passMeasurementsFileName); passMeasurementLayout.name = PASS_MEASUREMENTS; } } catch (IOException e) { throw new LayoutLoadException("Could not load measurement layout. Make sure it is installed\n" + "in folder:" + Config.currentDir+File.separator+"spacecraft\n" + e.getMessage()); } loadTleHistory(); // Dont call this until the Name and FoxId are set positionCache = new SpacecraftPositionCache(foxId); } /** * Create a new blank spacecraft MASTER file * @param satManager * @param masterFileName */ public Spacecraft(SatelliteManager satManager, File masterFileName, File userFileName, int foxId) { this.satManager = satManager; properties = new Properties(); propertiesFile = masterFileName; userPropertiesFile = userFileName; tleList = new SortedTleList(10); this.foxId = foxId; hasFOXDB_V3 = true; // should be true for all new spacecraft store_master_params(); } /** * This is a routine that determines if we can cast to FoxSpeacecrft, but currently everything can, so we return true * If this is used in the future then we need to be careful about the functionality that is turned on/off by it * It is not removed because the points in the code that call this may well be important switch points in the future and * it is easier to return true here than remove the calls and later try to work out where they were. * @return */ @Deprecated public boolean isFox1() { return true; // if (foxId < 10) return true; // return false; } public int getLayoutIdxByName(String name) { for (int i=0; i<numberOfLayouts; i++) if (layout[i].name.equalsIgnoreCase(name)) return i; return ERROR_IDX; } public int getLookupIdxByName(String name) { for (int i=0; i<numberOfLookupTables; i++) if (lookupTable[i].getName().equalsIgnoreCase(name)) return i; return ERROR_IDX; } public BitArrayLayout getLayoutByName(String name) { int i = getLayoutIdxByName(name); if (i != ERROR_IDX) return layout[i]; return null; } public String getLayoutNameByType(String type) { for (int i=0; i<numberOfLayouts; i++) if (layout[i].typeStr.equalsIgnoreCase(type)) return layout[i].name; return null; } public BitArrayLayout getLayoutByType(String type) { for (int i=0; i<numberOfLayouts; i++) if (layout[i].typeStr.equalsIgnoreCase(type)) return layout[i]; return null; } /** * Find the secondary layout for this layout * The secondary layout points to its parent * @param name * @return */ public BitArrayLayout getSecondaryLayoutFromPrimaryName(String name) { for (int i=0; i<numberOfLayouts; i++) if (layout[i].parentLayout != null) if (layout[i].parentLayout.equalsIgnoreCase(name)) return layout[i]; return null; } public BitArrayLayout getLayoutByCanId(int canId) { if (!hasCanBus) return null; if (canFrames == null) return null; String name = canFrames.getNameByCanId(canId); if (name != null) { int i = getLayoutIdxByName(name); if (i != ERROR_IDX) return layout[i]; } return getLayoutByName(Spacecraft.CAN_PKT_LAYOUT); // try to return the default instead. We dont have this CAN ID } public String[] getPayloadList() { String[] payloadList = new String[this.numberOfLayouts]; for (int i=0; i<numberOfLayouts; i++) { payloadList[i] = this.layout[i].name; } return payloadList; } public String[] getConversionsArray() { if (conversions == null) { return new String[0]; } String[] conv = new String[conversions.size()]; int i = 0; for (String key : conversions.keySet()) { conv[i++] = key; } return conv; } /** * Return the conversion for this spacecraft based on its name. Tables, Curves and Math expressions were stored in * conversions when the MASTER file was loaded. * * We also need to cope with the keywords for formatting and the functions. * * @param name * @return */ public Conversion getConversionByName(String name) { name = name.trim(); // The first and fastest check is if this is a curve, table or math expression in the conversions list if (this.useConversionCoeffs) { if (conversions == null) return null; Conversion conv = conversions.get(name); if (conv != null) return conv; } // Next check for legacy conversion. This is a single integer in the right range try { int convInt = Integer.parseInt(name); if (convInt >= 0 && convInt <= BitArrayLayout.MAX_CONVERSION_NUMBER) return new ConversionLegacy(name, this); } catch (NumberFormatException e) { ; } //ignore // Otherwise check formatting keywords try { if (name.equalsIgnoreCase(Conversion.FMT_INT)) return new ConversionFormat(name, this); if (name.equalsIgnoreCase(Conversion.FMT_1F)) return new ConversionFormat(name, this); if (name.equalsIgnoreCase(Conversion.FMT_2F)) return new ConversionFormat(name, this); if (name.equalsIgnoreCase(Conversion.FMT_3F)) return new ConversionFormat(name, this); if (name.equalsIgnoreCase(Conversion.FMT_4F)) return new ConversionFormat(name, this); if (name.equalsIgnoreCase(Conversion.FMT_5F)) return new ConversionFormat(name, this); if (name.equalsIgnoreCase(Conversion.FMT_6F)) return new ConversionFormat(name, this); if (name.substring(0, Conversion.FMT_HEX.length()).equalsIgnoreCase(Conversion.FMT_HEX)) return new ConversionFormat(name, this); if (name.substring(0, Conversion.FMT_BIN.length()).equalsIgnoreCase(Conversion.FMT_BIN)) return new ConversionFormat(name, this); if (name.substring(0, Conversion.FMT_F.length()).equalsIgnoreCase(Conversion.FMT_F) ) return new ConversionFormat(name, this); if (name.substring(0, Conversion.TIMESTAMP.length()).equalsIgnoreCase(Conversion.TIMESTAMP)) return new ConversionTimestamp(name, this); } catch (StringIndexOutOfBoundsException e) { return null; } try { if (name.substring(0, ConversionInvalidCheck.KEYWORD.length()).equalsIgnoreCase(ConversionInvalidCheck.KEYWORD)) return new ConversionInvalidCheck(name, this); } catch (RuntimeException e) { return null; } return null; } public ConversionLookUpTable getLookupTableByName(String name) { int i = getLookupIdxByName(name); if (i != ERROR_IDX) return lookupTable[i]; return null; } public String getLayoutFileNameByName(String name) { int i = getLayoutIdxByName(name); if (i != ERROR_IDX) return layoutFilename[i]; return null; } public String getLookupTableFileNameByName(String name) { int i = getLookupIdxByName(name); if (i != ERROR_IDX) return lookupTableFilename[i]; return null; } /** * TLEs are stored in the spacecraft directory in the logFileDirectory. * @throws IOException */ protected void loadTleHistory() { String file = Spacecraft.SPACECRAFT_DIR + File.separator + series + this.foxId + ".tle"; if (!Config.logFileDirectory.equalsIgnoreCase("")) { file = Config.logFileDirectory + File.separator + file; } File f = new File(file); InputStream is = null; try { Log.println("Loading TLE file: " + file); is = new FileInputStream(f); tleList = FoxTLE.importFoxSat(is); } catch (IOException e) { Log.println("... TLE file not loaded: " + file); //e.printStackTrace(Log.getWriter()); // No TLE, but this is not viewed as fatal. It should be fixed by Kep check } finally { try { if (is != null) is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void saveTleHistory() throws IOException { String file = Spacecraft.SPACECRAFT_DIR + File.separator + series + this.foxId + ".tle"; if (!Config.logFileDirectory.equalsIgnoreCase("")) { file = Config.logFileDirectory + File.separator + file; } File f = new File(file); Writer output = new BufferedWriter(new FileWriter(f, false)); for (FoxTLE tle : tleList) { //Log.println("Saving TLE to file: " + tle.toString() + ": " + tle.getEpoch()); output.write(tle.toFileString()); } output.flush(); output.close(); } /** * We are passed a new TLE for this spacecarft. We want to store it in the file if it is a TLE that we do not already have. * @param tle * @return * @throws IOException */ public boolean addTLE(FoxTLE tle) throws IOException { tleList.add(tle); saveTleHistory(); return true; } protected TLE getTLEbyDate(DateTime dateTime) throws PositionCalcException { if (tleList == null) return null; TLE t = tleList.getTleByDate(dateTime); if (t==null) { satPosErrorCode = FramePart.NO_TLE; throw new PositionCalcException(FramePart.NO_TLE); } return t; } /** * Calculate the position at a historical data/time * Typically we don't call this directly. Instead we call with the reset/uptime and hope that the value is already cached * @param timeNow * @return * @throws PositionCalcException */ public SatPos calcSatellitePosition(DateTime timeNow) throws PositionCalcException { final TLE tle = getTLEbyDate(timeNow); // if (Config.debugFrames) Log.println("TLE Selected fOR date: " + timeNow + " used TLE epoch " + tle.getEpoch()); if (tle == null) { satPosErrorCode = FramePart.NO_TLE; throw new PositionCalcException(FramePart.NO_TLE); // We have no keps } final Satellite satellite = SatelliteFactory.createSatellite(tle); final SatPos satellitePosition = satellite.getPosition(Config.GROUND_STATION, timeNow.toDate()); return satellitePosition; } /** * Calculate the current position and cache it * @return * @throws PositionCalcException */ protected SatPos calcualteCurrentPosition() throws PositionCalcException { DateTime timeNow = new DateTime(DateTimeZone.UTC); SatPos pos = null; pos = calcSatellitePosition(timeNow); satPos = pos; if (Config.debugSignalFinder) Log.println("Fox at: " + FramePart.latRadToDeg(pos.getAzimuth()) + " : " + FramePart.lonRadToDeg(pos.getElevation())); return pos; } public SatPos getCurrentPosition() throws PositionCalcException { if (satPos == null) { throw new PositionCalcException(FramePart.NO_POSITION_DATA); } return satPos; } public boolean aboveHorizon() { // if (Config.useDDEforAzEl) { // String satString = null; // SatPc32DDE satPC = new SatPc32DDE(); // boolean connected = satPC.connect(); // if (connected) { // satString = satPC.satellite; // //Log.println("SATPC32: " + satString); // if (satString != null && satString.equalsIgnoreCase(user_keps_name)) { // return true; // } // } // return false; // } if (satPos == null) return false; return (FramePart.radToDeg(satPos.getElevation()) >= 0); } public boolean setT0FromGPSTime(int resetToAdd, long uptime, ZonedDateTime timestamp) { int reset = 0; if (hasTimeZero()) { reset = timeZero.size(); // this will point to the next reset to add } else { timeZero = new ArrayList<Long>(100); } long T0Seconds = (timestamp.toEpochSecond() - uptime)*1000; // Now add the reset (and give any missing resets the same timestamp) for (int i=reset; i <= resetToAdd; i++) timeZero.add(i, T0Seconds); try { saveTimeZeroSeries(); } catch (IOException e) { e.printStackTrace(Log.getWriter()); return false; } if (Config.debugFrames) Log.println("SAVING RESET: " + resetToAdd + " as " + timestamp); return true; } public int getCurrentReset(int resetOnFrame, long uptime) { if (!hasFixedReset) return resetOnFrame; if (hasTimeZero()) { int reset = timeZero.size()-1; // we have one entry per reset long T0Seconds = timeZero.get(reset)/1000;; Date now = new Date(); long nowSeconds = now.getTime()/1000; long newT0estimate = (nowSeconds - uptime)*1000; if (resetOnFrame == reset + 1) { // somehow we had a normal reset // Add a new reset for this timeZero.add(newT0estimate); try { saveTimeZeroSeries(); } catch (IOException e) { e.printStackTrace(Log.getWriter()); } if (Config.debugFrames) Log.println("SAVING RESET: " + resetOnFrame); return resetOnFrame; } long diff = Math.abs(nowSeconds - (T0Seconds + uptime)); if (uptime < Config.newResetCheckUptimeMax) if (diff > Config.newResetCheckThreshold) { Log.println("*** HUSKY RESET DETECTED ...." + diff); timeZero.add(newT0estimate); try { saveTimeZeroSeries(); } catch (IOException e) { e.printStackTrace(Log.getWriter()); } if (Config.debugFrames) Log.println("SAVING RESET: " + (reset+1)); return reset + 1; } if (Config.debugFrames) Log.println("SAVING RESET: " + reset); return reset; } else { if (Config.debugFrames) Log.println("SAVING RESET: " + resetOnFrame); return resetOnFrame; } } public boolean hasTimeZero() { if (timeZero == null) return false; if (timeZero.size() == 0) return false; return true; } public boolean hasTimeZero(int reset) { if (timeZero == null) return false; if (reset >= timeZero.size()) return false; return true; } public String[][] getT0TableData() { if (timeZero == null) return null; if (timeZero.size() == 0) return null; String[][] data = new String[timeZero.size()][]; for (int i=0; i< timeZero.size(); i++) { data[i] = new String[2]; data[i][0] = ""+i; data[i][1] = getUtcDateForReset(i,0) + " " + getUtcTimeForReset(i,0); } return data; } public String getUtcTimeForReset(int reset, long uptime) { if (timeZero == null) return null; if (reset >= timeZero.size()) return null; Date dt = new Date(timeZero.get(reset) + uptime*1000); timeDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); String time = timeDateFormat.format(dt); return time; } public String getUtcDateForReset(int reset, long uptime) { if (timeZero == null) return null; if (reset >= timeZero.size()) return null; Date dt = new Date(timeZero.get(reset) + uptime *1000); dateDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); String time = dateDateFormat.format(dt); return time; } public Date getUtcForReset(int reset, long uptime) { if (timeZero == null) return null; if (reset >= timeZero.size()) return null; Date dt = new Date(timeZero.get(reset) + uptime*1000); return dt; } public DateTime getUtcDateTimeForReset(int reset, long uptime) { if (timeZero == null) return null; if (reset < 0 || reset >= timeZero.size()) return null; if (uptime < 0) return null; Date dt = new Date(timeZero.get(reset) + uptime*1000); DateTime dateTime = new DateTime(dt); // FIXME - this date conversion is not working. Need to understand how it works. return dateTime; } /** * Given a date, what is the reset and uptime * @param fromDate * @return a FoxTime object with the reset and uptime */ public FoxTime getUptimeForUtcDate(Date fromDate) { if (timeZero == null) return null; if (fromDate == null) return null; if (timeZero.size() == 0) return null; long dateTime = fromDate.getTime(); long T0 = -1; int reset = 0; long uptime = 0; // Search T0. It's short so we can scan the whole list for (int i=0; i<timeZero.size(); i++) { if (timeZero.get(i) > dateTime) { // then we want the previous value if (i==0) break; reset = i-1; T0 = timeZero.get(reset); break; } } if (T0 == -1) { // return the last reset, we scanned the whole list reset = timeZero.size()-1; T0 = timeZero.get(reset); } // Otherwise we have a valid reset, so calc the uptime, which is seconds from the T0 to the passed dateTime uptime = dateTime - T0; // milliseconds uptime = uptime / 1000; // seconds; FoxTime ft = new FoxTime(reset, uptime); return ft; } public SatPos getSatellitePosition(int reset, long uptime) throws PositionCalcException { // We need to construct a date for the historical time of this WOD record DateTime timeNow = getUtcDateTimeForReset(reset, uptime); if (timeNow == null) throw new PositionCalcException(FramePart.NO_T0); SatPos satellitePosition = positionCache.getPosition(timeNow.getMillis()); if (satellitePosition != null) { return satellitePosition; } final TLE tle = getTLEbyDate(timeNow); // if (Config.debugFrames) Log.println("TLE Selected fOR date: " + timeNow + " used TLE epoch " + tle.getEpoch()); if (tle == null) throw new PositionCalcException(FramePart.NO_TLE); // We have no keps final Satellite satellite = SatelliteFactory.createSatellite(tle); satellitePosition = satellite.getPosition(Config.GROUND_STATION, timeNow.toDate()); // Log.println("Cache value"); positionCache.storePosition(timeNow.getMillis(), satellitePosition); return satellitePosition; } public boolean sendToLocalServer() { if (user_localServer == null) return false; if (user_localServer.equalsIgnoreCase("")) return false; else return true; } /** * Returns true if this layout should be sent to the local server * @param name * @return */ public boolean shouldSendLayout(String name) { for (int i=0; i<numberOfLayouts; i++) if (layout[i].name.equals(name)) if (sendLayoutLocally[i]) return true; return false; } public boolean isValidConversion(String conv) { Conversion c = getConversionByName(conv); if (c == null) return false; return true; } public void loadConversions() throws LayoutLoadException, FileNotFoundException, IOException { // Conversions if (useConversionCoeffs) { conversions = new HashMap<String, Conversion>(); if (conversionCurvesFileName != null) { loadConversionCurves( Config.currentDir + File.separator + Spacecraft.SPACECRAFT_DIR + File.separator + conversionCurvesFileName); } if (conversionExpressionsFileName != null) { loadConversionExpresions( Config.currentDir + File.separator + Spacecraft.SPACECRAFT_DIR + File.separator + conversionExpressionsFileName); } // String Lookup Tables String sNumberOfStringLookupTables = getOptionalProperty("numberOfStringLookupTables"); if (sNumberOfStringLookupTables != null) { numberOfStringLookupTables = Integer.parseInt(sNumberOfStringLookupTables); stringLookupTableFilename = new String[numberOfStringLookupTables]; stringLookupTable = new ConversionStringLookUpTable[numberOfStringLookupTables]; for (int i=0; i < numberOfStringLookupTables; i++) { stringLookupTableFilename[i] = getProperty("stringLookupTable"+i+".filename"); String tableName = getProperty("stringLookupTable"+i); stringLookupTable[i] = new ConversionStringLookUpTable(tableName, stringLookupTableFilename[i], this); if (conversions.containsKey(stringLookupTable[i].getName())) { // we have a namespace clash, warn the user Log.errorDialog("DUPLICATE STRING TABLE NAME", this.user_keps_name + ": Lookup table or Curve already defined and will not be stored: " + tableName); } else { conversions.put(tableName, stringLookupTable[i]); Log.println("Stored: " + stringLookupTable[i]); } } } } // Lookup Tables numberOfLookupTables = Integer.parseInt(getProperty("numberOfLookupTables")); lookupTableFilename = new String[numberOfLookupTables]; lookupTable = new ConversionLookUpTable[numberOfLookupTables]; for (int i=0; i < numberOfLookupTables; i++) { lookupTableFilename[i] = getProperty("lookupTable"+i+".filename"); String tableName = getProperty("lookupTable"+i); lookupTable[i] = new ConversionLookUpTable(tableName, lookupTableFilename[i], this); if (useConversionCoeffs) { if (conversions.containsKey(lookupTable[i].getName())) { // we have a namespace clash, warn the user Log.errorDialog("DUPLICATE TABLE NAME", this.user_keps_name + ": Lookup table already defined and will not be stored: " + tableName); } else { conversions.put(tableName, lookupTable[i]); Log.println("Stored: " + lookupTable[i]); } } } } /** * This loads all of the settings including those that are overridden by the user_ settings. It they do not * exist yet then they are initialized here * @throws LayoutLoadException */ protected void load() throws LayoutLoadException { // try to load the properties from a file FileInputStream f = null; try { f=new FileInputStream(propertiesFile); properties.load(f); f.close(); } catch (IOException e) { if (f!=null) try { f.close(); } catch (Exception e1) {}; throw new LayoutLoadException("Could not load spacecraft. File is missing: " + propertiesFile.getAbsolutePath()); } try { foxId = Integer.parseInt(getProperty("foxId")); catalogNumber = Integer.parseInt(getProperty("catalogNumber")); user_keps_name = getProperty("name"); description = getProperty("description"); model = Integer.parseInt(getProperty("model")); user_telemetryDownlinkFreqkHz = Double.parseDouble(getProperty("telemetryDownlinkFreqkHz")); user_minFreqBoundkHz = Double.parseDouble(getProperty("minFreqBoundkHz")); user_maxFreqBoundkHz = Double.parseDouble(getProperty("maxFreqBoundkHz")); useConversionCoeffs = getOptionalBooleanProperty("useConversionCoeffs"); // Frame Layouts String frames = getOptionalProperty("numberOfFrameLayouts"); if (frames == null) numberOfFrameLayouts = 0; else { numberOfFrameLayouts = Integer.parseInt(frames); frameLayoutFilename = new String[numberOfFrameLayouts]; frameLayout = new FrameLayout[numberOfFrameLayouts]; for (int i=0; i < numberOfFrameLayouts; i++) { frameLayoutFilename[i] = getProperty("frameLayout"+i+".filename"); frameLayout[i] = new FrameLayout(foxId, frameLayoutFilename[i]); frameLayout[i].name = getProperty("frameLayout"+i+".name"); } } if (useConversionCoeffs) { conversionCurvesFileName = getOptionalProperty("conversionCurvesFileName"); conversionExpressionsFileName = getOptionalProperty("conversionExpressionsFileName"); } loadConversions(); String V3DB = getOptionalProperty("hasFOXDB_V3"); if (V3DB == null) hasFOXDB_V3 = false; else hasFOXDB_V3 = Boolean.parseBoolean(V3DB); // Telemetry Layouts numberOfLayouts = Integer.parseInt(getProperty("numberOfLayouts")); numberOfDbLayouts = numberOfLayouts; layoutFilename = new String[numberOfLayouts]; layout = new BitArrayLayout[numberOfLayouts]; sendLayoutLocally = new boolean[numberOfLayouts]; for (int i=0; i < numberOfLayouts; i++) { layoutFilename[i] = getProperty("layout"+i+".filename"); layout[i] = new BitArrayLayout(Config.currentDir + File.separator + Spacecraft.SPACECRAFT_DIR +File.separator + layoutFilename[i]); // Check that the conversions look valid -- any this should be re-factored into the Conversion class when I have time //TODO if (useConversionCoeffs) for (int c=0; c<layout[i].NUMBER_OF_FIELDS; c++) { String convName = layout[i].getConversionNameByPos(c); // Not a legacy int conversion String[] conversions = convName.split("\\|"); // split the conversion based on | in case its a pipeline for (String singleConv : conversions) { singleConv = singleConv.trim(); try { int convInt = Integer.parseInt(singleConv); if (convInt > BitArrayLayout.MAX_CONVERSION_NUMBER) { throw new LayoutLoadException("Conversion number "+ convInt +" is not defined. "+ "Error in row for field: " + layout[i].fieldName[c] + " on row: " + c + "\nwhen processing layout: " + layoutFilename[i] ); } } catch (NumberFormatException e) { Conversion conv = this.getConversionByName(singleConv); if (conv == null) { String stem3 = ""; if (singleConv.length() >=3) stem3 = singleConv.substring(0, 3); // first 3 characters to check for BIN, HEX String stem5 = ""; if (singleConv.length() >=5) stem5 = singleConv.substring(0, 5); // first 5 characters to check for FLOAT String stem9 = ""; if (singleConv.length() >=9) stem9 = singleConv.substring(0, 9); // first 9 characters to check for TIMESTAMP if (stem3.equalsIgnoreCase(Conversion.FMT_INT) || stem3.equalsIgnoreCase(Conversion.FMT_BIN) || stem3.equalsIgnoreCase(Conversion.FMT_HEX) || stem5.equalsIgnoreCase(Conversion.FMT_F) || stem9.equalsIgnoreCase(Conversion.TIMESTAMP)) { // we skip, this is applied in string formatting later } else throw new LayoutLoadException("Conversion '"+ convName +"' is not defined. "+ "Error in row for field: " + layout[i].fieldName[c] + " on row: " + c + "\nwhen processing layout: " + layoutFilename[i] ); } } } } layout[i].name = getProperty("layout"+i+".name"); layout[i].parentLayout = getOptionalProperty("layout"+i+".parentLayout"); layout[i].hasGPSTime = Boolean.parseBoolean(getOptionalProperty("layout"+i+".hasGPSTime")); if (hasFOXDB_V3) { layout[i].number = i; layout[i].typeStr = getProperty("layout"+i+".type"); if (!BitArrayLayout.isValidType(layout[i].typeStr)) { throw new LayoutLoadException("Invalid payload type found: "+ layout[i].typeStr + "\nfor payload: " + layout[i].name + "\nwhen processing Spacecraft file: " + propertiesFile.getAbsolutePath() ); } layout[i].title = getOptionalProperty("layout"+i+".title"); layout[i].shortTitle = getOptionalProperty("layout"+i+".shortTitle"); } } // sources numberOfSources = Integer.parseInt(getProperty("numberOfSources")); sourceName = new String[numberOfSources]; for (int i=0; i < numberOfSources; i++) { sourceName[i] = getProperty("source"+i+".name"); } // Source details String format = getOptionalProperty("source0.formatName"); if (format == null) { } else { sourceFormat = new TelemFormat[numberOfSources]; sourceFormatName = new String[numberOfSources]; for (int i=0; i < numberOfSources; i++) { sourceFormatName[i] = getProperty("source"+i+".formatName"); sourceFormat[i] = satManager.getFormatByName(sourceFormatName[i]); } } String t = getOptionalProperty("track"); if (t == null) user_track = true; else user_track = Boolean.parseBoolean(t); String s = getOptionalProperty("series"); if (s == null) series = "FOX"; else series = s; String serv = getOptionalProperty("localServer"); if (serv == null) user_localServer = null; else user_localServer = serv; String p = getOptionalProperty("localServerPort"); if (p == null) user_localServerPort = 0; else user_localServerPort = Integer.parseInt(p); // for (int i=0; i < numberOfLayouts; i++) { // String l = getOptionalProperty("sendLayoutLocally"+i); // if (l != null) // sendLayoutLocally[i] = Boolean.parseBoolean(l); // else // sendLayoutLocally[i] = false; // } String pri = getOptionalProperty("priority"); if (pri == null) user_priority = 1; else user_priority = Integer.parseInt(pri); String c = getOptionalProperty("hasCanBus"); if (c == null) hasCanBus = false; else hasCanBus = Boolean.parseBoolean(c); if (hasCanBus) { this.canFileDir = getProperty("canFileDir"); loadCanLayouts(); } user_format = getProperty("user_format"); user_display_name = getProperty("displayName"); String crc = getOptionalProperty("hasFrameCrc"); if (crc == null) hasFrameCrc = false; else hasFrameCrc = Boolean.parseBoolean(crc); } catch (NumberFormatException nf) { nf.printStackTrace(Log.getWriter()); throw new LayoutLoadException("Corrupt data found: "+ nf.getMessage() + "\nwhen processing Spacecraft file: " + propertiesFile.getAbsolutePath() ); // } catch (NullPointerException nf) { // nf.printStackTrace(Log.getWriter()); // throw new LayoutLoadException("NULL data value: "+ nf.getMessage() + "\nwhen processing Spacecraft file: " + propertiesFile.getAbsolutePath() ); } catch (FileNotFoundException e) { e.printStackTrace(Log.getWriter()); throw new LayoutLoadException("File not found: "+ e.getMessage() + "\nwhen processing Spacecraft file: " + propertiesFile.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(Log.getWriter()); throw new LayoutLoadException("File load error: "+ e.getMessage() + "\nwhen processing Spacecraft file: " + propertiesFile.getAbsolutePath()); } try { IHU_SN = Integer.parseInt(getProperty("IHU_SN")); // If fox hasFOXDB_V3 then the experiments are optional because all informtion for // tab layout is stored in the layouts and the rest of the master file for (int i=0; i< experiments.length; i++) { try { int num = Integer.parseInt(getProperty("EXP"+(i+1))); experiments[i] = num; } catch (LayoutLoadException nf) { if (!hasFOXDB_V3) throw nf; } } try { user_BATTERY_CURRENT_ZERO = Double.parseDouble(getProperty("BATTERY_CURRENT_ZERO")); } catch (LayoutLoadException nf) { if (!hasFOXDB_V3) throw nf; } try { useIHUVBatt = Boolean.parseBoolean(getProperty("useIHUVBatt")); } catch (LayoutLoadException nf) { if (!hasFOXDB_V3) throw nf; } measurementsFileName = getProperty("measurementsFileName"); passMeasurementsFileName = getProperty("passMeasurementsFileName"); String error = getOptionalProperty("mpptResistanceError"); if (error != null) { user_mpptResistanceError = Double.parseDouble(error); hasMpptSettings = true; } String threshold = getOptionalProperty("mpptSensorOffThreshold"); if (threshold != null) { user_mpptSensorOffThreshold = Integer.parseInt(threshold); hasMpptSettings = true; } String icr = getOptionalProperty("hasImprovedCommandReceiver"); if (icr != null) { hasImprovedCommandReceiver = Boolean.parseBoolean(icr); } String icr2 = getOptionalProperty("hasImprovedCommandReceiverII"); if (icr2 != null) { hasImprovedCommandReceiverII = Boolean.parseBoolean(icr2); } String mode = getOptionalProperty("hasModeInHeader"); if (mode != null) { hasModeInHeader = Boolean.parseBoolean(getProperty("hasModeInHeader")); } String fixedReset = getOptionalProperty("hasFixedReset"); if (fixedReset != null) { hasFixedReset = Boolean.parseBoolean(getProperty("hasFixedReset")); } String gpsTime = getOptionalProperty("hasGPSTime"); if (gpsTime != null) { hasGPSTime = Boolean.parseBoolean(getProperty("hasGPSTime")); } String mems_x = getOptionalProperty("memsRestValueX"); if (mems_x != null) { user_memsRestValueX = Integer.parseInt(mems_x); } String mems_y = getOptionalProperty("memsRestValueY"); if (mems_y != null) { user_memsRestValueY = Integer.parseInt(mems_y); } String mems_z = getOptionalProperty("memsRestValueZ"); if (mems_z != null) { user_memsRestValueZ = Integer.parseInt(mems_z); } if (user_memsRestValueX != 0 && user_memsRestValueY != 0 & user_memsRestValueZ != 0) hasMemsRestValues = true; } catch (NumberFormatException nf) { nf.printStackTrace(Log.getWriter()); throw new LayoutLoadException("Corrupt FOX data found when loading Spacecraft file: " + propertiesFile.getAbsolutePath() ); } catch (NullPointerException nf) { nf.printStackTrace(Log.getWriter()); throw new LayoutLoadException("Missing FOX data value when loading Spacecraft file: " + propertiesFile.getAbsolutePath()); } load_user_params(); } protected void load_user_params() throws LayoutLoadException { // try to load the properties from a file FileInputStream f = null; try { f=new FileInputStream(userPropertiesFile); user_properties = new Properties(); user_properties.load(f); f.close(); } catch (IOException e) { if (f!=null) try { f.close(); } catch (Exception e1) {}; //throw new LayoutLoadException("Could not load spacecraft user settings from: " + userPropertiesFile.getAbsolutePath()); // File does not exist, init save_user_params(); } try { user_keps_name = getUserProperty("name"); user_telemetryDownlinkFreqkHz = Double.parseDouble(getUserProperty("telemetryDownlinkFreqkHz")); user_minFreqBoundkHz = Double.parseDouble(getUserProperty("minFreqBoundkHz")); user_maxFreqBoundkHz = Double.parseDouble(getUserProperty("maxFreqBoundkHz")); String t = getOptionalUserProperty("track"); if (t == null) user_track = true; else user_track = Boolean.parseBoolean(t); String serv = getOptionalUserProperty("localServer"); if (serv == null) user_localServer = null; else user_localServer = serv; String p = getOptionalUserProperty("localServerPort"); if (p == null) user_localServerPort = 0; else user_localServerPort = Integer.parseInt(p); String pri = getOptionalUserProperty("priority"); if (pri == null) user_priority = 1; else user_priority = Integer.parseInt(pri); String tmp_user_format = getUserProperty("user_format"); // Make sure this is a valid format, otherwise we stay with the value from the MASTER file. Needed to cope with invalid legacy formats TelemFormat selectedFormat = this.satManager.getFormatByName(Config.format); if (selectedFormat != null) { user_format = tmp_user_format; } user_display_name = getUserProperty("displayName"); String gpsTime = getOptionalProperty("useGPSTimeForT0"); if (gpsTime != null) { user_useGPSTimeForT0 = Boolean.parseBoolean(getProperty("user_useGPSTimeForT0")); } } catch (NumberFormatException nf) { nf.printStackTrace(Log.getWriter()); throw new LayoutLoadException("Corrupt data found: "+ nf.getMessage() + "\nwhen processing Spacecraft user settings: " + userPropertiesFile.getAbsolutePath() ); } catch (LayoutLoadException L) { Log.infoDialog("Paramater Missing when loading User Spacecraft Properties", "For: "+user_keps_name+". If this is a new Spacecraft file or an upgrade then new values will be initialized."); save_user_params(); } catch (NullPointerException nf) { //nf.printStackTrace(Log.getWriter()); //throw new LayoutLoadException("Missing data value: "+ nf.getMessage() + "\nwhen processing Spacecraft user settings: " + userPropertiesFile.getAbsolutePath() ); // missing a value is OK, we must have it from the MASTER file. It will get saved at next save. Log.errorDialog("Initialization Corruption for User Properties", "For: "+user_keps_name+". If this is a new Spacecraft file then new values will be initialized."); save_user_params(); } try { if (!hasFOXDB_V3) user_BATTERY_CURRENT_ZERO = Double.parseDouble(getUserProperty("BATTERY_CURRENT_ZERO")); String error = getOptionalUserProperty("mpptResistanceError"); if (error != null) { user_mpptResistanceError = Double.parseDouble(error); hasMpptSettings = true; } String threshold = getOptionalUserProperty("mpptSensorOffThreshold"); if (threshold != null) { user_mpptSensorOffThreshold = Integer.parseInt(threshold); hasMpptSettings = true; } String mems_x = getOptionalUserProperty("memsRestValueX"); if (mems_x != null) { user_memsRestValueX = Integer.parseInt(mems_x); } String mems_y = getOptionalUserProperty("memsRestValueY"); if (mems_y != null) { user_memsRestValueY = Integer.parseInt(mems_y); } String mems_z = getOptionalUserProperty("memsRestValueZ"); if (mems_z != null) { user_memsRestValueZ = Integer.parseInt(mems_z); } if (user_memsRestValueX != 0 && user_memsRestValueY != 0 & user_memsRestValueZ != 0) hasMemsRestValues = true; } catch (NumberFormatException nf) { nf.printStackTrace(Log.getWriter()); throw new LayoutLoadException("Corrupt FOX data found when loading Spacecraft file: " + propertiesFile.getAbsolutePath() ); } catch (NullPointerException nf) { nf.printStackTrace(Log.getWriter()); throw new LayoutLoadException("Missing FOX data value when loading Spacecraft file: " + propertiesFile.getAbsolutePath()); } } /** * We have a CAN Bus and need to load the additional layouts for CAN Packts * These are defined in frames.csv in a subdirectory with the name of the spacecraft */ private void loadCanLayouts() { try { canFrames = new CanFrames( this.canFileDir+ File.separator +"frames.csv"); int canLayoutNum = canFrames.NUMBER_OF_FIELDS; Log.println("Loading " + canLayoutNum + " CAN Layouts"); BitArrayLayout[] existingLayouts = layout; layout = new BitArrayLayout[layout.length+canLayoutNum]; int i = 0; for (BitArrayLayout l : existingLayouts) layout[i++] = l; for (String frameName : canFrames.frame) { layout[i] = new BitArrayLayout( Config.currentDir + File.separator + Spacecraft.SPACECRAFT_DIR +File.separator + this.canFileDir+ File.separator + frameName + ".csv"); layout[i].name = frameName; layout[i].parentLayout = "cantelemetry"; // give it any name so that it has a parent and is not a top level "payload" i++; } numberOfLayouts = layout.length; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (LayoutLoadException e) { // TODO Auto-generated catch block e.printStackTrace(); } //layout[i] = new BitArrayLayout(layoutFilename[i]); } protected String getOptionalProperty(String key) throws LayoutLoadException { String value = properties.getProperty(key); if (value == null) { return null; } return value; } protected boolean getOptionalBooleanProperty(String key) throws LayoutLoadException { String value = properties.getProperty(key); if (value == null) { return false; } boolean b = Boolean.parseBoolean(value); return b; } protected String getOptionalUserProperty(String key) throws LayoutLoadException { String value = user_properties.getProperty(key); if (value == null) { return null; } return value; } protected String getProperty(String key) throws LayoutLoadException { String value = properties.getProperty(key); if (value == null) { throw new LayoutLoadException("Missing data value: " + key + " when loading Spacecraft file: \n" + propertiesFile.getAbsolutePath() ); // throw new NullPointerException(); } return value; } protected String getUserProperty(String key) throws LayoutLoadException { String value = user_properties.getProperty(key); if (value == null) { throw new LayoutLoadException("Missing user data value: " + key + " when loading Spacecraft file: \n" + userPropertiesFile.getAbsolutePath() ); // throw new NullPointerException(); } return value; } /** * The default save just saves the user editable params. FoxTelem will never edit the master file */ public void save() { save_user_params(); } protected void store_user_params() { FileOutputStream f = null; try { f=new FileOutputStream(userPropertiesFile); user_properties.store(f, "Fox 1 Telemetry Decoder User Spacecraft Properties"); f.close(); } catch (FileNotFoundException e1) { if (f!=null) try { f.close(); } catch (Exception e2) {}; Log.errorDialog("ERROR", "Could not write spacecraft user properties file. Check permissions on run directory or on the file"); e1.printStackTrace(Log.getWriter()); } catch (IOException e1) { if (f!=null) try { f.close(); } catch (Exception e3) {}; Log.errorDialog("ERROR", "Error writing spacecraft user properties file"); e1.printStackTrace(Log.getWriter()); } } protected void save_user_params() { user_properties = new Properties(); // clean record ready to save user_properties.setProperty("name", user_keps_name); user_properties.setProperty("displayName", user_display_name); user_properties.setProperty("telemetryDownlinkFreqkHz", Double.toString(user_telemetryDownlinkFreqkHz)); user_properties.setProperty("minFreqBoundkHz", Double.toString(user_minFreqBoundkHz)); user_properties.setProperty("maxFreqBoundkHz", Double.toString(user_maxFreqBoundkHz)); user_properties.setProperty("track", Boolean.toString(user_track)); user_properties.setProperty("user_format", user_format); user_properties.setProperty("user_useGPSTimeForT0", Boolean.toString(user_useGPSTimeForT0)); if (user_localServer != null) { user_properties.setProperty("localServer",user_localServer); user_properties.setProperty("localServerPort", Integer.toString(user_localServerPort)); } user_properties.setProperty("priority", Integer.toString(user_priority)); if (!this.hasFOXDB_V3) user_properties.setProperty("BATTERY_CURRENT_ZERO", Double.toString(user_BATTERY_CURRENT_ZERO)); if (this.hasMpptSettings) { user_properties.setProperty("mpptResistanceError", Double.toString(user_mpptResistanceError)); user_properties.setProperty("mpptSensorOffThreshold", Integer.toString(user_mpptSensorOffThreshold)); } if (hasMemsRestValues) { user_properties.setProperty("memsRestValueX", Integer.toString(user_memsRestValueX)); user_properties.setProperty("memsRestValueY", Integer.toString(user_memsRestValueY)); user_properties.setProperty("memsRestValueZ", Integer.toString(user_memsRestValueZ)); } user_properties.setProperty("hasModeInHeader", Boolean.toString(hasModeInHeader)); store_user_params(); } public class SortedProperties extends Properties { private static final long serialVersionUID = 1L; /** * constructor * * @param unsortedProperties */ public SortedProperties(Properties unsortedProperties) { putAll(unsortedProperties); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public synchronized Enumeration keys() { Enumeration<Object> keysEnum = super.keys(); Vector<String> keyList = new Vector<String>(); while (keysEnum.hasMoreElements()) { keyList.add((String) keysEnum.nextElement()); } Collections.sort(keyList); return keyList.elements(); } @Override public Set<java.util.Map.Entry<Object, Object>> entrySet() { // use a TreeMap since in java 9 entrySet() instead of keys() is used in store() TreeMap<Object, Object> treeMap = new TreeMap<>(); Set<Map.Entry<Object, Object>> entrySet = super.entrySet(); for (Map.Entry<Object, Object> entry : entrySet) { treeMap.put(entry.getKey(), entry.getValue()); } return Collections.synchronizedSet(treeMap.entrySet()); } } protected void store_master_params() { final Properties tmp = new SortedProperties(properties); /** Entry set is called post Java 8, so we would use this Properties tmp = new Properties() { private static final long serialVersionUID = 1L; @Override public synchronized Set<Map.Entry<Object, Object>> entrySet() { return Collections.synchronizedSet( super.entrySet() .stream() .sorted(Comparator.comparing(e -> e.getKey().toString())) .collect(Collectors.toCollection(LinkedHashSet::new))); } }; tmp.putAll(properties); */ FileOutputStream f = null; try { f=new FileOutputStream(propertiesFile); tmp.store(f, "AMSAT Spacecraft Properties"); f.close(); } catch (FileNotFoundException e1) { if (f!=null) try { f.close(); } catch (Exception e2) {}; Log.errorDialog("ERROR", "Could not write spacecraft MASTER file. Check permissions on run directory or on the file"); e1.printStackTrace(Log.getWriter()); } catch (IOException e1) { if (f!=null) try { f.close(); } catch (Exception e3) {}; Log.errorDialog("ERROR", "Error writing spacecraft MASTER file"); e1.printStackTrace(Log.getWriter()); } } /** * This should never be called by the decoder. This is only called by the spacecraft editor * */ public void save_master_params() { // Store the MASTER params properties = new Properties(); // clean empty file // Store the values properties.setProperty("foxId", String.valueOf(foxId)); properties.setProperty("series", String.valueOf(series)); properties.setProperty("IHU_SN", String.valueOf(IHU_SN)); properties.setProperty("catalogNumber", String.valueOf(catalogNumber)); properties.setProperty("name", user_keps_name); properties.setProperty("description", description); properties.setProperty("model", String.valueOf(model)); properties.setProperty("numberOfLookupTables", String.valueOf(numberOfLookupTables)); for (int i=0; i < numberOfLookupTables; i++) { if (lookupTable[i] != null) properties.setProperty("lookupTable"+i,lookupTable[i].getName()); if (this.lookupTableFilename[i] != null) properties.setProperty("lookupTable"+i+".filename",lookupTableFilename[i]); } properties.setProperty("numberOfLayouts", String.valueOf(numberOfLayouts)); for (int i=0; i < numberOfLayouts; i++) { if (this.layoutFilename[i] != null) properties.setProperty("layout"+i+".filename",layoutFilename[i]); if (this.layout[i] != null) { properties.setProperty("layout"+i+".name",layout[i].name); if (!layout[i].typeStr.equalsIgnoreCase("")) properties.setProperty("layout"+i+".type",layout[i].typeStr); if (layout[i].title != null) properties.setProperty("layout"+i+".title",layout[i].title); if (layout[i].shortTitle != null) properties.setProperty("layout"+i+".shortTitle",layout[i].shortTitle); if (layout[i].parentLayout != null && !layout[i].parentLayout.equalsIgnoreCase("")) properties.setProperty("layout"+i+".parentLayout",layout[i].parentLayout); properties.setProperty("layout"+i+".hasGPSTime",String.valueOf(layout[i].hasGPSTime)); } } properties.setProperty("numberOfSources", String.valueOf(numberOfSources)); for (int i=0; i < numberOfSources; i++) { if (sourceName[i] != null) properties.setProperty("source"+i+".name",sourceName[i]); if (sourceFormatName != null && sourceFormatName[i] != null) properties.setProperty("source"+i+".formatName",sourceFormatName[i]); } properties.setProperty("measurementsFileName", measurementsFileName); properties.setProperty("passMeasurementsFileName", passMeasurementsFileName); // optional properties properties.setProperty("useConversionCoeffs", String.valueOf(useConversionCoeffs)); /////// IF TRUE SAVE THE FILE NAMES HERE if (useConversionCoeffs) { if (conversionCurvesFileName != null) properties.setProperty("conversionCurvesFileName", String.valueOf(conversionCurvesFileName)); if (conversionExpressionsFileName != null) properties.setProperty("conversionExpressionsFileName", String.valueOf(conversionExpressionsFileName)); } properties.setProperty("numberOfStringLookupTables", String.valueOf(numberOfStringLookupTables)); for (int i=0; i < numberOfStringLookupTables; i++) { if (this.stringLookupTable[i] != null) { properties.setProperty("stringLookupTable"+i,stringLookupTable[i].getName()); properties.setProperty("stringLookupTable"+i+".filename",stringLookupTableFilename[i]); } } properties.setProperty("hasFOXDB_V3", String.valueOf(hasFOXDB_V3)); // user params that need default value in master file properties.setProperty("telemetryDownlinkFreqkHz", String.valueOf(user_telemetryDownlinkFreqkHz)); properties.setProperty("minFreqBoundkHz", String.valueOf(user_minFreqBoundkHz)); properties.setProperty("maxFreqBoundkHz", String.valueOf(user_maxFreqBoundkHz)); properties.setProperty("track", String.valueOf(user_track)); properties.setProperty("priority", String.valueOf(user_priority)); properties.setProperty("user_format", user_format); properties.setProperty("displayName", String.valueOf(user_display_name)); // Frame Layouts properties.setProperty("numberOfFrameLayouts", String.valueOf(numberOfFrameLayouts)); for (int i=0; i < numberOfFrameLayouts; i++) { if (this.frameLayout[i] != null) { properties.setProperty("frameLayout"+i+".name",frameLayout[i].name); properties.setProperty("frameLayout"+i+".filename",this.frameLayoutFilename[i]); } } if (user_localServer != null) { properties.setProperty("localServer",user_localServer); properties.setProperty("localServerPort", Integer.toString(user_localServerPort)); } if (!this.hasFOXDB_V3) properties.setProperty("BATTERY_CURRENT_ZERO", Double.toString(user_BATTERY_CURRENT_ZERO)); if (this.hasMpptSettings) { properties.setProperty("mpptResistanceError", Double.toString(user_mpptResistanceError)); properties.setProperty("mpptSensorOffThreshold", Integer.toString(user_mpptSensorOffThreshold)); } if (hasMemsRestValues) { properties.setProperty("memsRestValueX", Integer.toString(user_memsRestValueX)); properties.setProperty("memsRestValueY", Integer.toString(user_memsRestValueY)); properties.setProperty("memsRestValueZ", Integer.toString(user_memsRestValueZ)); } properties.setProperty("useIHUVBatt", Boolean.toString(useIHUVBatt)); properties.setProperty("hasModeInHeader", Boolean.toString(hasModeInHeader)); properties.setProperty("hasImprovedCommandReceiver", Boolean.toString(hasImprovedCommandReceiver)); properties.setProperty("hasImprovedCommandReceiverII", Boolean.toString(hasImprovedCommandReceiverII)); properties.setProperty("hasCanBus", Boolean.toString(hasCanBus)); properties.setProperty("hasFrameCrc", Boolean.toString(this.hasFrameCrc)); for (int i=0; i<4; i++) { properties.setProperty("EXP"+(i+1), Integer.toString(experiments[i])); } properties.setProperty("hasGPSTime", Boolean.toString(hasGPSTime)); // things you can't edit don't need to be passed through because they will have the same value in the properties file still store_master_params(); } private void loadConversionCurves(String conversionCurvesFileName) throws FileNotFoundException, IOException { try (BufferedReader br = new BufferedReader(new FileReader(conversionCurvesFileName))) { // try with resource closes it String line = null; //line = br.readLine(); // read the header, which we ignore int linenum = 0; while ((line = br.readLine()) != null) { String[] values = line.split(","); if (values.length >= ConversionCurve.CSF_FILE_ROW_LENGTH) try { ConversionCurve conversion = new ConversionCurve(values, this); if (conversions.containsKey(conversion.getName())) { // we have a namespace clash, warn the user Log.errorDialog("DUPLICATE CURVE NAME", this.user_keps_name + "- Conversion Curve already defined. This duplicate name will not be stored: " + conversion.getName()); } else { conversions.put(conversion.getName(), conversion); Log.println("Stored: " + conversion); } linenum++; } catch (IllegalArgumentException e) { if (linenum == 0) { // ignore the header }else { Log.println("Could not load conversion: " + e); Log.errorDialog("CORRUPT CONVERSION: ", e.toString()); // ignore this corrupt row } } } } } private void loadConversionExpresions(String conversionExpressionsFileName) throws FileNotFoundException, IOException, LayoutLoadException { try (BufferedReader br = new BufferedReader(new FileReader(conversionExpressionsFileName))) { // try with resource closes it String line = null; //br.readLine(); // read the header, which we ignore int linenum = 0; while ((line = br.readLine()) != null) { String[] values = line.split(","); // Don't check the length because we are allowed to have commas in the description try { ConversionMathExpression conversion = new ConversionMathExpression(values[0], values[1], this); // name, equation if (conversions.containsKey(conversion.getName())) { // we have a namespace clash, warn the user Log.errorDialog("DUPLICATE CONVERSION EXPRESSION NAME", this.user_keps_name + "- A Curve, expression or table is already defined called " + conversion.getName() + "\nThis duplicate name will not be stored."); } else { conversions.put(conversion.getName(), conversion); Log.println("Expression loaded: " + conversion); } linenum++; } catch (IllegalArgumentException e) { if (linenum == 0) { // ignore the header }else { Log.println("Could not load conversion: " + e); Log.errorDialog("CORRUPT CONVERSION: ", e.toString()); // ignore this corrupt row } } } } } public void saveTimeZeroSeries() throws IOException { String log = series + foxId + Config.t0UrlFile; if (!Config.logFileDirectory.equalsIgnoreCase("")) { log = Config.logFileDirectory + File.separator + log; Log.println("Loading: " + log); } //use buffering and replace the existing file File aFile = new File(log ); Writer output = new BufferedWriter(new FileWriter(aFile, false)); int r = 0; try { for (long l : timeZero) { output.write(r +"," + l + "\n" ); output.flush(); r++; } } finally { // Make sure it is closed even if we hit an error output.flush(); output.close(); } } public boolean loadTimeZeroSeries(String log) throws FileNotFoundException { timeZero = new ArrayList<Long>(100); String line = null; if (log == null) { // then use the default log = series + foxId + Config.t0UrlFile; if (!Config.logFileDirectory.equalsIgnoreCase("")) { log = Config.logFileDirectory + File.separator + log; Log.println("Loading: " + log); } } //File aFile = new File(log ); boolean hasContent = false; BufferedReader dis = new BufferedReader(new FileReader(log)); try { while ((line = dis.readLine()) != null) { if (line != null) { StringTokenizer st = new StringTokenizer(line, ","); int reset = Integer.valueOf(st.nextToken()).intValue(); long uptime = Long.valueOf(st.nextToken()).longValue(); //Log.println("Loaded T0: " + reset + ": " + uptime); if (reset == timeZero.size()) { timeZero.add(uptime); hasContent = true; } else throw new IndexOutOfBoundsException("Reset in T0 file is missing or out of sequence: " + reset); } } dis.close(); } catch (IOException e) { e.printStackTrace(Log.getWriter()); return false; } catch (NumberFormatException n) { n.printStackTrace(Log.getWriter()); return false; } catch (NoSuchElementException m) { // This was likely a blank file because we have no internet connection return false; } finally { try { dis.close(); } catch (IOException e) { // ignore error } } return hasContent; } // public String getIdString() { // String id = "??"; // id = Integer.toString(foxId); // // return id; // } /** * Return true if one of the experiment slots contains the Virginia Tech Camera * @return */ public boolean hasCamera() { for (int i=0; i< experiments.length; i++) { if (experiments[i] == EXP_VT_CAMERA) return true; if (experiments[i] == EXP_VT_CAMERA_LOW_RES) return true; } return false; } public boolean hasLowResCamera() { for (int i=0; i< experiments.length; i++) { if (experiments[i] == EXP_VT_CAMERA_LOW_RES) return true; } return false; } public boolean hasMesatCamera() { for (int i=0; i< experiments.length; i++) { if (experiments[i] == EXP_UMAINE_CAMERA) return true; } return false; } /** * Return true if one of the experiment slots contains the HERCI experiment * @return */ public boolean hasHerci() { for (int i=0; i< experiments.length; i++) if (experiments[i] == EXP_IOWA_HERCI) return true; return false; } /** * Return true if one of the experiment slots contains the HERCI experiment * @return */ public boolean hasExperiment(int e) { for (int i=0; i< experiments.length; i++) if (experiments[i] == e) return true; return false; } public String getIdString() { String id = "??"; if (foxId == 1) id = "1A"; else if (foxId == 2) id = "1B"; else if (foxId == 3) id = "1Cliff"; else if (foxId == 4) id = "1D"; else if (foxId == 5) id = "1E"; else id = Integer.toString(foxId); // after the "fox-1" spacecraft just use the fox id return id; } public static String getModeString(int mode) { return Spacecraft.modeNames[mode]; } /** * Return the mode of the spacecraft based in the most recent RT, MAX, MIN and EXP payloads * @param realTime * @param maxPaylaod * @param minPayload * @param radPayload * @return */ public static int determine1A1DMode(PayloadRtValues realTime, PayloadMaxValues maxPayload, PayloadMinValues minPayload, FramePart radPayload) { if (realTime != null && minPayload != null && maxPayload != null) { if (realTime.uptime == minPayload.uptime && minPayload.uptime == maxPayload.uptime) return DATA_MODE; } // Otherwise, if RAD received more recently than max/min and RT // In the compare, a -ve result means older, because the reset or uptime is less // So a result >0 means the object calling the compare is newer if (radPayload != null) if (realTime != null && radPayload.compareTo(realTime) > 0) if (maxPayload == null && minPayload == null) return TRANSPONDER_MODE; else if (maxPayload != null && radPayload.compareTo(maxPayload) > 0) if (minPayload == null) return TRANSPONDER_MODE; else if (radPayload.compareTo(minPayload) > 0) return TRANSPONDER_MODE; // Otherwise find the most recent max/min // if we have just a max payload, or we have both and max is more recent or the same if ((minPayload == null && maxPayload != null) || (maxPayload != null && minPayload != null && maxPayload.compareTo(minPayload) >=0)) { if (maxPayload.getRawValue(SCIENCE_MODE_IND) == 1) return SCIENCE_MODE; else if (maxPayload.getRawValue(SAFE_MODE_IND) == 1) return SAFE_MODE; else return TRANSPONDER_MODE; } else if (minPayload != null) { // this is the case when we have both and min is more recent if (minPayload.getRawValue(SCIENCE_MODE_IND) == 1) return SCIENCE_MODE; else if (minPayload.getRawValue(SAFE_MODE_IND) == 1) return SAFE_MODE; else return TRANSPONDER_MODE; } // return default return TRANSPONDER_MODE; } public String determineModeFromHeader() { // Mode is stored in the header // Find the most recent frame and return the mode that it has SortedFramePartArrayList payloads = new SortedFramePartArrayList(numberOfLayouts); int maxLayouts = 10; // First four layouts are rt, max, min, exp, but we may have mode in any layout. Cap at 10. for (int i=0; i <= maxLayouts && i < layout.length; i++) { //System.err.println("Checking mode in: "+layout[i].name ); FramePart part = Config.payloadStore.getLatest(foxId, layout[i].name); if (part != null) payloads.add(part); } int mode = NO_MODE; if (payloads.size() > 0) mode = payloads.get(payloads.size()-1).newMode; return getModeString(mode); } public static String OLDdetermineModeFromHeader(PayloadRtValues realTime, PayloadMaxValues maxPayload, PayloadMinValues minPayload, FramePart radPayload) { // Mode is stored in the header // Find the most recent frame and return the mode that it has SortedFramePartArrayList payloads = new SortedFramePartArrayList(4); if (realTime != null) payloads.add(realTime); if (maxPayload != null) payloads.add(maxPayload); if (minPayload != null) payloads.add(minPayload); if (radPayload != null) payloads.add(radPayload); int mode = NO_MODE; if (payloads.size() > 0) mode = payloads.get(payloads.size()-1).newMode; return getModeString(mode); } public static String determineModeString(Spacecraft fox, PayloadRtValues realTime, PayloadMaxValues maxPayload, PayloadMinValues minPayload, FramePart radPayload) { int mode; mode = determine1A1DMode(realTime, maxPayload, minPayload, radPayload); return getModeString(mode); } public String toString() { return this.user_display_name; //"Fox-" + getIdString(); } @Override public int compareTo(Spacecraft s2) { if (user_priority == s2.user_priority) return user_display_name.compareTo(s2.user_display_name); else if (user_priority < s2.user_priority) return -1; else if (user_priority > s2.user_priority) return 1; return -1; } }
ac2cz/FoxTelem
src/common/Spacecraft.java
249,690
// CSC 369: Distributed Computing // Alex Dekhtyar // Java Hadoop Template // Section 1: Imports import org.apache.hadoop.io.IntWritable; // Hadoop's serialized int wrapper class import org.apache.hadoop.io.LongWritable; // Hadoop's serialized int wrapper class import org.apache.hadoop.io.Text; // Hadoop's serialized String wrapper class import org.apache.hadoop.mapreduce.Mapper; // Mapper class to be extended by our Map function import org.apache.hadoop.mapreduce.Reducer; // Reducer class to be extended by our Reduce function import org.apache.hadoop.mapreduce.Job; // the MapReduce job class that is used a the driver import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; // class for "pointing" at input file(s) import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; // class for "pointing" at output file import org.apache.hadoop.fs.Path; // Hadoop's implementation of directory path/filename import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat; // input format for key-value files import org.apache.hadoop.conf.Configuration; // Hadoop's configuration object // Exception handling import java.io.IOException; public class IowaLiquor { // Mapper Class Template public static class SwitchMapper extends Mapper< Text, Text, Text, Text > { @Override public void map(Text key, Text value, Context context) throws IOException, InterruptedException { String[] valueStr = value.toString().split(","); String[] date = valueStr[0].split("/"); if(valueStr.length == 24 && valueStr[20].length() > 0 && valueStr[21].length() > 0 && valueStr[22].length() > 0 && Character.isDigit(valueStr[20].charAt(0)) && Character.isDigit(valueStr[22].charAt(0)) && date.length == 3) { String bottles = valueStr[20].replace("\"", ""); String sales = valueStr[21].replace("\"", ""); String vol = valueStr[22].replace("\"", ""); String year = date[2]; double volume = Double.parseDouble(vol) * Double.parseDouble(bottles); String resString = "" + volume + "," + sales; context.write(new Text(year), new Text(resString)); } } // map } // MyMapperClass // Reducer Class Template public static class SwitchReducer // needs to replace the four type labels with actual Java class names extends Reducer< Text, Text, Text, Text> { @Override public void reduce( Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { double totSales = 0.0; double totVol = 0.0; int numSales = 0; for(Text value : values) { String[] valueArr = value.toString().split(","); totVol += Double.parseDouble(valueArr[0]); totSales += Double.parseDouble(valueArr[1]); numSales++; } String resString = "Number of sales: " + numSales + " Total Volume: " + totVol + " Total Sales: " + totSales; context.write(key, new Text(resString)); } // reduce } // reducer // MapReduce Driver // we do everything here in main() public static void main(String[] args) throws Exception { // Step 0: let's get configuration Configuration conf = new Configuration(); conf.set("mapreduce.input.keyvaluelinerecordreader.key.value.separator",","); // learn to process two-column CSV files. // step 1: get a new MapReduce Job object Job job = Job.getInstance(conf); // job = new Job() is now deprecated // step 2: register the MapReduce class job.setJarByClass(IowaLiquor.class); // step 3: Set Input and Output files KeyValueTextInputFormat.addInputPath(job, new Path("/data/", "Iowa_Liquor_Sales.csv")); // put what you need as input file FileOutputFormat.setOutputPath(job, new Path("./test/","iowa-liquorSales")); // put what you need as output file job.setInputFormatClass(KeyValueTextInputFormat.class); // let's make input a CSV file // step 4: Register mapper and reducer job.setMapperClass(SwitchMapper.class); job.setReducerClass(SwitchReducer.class); // step 5: Set up output information job.setOutputKeyClass(Text.class); // specify the output class (what reduce() emits) for key job.setOutputValueClass(Text.class); // specify the output class (what reduce() emits) for value // step 6: Set up other job parameters at will job.setJobName("iowa sales"); // step 8: profit System.exit(job.waitForCompletion(true) ? 0:1); } // main() } // MyMapReduceDriver
QColeman97/Hadoop-Di-Scoop
prob2/IowaLiquor.java
249,691
/** * Author: [email protected] * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version, * provided that any use properly credits the author. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details at http://www.gnu.org * * */ package utils; import java.io.InputStream; import java.util.Properties; public class ConfigReader { public static final String PROPERTIES_FILE = "MetagenomicsTools.properties"; private static ConfigReader configReader = null; private static Properties props = new Properties(); public static final String TRUE = "TRUE"; public static final String YES = "YES"; public static final String BLAST_DIRECTORY = "BLAST_DIRECTORY"; public static final String VERBOSE_CONSOLE = "VERBOSE_CONSOLE"; public static final String PANCREATITIS_DIR = "PANCREATITIS_DIR"; public static final String MACHINE_LEARNING_DIR = "MACHINE_LEARNING_DIR"; public static final String BURKHOLDERIA_DIR = "BURKHOLDERIA_DIR"; public static final String BIG_BLAST_DIR = "BIG_BLAST_DIR"; public static final String GENBANK_CACHE_DIR = "GENBANK_CACHE_DIR"; public static final String REDUCE_OTU_DIR = "REDUCE_OTU_DIR"; public static final String SACCHARINE_RAT_DIR = "SACCHARINE_RAT_DIR"; public static final String IAN_ANOREXIA_DIR = "IAN_ANOREXIA_DIR"; public static final String LACTO_CHECK_DIR = "LACTO_CHECK_DIR"; public static final String MOTHUR_DIR = "MOTHUR_DIR"; public static final String CROSSOVER_EXERCISE_DIR = "CROSSOVER_EXERCISE_DIR"; public static final String ERIN_DATA_DIR = "ERIN_DATA_DIR"; public static final String BLAST_DIR = "BLAST_DIR"; public static final String E_TREE_TEST_DIR = "E_TREE_TEST_DIR"; public static final String RDP_JAR_PATH= "RDP_JAR_PATH"; public static final String MOCK_SEQ_DIR="MOCK_SEQ_DIR"; public static final String UEGP_DIR = "UEGP_DIR"; public static final String D3_DIR = "D3_DIR"; public static final String R_DIRECTORY = "R_DIRECTORY"; public static final String NINA_WITH_DUPLICATES_DIR = "NINA_WITH_DUPLICATES_DIR"; public static final String SANDRA_RIVER_JUNE_2012_Dir = "SANDRA_RIVER_JUNE_2012_Dir"; public static final String CHINA_DIR_DEC_2017 = "CHINA_DIR_DEC_2017"; public static final String METABOLITES_CASE_CONTROL = "METABOLITES_CASE_CONTROL"; public static final String SVM_DIR = "SVM_DIR"; public static final String JANELLE_RNA_SEQ_DIR = "JANELLE_RNA_SEQ_DIR"; public static final String KLEB_DIR="KLEB_DIR"; public static final String BIG_DATA_SCALING_FACTORS = "BIG_DATA_SCALING_FACTORS"; public static final String ADENONMAS_RELEASE_DIR = "ADENONMAS_RELEASE_DIR"; public static final String TOPE_CHECK_DIR = "TOPE_CHECK_DIR"; public static final String SCOTT_PILOT_DIR = "SCOTT_PILOT_DIR"; public static final String CHINA_DIR = "CHINA_DIR"; public static final String MBQC_DIR = "MBQC_DIR"; public static final String RAT_SACH_REANALYSIS_DIR = "RAT_SACH_REANALYSIS_DIR"; public static final String MICROBES_VS_METABOLITES_DIR = "MICROBES_VS_METABOLITES_DIR"; public static final String VANDERBILT_DIR = "VANDERBILT_DIR"; public static final String KYLIE_AGE_DIR = "KYLIE_AGE"; public static final String KYLIE_16S_DIR= "KYLIE_16S_DIR"; public static final String KYLIE_DROPBOX_DIR = "KYLIE_DROPBOX_DIR"; public static final String KATIE_DIR = "KATIE_DIR"; public static final String JOBIN_CARDIO_DIR = "JOBIN_CARDIO_DIR"; public static final String IAN_LONGITUDINAL_DEC_2015_DIR= "IAN_LONGITUDINAL_DEC_2015_DIR"; public static final String TOPE_CONTROL_DIR = "TOPE_CONTROL_DIR"; public static final String HUMAN_IOWA = "HUMAN_IOWA"; public static final String LAURA_DIR = "LAURA_DIR"; public static final String ROSHONDA_CASE_CONTROL_DIR = "ROSHONDA_CASE_CONTROL_DIR"; public static final String CHAPEL_HILL_WORKSHOP_DIR = "CHAPEL_HILL_WORKSHOP_DIR"; public static final String SONJA_2016_DIR = "SONJA_2016_DIR"; public static final String TOPE_DIVERTICULOSIS_DEC_2015_DIR = "TOPE_DIVERTICULOSIS_DEC_2015_DIR"; public static final String TOPE_DIVERTICULOSIS_JAN_2016_DIR = "TOPE_DIVERTICULOSIS_JAN_2016_DIR"; public static final String TOPE_DIVERTICULOSIS_FEB_2016_DIR = "TOPE_DIVERTICULOSIS_FEB_2016_DIR"; public static final String IAN_NOVEMBER_2015 = "IAN_NOVEMBER_2015"; public static final String TANYA_DIR="TANYA_DIR"; public static final String GORAN_TRIAL = "GORAN_TRIAL"; public static final String JENNIFER_TEST_DIR = "JENNIFER_TEST_DIR"; public static final String JOBIN_APRIL_2015_DIR = "JOBIN_APRIL_2015_DIR"; public static final String MARK_AUG_2015_BATCH1_DIR = "MARK_AUG_2015_BATCH1_DIR"; public static final String TOPE_SEP_2015_DIR = "TOPE_SEP_2015_DIR"; public static final String GORAN_OCT_2015_DIR = "GORAN_OCT_2015_DIR"; public static final String IAN_OCT_2015_DIR = "IAN_OCT_2015_DIR"; public static final String FRAGMENT_RECRUITER_SUPPORT_DIR = "FRAGMENT_RECRUITER_SUPPORT_DIR"; public static final String CRE_ORTHOLOGS_DIR = "CRE_ORTHOLOGS_DIR"; public static final String CHS_DIR = "CHS_DIR"; public static final String GORAN_LAB_RAT_DATA = "GORAN_LAB_RAT_DATA"; public static final String TOPE_ONE_AT_A_TIME_DIR = "TOPE_ONE_AT_A_TIME_DIR"; public static final String SANG_LAB_MAY_2016_DIR = "SANG_LAB_MAY_2016_DIR"; public static final String BIOLOCK_J_DIR = "BIOLOCK_J_DIR"; public static final String LYTE_NOV_2016_DIR = "LYTE_NOV_2016_DIR"; public static final String MERGED_ARFF_DIR = "MERGED_ARFF_DIR"; public static final String TING_DIR = "TING_DIR"; public static final String LYTE_BEHAVIOR_MARCH_2017_DIR = "LYTE_BEHAVIOR_MARCH_2017_DIR"; public static final String IAN_MOUSE_AUG_2017_DIR = "IAN_MOUSE_AUG_2017_DIR"; public static final String EMILY_TRANSFER_PROJECT = "EMILY_TRANSFER_PROJECT"; public static final String TANYA_BLOOD_DIR= "TANYA_BLOOD_DIR"; public static final String TANYA_BLOOD_DIR2= "TANYA_BLOOD_DIR2"; public static final String EMILY_JAN_2018_DIR = "EMILY_JAN_2018_DIR"; public static final String EMILY_MAY_2018_DIR = "EMILY_MAY_2018_DIR"; public static final String IAN_ORGANOID_DIRECTORY = "IAN_ORGANOID_DIRECTORY"; public static final String KATIE_BLAST_DIR = "KATIE_BLAST_DIR"; public static final String TANYA_FEB_2018_DIR = "TANYA_FEB_2018_DIR"; public static final String FARNAZ_FEB_2018_DIR = "FARNAZ_FEB_2018_DIR"; public static final String EVAN_FEB_2018_DIR = "EVAN_FEB_2018_DIR"; public static final String PETER_ANTIBODY_DIR = "PETER_ANTIBODY_DIR"; public static final String JAMES_EOE_DIR= "JAMES_EOE_DIR"; public static final String FARNAZ_DADA2_DIR = "FARNAZ_DADA2_DIR"; public static final String HANSEN_ALLELE_DIR = "HANSEN_ALLELE_DIR"; public static final String TOPE_VICKI_DIR = "TOPE_VICKI_DIR"; public static final String LUTHUR_RNA_SEQ_DIR = "LUTHUR_RNA_SEQ_DIR"; public static final String CHINA_MAY_2017_DIR = "CHINA_MAY_2017_DIR"; public static final String AARON_EXERCISE_TEST_DIR = "AARON_EXERCISE_TEST_DIR"; public static final String ENGEL_CHECK_DIR = "ENGEL_CHECK_DIR"; public static final String GRANT_CHECK_DIR = "GRANT_CHECK_DIR"; public static final String TB_JUNE_2019_DIR = "TB_JUNE_2019_DIR"; public static final String PIERCE_DEC_2019_DIR = "PIERCE_DEC_2019_DIR"; public static final String VICKI_DEC_2019_DIR = "VICKI_DEC_2019_DIR"; public static final String FARNAZ_CROSS_DIR_BS = "FARNAZ_CROSS_DIR_BS"; public static String getFarnazCrossDirBS() throws Exception { return getConfigReader().getAProperty(FARNAZ_CROSS_DIR_BS); } public static String getAaronExerciseDirectory() throws Exception { return getConfigReader().getAProperty(AARON_EXERCISE_TEST_DIR ); } public static String getVicki2019Directory() throws Exception { return getConfigReader().getAProperty(VICKI_DEC_2019_DIR ); } public static String getEngelCheckDir() throws Exception { return getConfigReader().getAProperty(ENGEL_CHECK_DIR); } public static String getPierce2019Dir() throws Exception { return getConfigReader().getAProperty(PIERCE_DEC_2019_DIR ); } public static String getGrantCheckDir() throws Exception { return getConfigReader().getAProperty(GRANT_CHECK_DIR); } public static final String getTopeVickiDir() throws Exception { return getConfigReader().getAProperty(TOPE_VICKI_DIR); } public static String getPeterAntibodyDirectory() throws Exception { return getConfigReader().getAProperty(PETER_ANTIBODY_DIR); } public static String getChinaMay2017Dir() throws Exception { return getConfigReader().getAProperty(CHINA_MAY_2017_DIR); } public static String getHansenAlleleDirectory() throws Exception { return getConfigReader().getAProperty(HANSEN_ALLELE_DIR); } public static String getFarnazFeb2018Directory() throws Exception { return getConfigReader().getAProperty(FARNAZ_FEB_2018_DIR); } public static String getFarnazDada2Directory() throws Exception { return getConfigReader().getAProperty(FARNAZ_DADA2_DIR); } public static String getJamesEoeDirectory() throws Exception { return getConfigReader().getAProperty(JAMES_EOE_DIR); } public static String getEvanFeb2018Dir() throws Exception { return getConfigReader().getAProperty(EVAN_FEB_2018_DIR); } public static String getLauraDir() throws Exception { return getConfigReader().getAProperty(LAURA_DIR); } public static String getHumanIowa() throws Exception { return getConfigReader().getAProperty(HUMAN_IOWA); } public static String getIanOrganoidDirectory() throws Exception { return getConfigReader().getAProperty(IAN_ORGANOID_DIRECTORY); } public static String getTanyaFeb2018Directory() throws Exception { return getConfigReader().getAProperty(TANYA_FEB_2018_DIR); } public static String getKatieBlastDir() throws Exception { return getConfigReader().getAProperty(KATIE_BLAST_DIR); } public static String getFragmentRecruiterSupportDir() throws Exception { return getConfigReader().getAProperty(FRAGMENT_RECRUITER_SUPPORT_DIR ); } public static String getEmilyTransferProject() throws Exception { return getConfigReader().getAProperty(EMILY_TRANSFER_PROJECT); } public static String getEmilyJan2018Dir() throws Exception { return getConfigReader().getAProperty(EMILY_JAN_2018_DIR); } public static String getEmilyMay2018Dir() throws Exception { return getConfigReader().getAProperty(EMILY_MAY_2018_DIR); } public static String getBioLockJDir() throws Exception { return getConfigReader().getAProperty(BIOLOCK_J_DIR); } public static String getTanyaBloodDir() throws Exception { return getConfigReader().getAProperty(TANYA_BLOOD_DIR); } public static String getTanyaBloodDir2() throws Exception { return getConfigReader().getAProperty(TANYA_BLOOD_DIR2); } public static String getIanMouseAug2017Dir() throws Exception { return getConfigReader().getAProperty(IAN_MOUSE_AUG_2017_DIR); } public static String getSangLabMay2016Dir() throws Exception { return getConfigReader().getAProperty(SANG_LAB_MAY_2016_DIR); } public static String getUEGPDir() throws Exception { return getConfigReader().getAProperty(UEGP_DIR); } public static String getLyteNov2016Dir() throws Exception { return getConfigReader().getAProperty(LYTE_NOV_2016_DIR); } public static String getChinaDecember2017Dir() throws Exception { return getConfigReader().getAProperty(CHINA_DIR_DEC_2017); } public static String getLactoCheckDir() throws Exception { return getConfigReader().getAProperty(LACTO_CHECK_DIR); } public static String getTopeOneAtATimeDir() throws Exception { return getConfigReader().getAProperty(TOPE_ONE_AT_A_TIME_DIR); } public static String getMergedArffDir() throws Exception { return getConfigReader().getAProperty(MERGED_ARFF_DIR); } public static String getLyteBehaviorMarch2017Dir() throws Exception { return getConfigReader().getAProperty(LYTE_BEHAVIOR_MARCH_2017_DIR); } public static boolean isVerboseConsole() throws Exception { return getConfigReader().isSetToTrue(VERBOSE_CONSOLE); } public static String getTingDir() throws Exception { return getConfigReader().getAProperty(TING_DIR); } public static String getGoranLabRatData() throws Exception { return getConfigReader().getAProperty(GORAN_LAB_RAT_DATA ); } public static String getTanyaDir() throws Exception { return getConfigReader().getAProperty(TANYA_DIR); } public static String getIanNov2015Dir() throws Exception { return getConfigReader().getAProperty(IAN_NOVEMBER_2015); } public static String getJobinLabRNASeqDir() throws Exception { throw new Exception("From legacy code"); } public static String getTopeJan2016Dir() throws Exception { return getConfigReader().getAProperty(TOPE_DIVERTICULOSIS_JAN_2016_DIR); } public static String getTopeFeb2016Dir() throws Exception { return getConfigReader().getAProperty(TOPE_DIVERTICULOSIS_FEB_2016_DIR); } public static String getTopeControlDir() throws Exception { return getConfigReader().getAProperty(TOPE_CONTROL_DIR); } public static String getIanLongitudnalDec2015Dir() throws Exception { return getConfigReader().getAProperty(IAN_LONGITUDINAL_DEC_2015_DIR); } public static String getSonja2016Dir() throws Exception { return getConfigReader().getAProperty(SONJA_2016_DIR); } public static String getTopeDiverticulosisDec2015Dir() throws Exception { return getConfigReader().getAProperty(TOPE_DIVERTICULOSIS_DEC_2015_DIR); } public static String getMarkAug2015Batch1Dir() throws Exception { return getConfigReader().getAProperty(MARK_AUG_2015_BATCH1_DIR); } public static String getCREOrthologsDir() throws Exception { return getConfigReader().getAProperty(CRE_ORTHOLOGS_DIR); } public static String getCHSDir() throws Exception { return getConfigReader().getAProperty(CHS_DIR); } public static String getTopeSep2015Dir() throws Exception { return getConfigReader().getAProperty(TOPE_SEP_2015_DIR); } public static String getGoranOct2015Dir() throws Exception { return getConfigReader().getAProperty(GORAN_OCT_2015_DIR); } public static String getJobinApril2015Dir() throws Exception { return getConfigReader().getAProperty(JOBIN_APRIL_2015_DIR); } public static String getRoshondaCaseControlDir() throws Exception { return getConfigReader().getAProperty(ROSHONDA_CASE_CONTROL_DIR); } public static String getKatieDir() throws Exception { return getConfigReader().getAProperty(KATIE_DIR); } public static String getChapelHillWorkshopDir() throws Exception { return getConfigReader().getAProperty(CHAPEL_HILL_WORKSHOP_DIR); } public static String getNinaWithDuplicatesDir() throws Exception { return getConfigReader().getAProperty(NINA_WITH_DUPLICATES_DIR); } public static String getJobinCardioDir() throws Exception { return getConfigReader().getAProperty(JOBIN_CARDIO_DIR); } public static String getRachSachReanalysisDir() throws Exception { return getConfigReader().getAProperty(RAT_SACH_REANALYSIS_DIR); } public static String getIanOct2015Dir() throws Exception { return getConfigReader().getAProperty(IAN_OCT_2015_DIR); } public static String getJenniferTestDir() throws Exception { return getConfigReader().getAProperty(JENNIFER_TEST_DIR); } public static String getVanderbiltDir() throws Exception { return getConfigReader().getAProperty(VANDERBILT_DIR); } public static String getGoranTrialDir() throws Exception { return getConfigReader().getAProperty(GORAN_TRIAL); } public static String getKylieDropoxDir() throws Exception { return getConfigReader().getAProperty(KYLIE_DROPBOX_DIR); } public static String getSvmDir() throws Exception { return getConfigReader().getAProperty(SVM_DIR); } public static String getTopeCheckDir() throws Exception { return getConfigReader().getAProperty(TOPE_CHECK_DIR); } public static String getMetabolitesCaseControl() throws Exception { return getConfigReader().getAProperty(METABOLITES_CASE_CONTROL); } public static String getKylie16SDir() throws Exception { return getConfigReader().getAProperty(KYLIE_16S_DIR); } public static String getKylieAgeDir() throws Exception { return getConfigReader().getAProperty(KYLIE_AGE_DIR); } public static String getChinaDir() throws Exception { return getConfigReader().getAProperty(CHINA_DIR); } public static String getAdenomasReleaseDir() throws Exception { return getConfigReader().getAProperty(ADENONMAS_RELEASE_DIR); } public static String getKlebDir() throws Exception { return getConfigReader().getAProperty(KLEB_DIR); } public static String getMicrboesVsMetabolitesDir() throws Exception { return getConfigReader().getAProperty(MICROBES_VS_METABOLITES_DIR); } public static String getScottPilotDataDir() throws Exception { return getConfigReader().getAProperty(SCOTT_PILOT_DIR); } public static String getMbqcDir() throws Exception { return getConfigReader().getAProperty(MBQC_DIR); } public static String getMachineLearningDir() throws Exception { return getConfigReader().getAProperty(MACHINE_LEARNING_DIR); } public static String getSaccharineRatDir() throws Exception { return getConfigReader().getAProperty(SACCHARINE_RAT_DIR); } public static String getD3Dir() throws Exception { return getConfigReader().getAProperty(D3_DIR); } public static String getBigDataScalingFactorsDir() throws Exception { return getConfigReader().getAProperty(BIG_DATA_SCALING_FACTORS); } public static String getSandraRiverJune2012Dir() throws Exception { return getConfigReader().getAProperty(SANDRA_RIVER_JUNE_2012_Dir); } public static String getETreeTestDir() throws Exception { return getConfigReader().getAProperty(E_TREE_TEST_DIR); } public static String getMockSeqDir() throws Exception { return getConfigReader().getAProperty(MOCK_SEQ_DIR); } public static String getRDirectory() throws Exception { return getConfigReader().getAProperty(R_DIRECTORY); } public static String getRDPJarPath() throws Exception { return getConfigReader().getAProperty(RDP_JAR_PATH); } public static String getIanAnorexiaDir() throws Exception { return getConfigReader().getAProperty(IAN_ANOREXIA_DIR); } public static String getJanelleRNASeqDir() throws Exception { return getConfigReader().getAProperty(JANELLE_RNA_SEQ_DIR); } public static String getLuthurJan2019Dir() throws Exception { return getConfigReader().getAProperty(LUTHUR_RNA_SEQ_DIR); } private boolean isSetToTrue(String namedProperty) { Object obj = props.get(namedProperty); if (obj == null) return false; if (obj.toString().equalsIgnoreCase(TRUE) || obj.toString().equalsIgnoreCase(YES)) return true; return false; } public static String getReducedOTUDir() throws Exception { return getConfigReader().getAProperty(REDUCE_OTU_DIR); } private static String getAProperty(String namedProperty) throws Exception { Object obj = props.get(namedProperty); if (obj == null) throw new Exception("Error! Could not find " + namedProperty + " in " + PROPERTIES_FILE); return obj.toString(); } public static String getBlastDirectory() throws Exception { return getConfigReader().getAProperty(BLAST_DIR); } public static String getTb_June_2019_Dir() throws Exception { return getConfigReader().getAProperty(TB_JUNE_2019_DIR); } public static String getBurkholderiaDir() throws Exception { return getConfigReader().getAProperty(BURKHOLDERIA_DIR); } public static String getPancreatitisDir() throws Exception { return getConfigReader().getAProperty(PANCREATITIS_DIR); } public static String getBigBlastDir() throws Exception { return getConfigReader().getAProperty(BIG_BLAST_DIR); } public static String getMothurDir() throws Exception { return getConfigReader().getAProperty(MOTHUR_DIR); } public static String getErinDataDir() throws Exception { return getConfigReader().getAProperty(ERIN_DATA_DIR); } public static String getGenbankCacheDir() throws Exception { return getConfigReader().getAProperty(GENBANK_CACHE_DIR); } public static String getCrossoverExerciseDir() throws Exception { return getConfigReader().getAProperty(CROSSOVER_EXERCISE_DIR); } private ConfigReader() throws Exception { Object o = new Object(); InputStream in = o.getClass().getClassLoader() .getSystemResourceAsStream(PROPERTIES_FILE); if (in == null) throw new Exception("Error! Could not find " + PROPERTIES_FILE + " anywhere on the current classpath"); props = new Properties(); props.load(in); } private static synchronized ConfigReader getConfigReader() throws Exception { if (configReader == null) { configReader = new ConfigReader(); } return configReader; } }
afodor/metagenomicsTools
src/utils/ConfigReader.java
249,694
public class funkcjaLiniowa { private int a, b; public funkcjaLiniowa(int a, int b) { this.a=a; this.b=b; } public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } void wypisz() { System.out.println("Wzor funkcji liniowej to f(x)= "+a+"x + "+b); } int ileMiejscZerowych() { int x; if(a==0 && b!=0) x=0; if(a==0 && b==0) x=Integer.MAX_VALUE; else x= 1; System.out.println(x); return x; } }
icerokK/funkcjaLiniowaKwadratowa
src/funkcjaLiniowa.java
249,695
/** * klasa FunkcjaLiniowa - parametry a i b * * @author A Mlynczak */ public class FunkcjaLiniowa extends Funkcja{ private double a; private double b; /** * kostruktor */ public FunkcjaLiniowa(double _a, double _b){ a = _a; b = _b; nazwa = "Funkcja_Liniowa"; } @Override public double oblicz(double x){ return a*x + b; } @Override public double[] miejscaZerowe(){ double[] result; if(a!=0){ result = new double[1]; result[0] = (-b)/a; }else{ result = new double[0]; } return result; } }
amlynczak/Programowanie-Obiektowe-2
lab08/FunkcjaLiniowa.java
249,696
package jisa.visa; import jisa.Util; import jisa.addresses.Address; import jisa.devices.DeviceException; import jisa.devices.interfaces.Instrument; import jisa.visa.connections.*; import jisa.visa.drivers.Driver; import jisa.visa.exceptions.VISAException; import kotlin.jvm.JvmClassMappingKt; import kotlin.reflect.KClass; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * Generic instrument encapsulation via VISA */ public class VISADevice implements Instrument { public final static int DEFAULT_TIMEOUT = 13; public final static int DEFAULT_EOI = 1; public final static int DEFAULT_EOS = 0; public final static int EOS_RETURN = 5130; public final static int LF_TERMINATOR = 0x0A; public final static int CR_TERMINATOR = 0x0D; public final static int CRLF_TERMINATOR = 0x0D0A; public final static String C_IDN = "*IDN?"; private ScheduledExecutorService scheduler = null; private int ioInterval = 0; private final Semaphore ioPermits = new Semaphore(1); private final Runnable ioWait = ioPermits::release; private boolean writeWait = false; private boolean readWait = false; private final static List<WeakReference<VISADevice>> opened = new LinkedList<>(); static { /* * Close any surviving connections when the JVM shuts down. */ Util.addShutdownHook(() -> { for (WeakReference<VISADevice> reference : opened) { VISADevice device = reference.get(); if (device != null) { try { device.close(); } catch (Exception ignored) {} } } }); } private final List<String> toRemove = new LinkedList<>(); private final Connection connection; private final Address address; private String terminator = ""; private String lastCommand = null; private String lastRead = null; private int readBufferSize = 1024; private int retryCount = 3; private int timeout = 2000; public VISADevice(Address address) throws IOException { this(address, null); } /** * Opens the device at the specified address * * @param address Some form of InstrumentAddress (eg GPIBAddress, USBAddress etc) * @param prefDriver Preferred driver to try first * * @throws IOException Upon communications error */ public VISADevice(Address address, Class<? extends Driver> prefDriver) throws IOException { if (address == null) { this.connection = null; this.address = null; return; } this.connection = VISA.openInstrument(address, prefDriver); this.address = address; // Keep a weak reference to this opened.add(new WeakReference<>(this)); } public Connection getConnection() { return connection; } public synchronized <T extends Connection> void config(Class<T> type, ConfigRun<T> run) throws IOException, DeviceException { if (type.isAssignableFrom(getConnection().getClass())) { run.config((T) getConnection()); } } public synchronized <T extends Connection> void config(KClass<T> type, ConfigRun<T> run) throws IOException, DeviceException { config(JvmClassMappingKt.getJavaClass(type), run); } public synchronized void configGPIB(ConfigRun<GPIBConnection> run) throws IOException, DeviceException { config(GPIBConnection.class, run); } public synchronized void configSerial(ConfigRun<SerialConnection> run) throws IOException, DeviceException { config(SerialConnection.class, run); } public synchronized void configTCPIP(ConfigRun<TCPIPConnection> run) throws IOException, DeviceException { config(TCPIPConnection.class, run); } public synchronized void configLXI(ConfigRun<LXIConnection> run) throws IOException, DeviceException { config(LXIConnection.class, run); } public synchronized void configUSB(ConfigRun<USBConnection> run) throws IOException, DeviceException { config(USBConnection.class, run); } public synchronized void clearBuffers() throws IOException { try { connection.clear(); } catch (VISAException e) { throw new IOException(e.getMessage()); } } /** * Continuously reads from the read buffer until there's nothing left to read. (Clears the read buffer for the more * stubborn of instruments). Do not use on GPIB instruments programmed to respond to TALK requests (it will never * terminate). * * @throws IOException Upon communications error */ public synchronized void manuallyClearReadBuffer() throws IOException { try { connection.setTimeout(250); } catch (VISAException e) { throw new IOException(e.getMessage()); } while (true) { try { connection.readBytes(1); } catch (VISAException e) { break; } Util.sleep(Math.max(25, ioInterval)); } try { connection.setTimeout(timeout); } catch (VISAException e) { throw new IOException(e.getMessage()); } } /** * Sets whether this VISADevice object should wait a minimum amount of time between successive read/write * operations. * * @param interval The minimum interval, in milliseconds (0 will disable this feature) * @param read Whether this wait should apply to read operations * @param write Whether this wait should apply to write operations */ public synchronized void setIOLimit(int interval, boolean read, boolean write) { if (interval < 0) { throw new IllegalArgumentException("Minimum I/O interval cannot be negative."); } if (interval > 0 && scheduler == null) { scheduler = Executors.newSingleThreadScheduledExecutor(); } else if (interval == 0 && scheduler != null) { scheduler.shutdown(); scheduler = null; } ioInterval = interval; readWait = read; writeWait = write; } /** * What default number of bytes should we expect to get when reading from the device? * * @param bytes The number of bytes, yikes. */ public synchronized void setReadBufferSize(int bytes) { readBufferSize = bytes; } public synchronized void addAutoRemove(String... phrases) { toRemove.addAll(List.of(phrases)); } public synchronized void setRetryCount(int count) { retryCount = count; } public synchronized void setTimeout(int msec) throws IOException { this.timeout = msec; getConnection().setTimeout(msec); } /** * Returns the address used to connect to the device * * @return Address object */ public Address getAddress() { return address; } /** * Set a termination character to tell the device when we've stopped talking to it * * @param term The character to use (eg "\n" or "\r") */ public synchronized void setWriteTerminator(String term) { terminator = term; } public synchronized void setReadTerminator(String term) throws VISAException { getConnection().setReadTerminator(term); } public synchronized void setReadTerminator(long term) throws VISAException { getConnection().setReadTerminator(term); } /** * Write the given string to the device * * @param command The string to write * @param args Any formatting arguments * * @throws IOException Upon communications error */ public synchronized void write(String command, Object... args) throws IOException { String commandParsed = String.format(command, args).concat(terminator); boolean wait = writeWait && ioInterval > 0; if (wait) { ioPermits.acquireUninterruptibly(); } lastCommand = commandParsed; try { connection.write(commandParsed); } catch (VISAException e) { throw new IOException(e.getMessage()); } finally { if (wait) { scheduler.schedule(ioWait, ioInterval, TimeUnit.MILLISECONDS); } } } public synchronized void writeBytes(byte[] bytes) throws IOException { try { connection.writeBytes(bytes); } catch (VISAException e) { throw new IOException(e.getMessage()); } } /** * Read a string from the device * * @return The string returned by the device * * @throws IOException Upon communications error */ public synchronized String read() throws IOException { return read(retryCount); } /** * Read a string from the device * * @param attempts Number of failed attempts to read before throwing an exception * * @return The string returned by the device * * @throws IOException Upon communications error */ public synchronized String read(int attempts) throws IOException { int count = 0; final boolean wait = readWait && ioInterval > 0; // Try n times while (true) { if (wait) { ioPermits.acquireUninterruptibly(); } try { lastRead = connection.read(readBufferSize); for (String remove : toRemove) { lastRead = lastRead.replace(remove, ""); } break; } catch (VISAException e) { count++; if (count >= attempts) { throw e; } System.out.printf("Retrying read from \"%s\", reason: %s%n", address.toString(), e.getMessage()); } finally { if (wait) { scheduler.schedule(ioWait, ioInterval, TimeUnit.MILLISECONDS); } } } return lastRead; } public synchronized byte[] readBytes(int numBytes) throws IOException { try { return connection.readBytes(numBytes); } catch (VISAException e) { throw new IOException(e.getMessage()); } } /** * Read a double from the device * * @return The number returned by the device * * @throws IOException Upon communications error */ public synchronized double readDouble() throws IOException { return Double.parseDouble(read().replace("\n", "").replace("\r", "").trim()); } /** * Read an integer from the device * * @return Integer read from the device * * @throws IOException Upon communications error */ public synchronized int readInt() throws IOException { return Integer.parseInt(read().replace("\n", "").replace("\r", "").trim()); } /** * Write the given string, then immediately read the response as a double * * @param command String to write * @param args Formatting arguments * * @return Numerical response * * @throws IOException Upon communications error */ public synchronized double queryDouble(String command, Object... args) throws IOException { write(command, args); return readDouble(); } /** * Write the given string, then immediately read the response as an integer * * @param command String to write * @param args Formatting arguments * * @return Numerical response * * @throws IOException Upon communications error */ public synchronized int queryInt(String command, Object... args) throws IOException { write(command, args); return readInt(); } /** * Write the given string, then immediately read the response * * @param command String to write * @param args Formatting arguments * * @return String response * * @throws IOException Upon communications error */ public synchronized String query(String command, Object... args) throws IOException { write(command, args); return read(); } /** * Sends the standard identifications query to the device (*IDN?) * * @return The resposne of the device * * @throws IOException Upon communications error */ public synchronized String getIDN() throws IOException { return query(C_IDN); } @Override public String getName() { return "VISA Device"; } /** * Close the connection to the device * * @throws IOException Upon communications error */ public synchronized void close() throws IOException { try { connection.close(); } catch (VISAException e) { throw new IOException(e.getMessage()); } } /** * Method to check limits of instruments values, throws DeviceException exceeded. * * @param valueName parameter to be checked (e.g. Voltage range) * @param value value to set * @param lower lower limit * @param upper upper limit * @param unit unit of value */ protected void checkLimit(String valueName, Number value, Number lower, Number upper, String unit) throws DeviceException { if (!Util.isBetween(value, lower, upper)) { throw new DeviceException("%s = %e %s is out of range (%e to %e)", valueName, value, unit, lower, upper); } } protected void checkLimit(String valueName, Number value, Number lower, Number upper) throws DeviceException { if (!Util.isBetween(value, lower, upper)) { throw new DeviceException("%s = %e is out of range (%e to %e)", valueName, value, lower, upper); } } public interface ConfigRun<T extends Connection> { void config(T connection) throws DeviceException, IOException; } }
OE-FET/JISA
src/jisa/visa/VISADevice.java
249,697
/* * Copyright 2014, Anthony Urso, Hridesh Rajan, Robert Dyer, * and Iowa State University of Science and Technology * * 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 boa.types; import boa.compiler.ast.types.AbstractType; import boa.compiler.SymbolTable; /** * A {@link BoaType} representing the wildcard or any type. * * @author anthonyu * @author rdyer */ public class BoaAny extends BoaType { /** {@inheritDoc} */ @Override public boolean assigns(final BoaType that) { // anything can be assigned to a variable of type 'any' return true; } /** {@inheritDoc} */ @Override public boolean accepts(final BoaType that) { // anything can be be used as an 'any' param return true; } /** {@inheritDoc} */ @Override public AbstractType toAST(final SymbolTable env) { throw new RuntimeException("toAST() not supported on BoaAny"); } /** {@inheritDoc} */ @Override public String toJavaType() { return "void"; } /** {@inheritDoc} */ @Override public String toString() { return "any"; } }
boalang/compiler
src/java/boa/types/BoaAny.java
249,698
/** * Task class with black-box method * computeIntensive(). */ public abstract class Task extends Thread { @SuppressWarnings("unused") private volatile Long result; Task(String name) { super(name); } public void doWork(int i) { computeIntensive(i); } public void ioWait() { try { Thread.sleep(500); } catch (InterruptedException ie) { // do nothing } } public Long computeIntensive(int i) { if (i < 2) { return Long.valueOf(1L); } else { Long l1 = computeIntensive(i - 1); Long l2 = computeIntensive(i - 2); if (l1.compareTo(l2) == 0) { result = l1; } else if (l1.compareTo(l2) > 0) { result = l2; } return Long.valueOf(l1.longValue() + l2.longValue()); } } }
jerboaa/thermostat-byteman-demo
Task.java
249,700
/* * --- Operating Systems Homework 2 --- * Copyright (c) 2014, Mark Plagge -- plaggm * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import java.util.HashMap; /** * * @author Mark */ public abstract class AbstractProcess { long pid; boolean isInteractive; long cpuTimeNeeded; //Initial values (set via constructor) long vWait; long ioWait; /** burstValue is the total CPU time needed. **/ long burstValue; /** burstNums is the number of CPU burst times left **/ long burstNums; long priority; long userWait; long startTime; //Calculated Values (xxxTime is time spent in a state) ProcessState pState; private static final String pidStr = "Process ID: "; private static final String sttStr = "|| Start Stime: "; private static final String twtStr = "|| Total Wait Time: "; private static final String tioStr = "|| Total IO Waiting Time: "; HashMap<ProcessState, Integer> timings; public AbstractProcess(int pid, boolean isInteractive,int burstNums, int priority ) { this.pid = pid; this.isInteractive = isInteractive; this.burstNums = burstNums; this.priority = priority; this.pState = ProcessState.idle; //set up timing table: timings = new HashMap<>(6); int it = 0; timings.put(ProcessState.idle, it); timings.put(ProcessState.active, it); timings.put(ProcessState.contextSwitch, it); timings.put(ProcessState.terminated, it); timings.put(ProcessState.userWait, it); timings.put(ProcessState.IOWait, it); } public boolean isInteractive() { return this.isInteractive; } //Timing getter: public abstract long getTiming(String t); public abstract long getTiming(ProcessState stq); //return timings (current process times): public long getActiveTime() { return getTiming(ProcessState.active); } public long getIoWaitTime() { return getTiming(ProcessState.IOWait); } public long getUserWaitTime() { return getTiming(ProcessState.userWait); } public long getCtxSwitchTime() { return getTiming(ProcessState.contextSwitch); } public long getIdleTime() { return getTiming(ProcessState.idle); } public long getRemainingBursts() { return this.burstValue; } public long getBurstValue() { return burstValue; } //Process stat methods public long getStartTime() { return startTime; } public long getPriority() { return priority; } public long getPid() { return pid; } @Override public String toString() { return pidStr + this.getPid() + sttStr + this.getStartTime() + twtStr + getTotalWaitTime()+ tioStr + getIoWaitTime(); } /** Setters Below * @param state **/ public void setState(ProcessState state){ this.pState = state; } //process remaining time(calculated values) public abstract long getTotalWaitTime(); abstract long remIoWait(); abstract long remUserWait(); //Abstract (need to implement) methods: abstract public void tick(); abstract public boolean isDone(); }
nmcglo/procSimulator
src/AbstractProcess.java
249,701
package roj.io; import org.jetbrains.annotations.Nullable; import roj.collect.SimpleList; import roj.compiler.plugins.annotations.Attach; import roj.concurrent.FastThreadLocal; import roj.config.data.CLong; import roj.crypt.Base64; import roj.reflect.ReflectionUtils; import roj.text.CharList; import roj.text.TextReader; import roj.text.TextUtil; import roj.text.UTF8MB4; import roj.util.ByteList; import roj.util.Helpers; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Predicate; /** * @author Roj234 * @since 2021/5/29 22:1 */ public final class IOUtil { public static final FastThreadLocal<IOUtil> SharedCoder = FastThreadLocal.withInitial(IOUtil::new); // region ThreadLocal part public final CharList charBuf = new CharList(1024); public final ByteList byteBuf = new ByteList(); {byteBuf.ensureCapacity(1024);} private final ByteList.Slice shell = new ByteList.Slice(); public final ByteList.Slice shellB = new ByteList.Slice(); public final StringBuilder numberHelper = new StringBuilder(32); public byte[] encode(CharSequence str) { ByteList b = byteBuf; b.clear(); return b.putUTFData(str).toByteArray(); } public String decode(byte[] b) { CharList c = charBuf; c.clear(); UTF8MB4.CODER.decodeFixedIn(shell.setR(b,0,b.length), b.length, c); return c.toString(); } public String encodeHex(byte[] b) { return shell.setR(b,0,b.length).hex(); } public String encodeBase64(byte[] b) { return shell.setR(b,0,b.length).base64(); } public byte[] decodeHex(CharSequence c) { ByteList b = byteBuf; b.clear(); return TextUtil.hex2bytes(c, b).toByteArray(); } public ByteList decodeBase64(CharSequence c) { return decodeBase64(c, Base64.B64_CHAR_REV); } public ByteList decodeBase64(CharSequence c, byte[] chars) { ByteList b = byteBuf; b.clear(); Base64.decode(c, 0, c.length(), b, chars); return b; } public ByteList wrap(byte[] b) { return shell.setR(b,0,b.length); } public ByteList wrap(byte[] b, int off, int len) { return shell.setR(b,off,len); } // endregion public static ByteList getSharedByteBuf() { ByteList o = SharedCoder.get().byteBuf; o.clear(); return o; } public static CharList getSharedCharBuf() { CharList o = SharedCoder.get().charBuf; o.clear(); return o; } public static byte[] getResource(String path) throws IOException { return getResource(ReflectionUtils.getCallerClass(2), path); } public static byte[] getResource(Class<?> caller, String path) throws IOException { var in = caller.getClassLoader().getResourceAsStream(path); if (in == null) throw new FileNotFoundException(path+" is not in jar "+caller.getName()); return new ByteList(Math.max(in.available(), 4096)).readStreamFully(in).toByteArrayAndFree(); } public static String getTextResource(String path) throws IOException { return getTextResource(ReflectionUtils.getCallerClass(2), path); } public static String getTextResource(Class<?> caller, String path) throws IOException { var in = caller.getClassLoader().getResourceAsStream(path); if (in == null) throw new FileNotFoundException(path+" is not in jar "+caller.getName()); try (var r = TextReader.from(in, StandardCharsets.UTF_8)) { return new CharList(Math.max(in.available()/3, 4096)).readFully(r).toStringAndFree(); } } public static byte[] read(File file) throws IOException { long len = file.length(); if (len > Integer.MAX_VALUE) throw new IOException("file > 2GB"); byte[] data = new byte[(int) len]; try (FileInputStream in = new FileInputStream(file)) { readFully(in, data); return data; } } public static byte[] read(InputStream in) throws IOException { return getSharedByteBuf().readStreamFully(in).toByteArray(); } public static String readUTF(File f) throws IOException { try (var r = TextReader.from(f, StandardCharsets.UTF_8)) { return f.length() > 1048576L ? read1(r) : read(r); } } public static String readUTF(InputStream in) throws IOException { try (var r = TextReader.from(in, StandardCharsets.UTF_8)) { return in.available() > 1048576L ? read1(r) : read(r); } } public static String readString(File f) throws IOException { try (var r = TextReader.auto(f)) { return f.length() > 1048576L ? read1(r) : read(r); } } public static String readString(InputStream in) throws IOException { try (var r = TextReader.auto(in)) { return in.available() > 1048576L ? read1(r) : read(r); } } public static String read(Reader r) throws IOException { return getSharedCharBuf().readFully(r).toString(); } private static String read1(Reader r) throws IOException { return new CharList(1048576).readFully(r).toStringAndFree(); } @Attach public static void readFully(InputStream in, byte[] b) throws IOException {readFully(in, b, 0, b.length);} @Attach public static void readFully(InputStream in, byte[] b, int off, int len) throws IOException { while (len > 0) { int r = in.read(b, off, len); if (r < 0) throw new EOFException(); len -= r; off += r; } } @Attach("skipAlt") public static long skip(InputStream in, long count) throws IOException { for(;;) { long i = in.skip(count); if (i == 0) break; count -= i; if (count == 0) break; } return count; } @Attach public static void skipFully(InputStream in, long count) throws IOException { if (skip(in, count) < count) throw new EOFException(); } public static void copyFile(File source, File target) throws IOException { Files.copy(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING); } public static void copyStream(InputStream in, OutputStream out) throws IOException { ByteList b = getSharedByteBuf(); byte[] data = b.list; while (true) { int len = in.read(data); if (len < 0) break; out.write(data, 0, len); } } @Attach("listAll") public static List<File> findAllFiles(File file) { return findAllFiles(file, SimpleList.hugeCapacity(0), Helpers.alwaysTrue()); } @Attach("listAll") public static List<File> findAllFiles(File file, Predicate<File> predicate) { return findAllFiles(file, SimpleList.hugeCapacity(0), predicate); } @Attach("listAll") public static List<File> findAllFiles(File file, List<File> files, Predicate<File> predicate) { try { Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { File t = file.toFile(); if (predicate.test(t)) files.add(t); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { e.printStackTrace(); } return files; } @Attach public static boolean deletePath(File file) { try { Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); if (exc != null) throw exc; return FileVisitResult.CONTINUE; } }); } catch (IOException e) { return false; } return true; } public static void allocSparseFile(File file, long length) throws IOException { // noinspection all if (file.length() != length) { // noinspection all if (!file.isFile() || (file.length() < length && file.delete())) { FileChannel fc = FileChannel.open(file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW, StandardOpenOption.SPARSE) .position(length-1); fc.write(ByteBuffer.wrap(new byte[1])); fc.close(); } else if (length < Integer.MAX_VALUE) { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.setLength(length); // alloc raf.close(); } } else if (length == 0) file.createNewFile(); } public static boolean checkTotalWritePermission(File file) { try (RandomAccessFile f = new RandomAccessFile(file, "rw")) { long l = f.length(); f.seek(l); f.writeByte(1); f.setLength(l); } catch (IOException e) { return false; } return true; } public static int removeEmptyPaths(Collection<String> files) { boolean oneRemoved = true; int i = 0; while (oneRemoved) { oneRemoved = false; for (String path : files) { File dir = new File(path); while ((dir = dir.getParentFile()) != null) { if (!dir.delete()) break; oneRemoved = true; i++; } } } return i; } public static long transferFileSelf(FileChannel cf, long from, long to, long len) throws IOException { if (from == to || len == 0) return len; long pos = cf.position(); try { if (from > to ? to + len <= from : from + len <= to) { // 区间不交叉 return cf.transferTo(from, len, cf.position(to)); } if (len <= 1048576) { ByteBuffer direct = ByteBuffer.allocateDirect((int) len); try { direct.position(0).limit((int) len); cf.read(direct, from); direct.position(0); return cf.position(to).write(direct); } finally { NIOUtil.clean(direct); } } else { File tmpPath = new File(System.getProperty("java.io.tmpdir")); File tmpFile; do { tmpFile = new File(tmpPath, "FUT~"+(float)Math.random()+".tmp"); } while (tmpFile.exists()); try (FileChannel ct = FileChannel.open(tmpFile.toPath(), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.DELETE_ON_CLOSE)) { cf.transferTo(from, len, ct.position(0)); return ct.transferTo(0, len, cf.position(to)); } } } finally { // 还原位置 cf.position(pos+len); } } public static CharList mavenPath(CharSequence name) { int i = TextUtil.gIndexOf(name, ':'); CharList cl = new CharList().append(name).replace('.', '/', 0, i); List<String> parts = TextUtil.split(new ArrayList<>(4), cl, ':'); String ext = "jar"; final String s = parts.get(parts.size() - 1); int extPos = s.lastIndexOf('@'); if (extPos != -1) { ext = s.substring(extPos + 1); parts.set(parts.size() - 1, s.substring(0, extPos)); } cl.clear(); cl.append(parts.get(0)).append('/') // d .append(parts.get(1)).append('/') // n .append(parts.get(2)).append('/') // v .append(parts.get(1)).append('-').append(parts.get(2)); // n-v if (parts.size() > 3) { cl.append('-').append(parts.get(3)); } return cl.append('.').append(ext); } public static String extensionName(String path) { path = path.substring(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'))+1); int i = path.lastIndexOf('.'); return i < 0 ? "" : path.substring(i+1); } public static String fileName(String pat) { pat = pat.substring(Math.max(pat.lastIndexOf('/'), pat.lastIndexOf('\\'))+1); int i = pat.lastIndexOf('.'); return i < 0 ? pat : pat.substring(0, i); } public static String pathToName(String text) { int i = text.lastIndexOf('/'); i = Math.max(i, text.lastIndexOf('\\')); return text.substring(i+1); } /** * no URLDecode * no \ TO / * @param path * @return */ public static String safePath(String path) { CharList sb = getSharedCharBuf(); int altStream = path.lastIndexOf(':'); if (altStream > 1) path = path.substring(0, altStream); return sb.append(path).trim() .replaceInReplaceResult("../", "/") .replaceInReplaceResult("//", "/") .substring(sb.length() > 0 && sb.charAt(0) == '/' ? 1 : 0, sb.length()); } public static long movePath(File from, File to, boolean move) throws IOException { if (!from.isDirectory()) { if (move) return from.renameTo(to) ? 1 : 0; copyFile(from, to); return 1; } if (from.equals(to)) return 1; CLong state = new CLong(); int len = from.getAbsolutePath().length()+1; to.mkdirs(); Files.walkFileTree(from.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { String relpath = dir.toString(); if (relpath.length() > len) { relpath = relpath.substring(len); if (!new File(to, relpath).mkdir()) { state.value |= Long.MIN_VALUE; return FileVisitResult.TERMINATE; } else { state.value += 1L << 20; } } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { File from = file.toFile(); File target = new File(to, file.toString().substring(len)); if (move) { if (from.renameTo(target)) { state.value++; } else { state.value |= Long.MIN_VALUE; return FileVisitResult.TERMINATE; } } else { copyFile(from, target); state.value++; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { if (move) dir.toFile().delete(); return FileVisitResult.CONTINUE; } }); return state.value; } @Attach public static void closeSilently(@Nullable AutoCloseable c) { if (c != null) try { c.close(); } catch (Throwable e) { e.printStackTrace(); } } public static void ioWait(AutoCloseable closeable, Object waiter) throws IOException { synchronized (waiter) { try { waiter.wait(); } catch (InterruptedException e) { ClosedByInterruptException ex2 = new ClosedByInterruptException(); try { closeable.close(); } catch (Throwable ex) { ex2.addSuppressed(ex); } throw ex2; } } } }
roj234/rojlib
java/roj/io/IOUtil.java
249,702
package View; import java.awt.EventQueue; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.swing.JFrame; import javax.swing.JComboBox; import javax.swing.JSlider; import javax.swing.JTextField; import Controller.Controller; import Model.DefuzzyficationMethod; import Model.LinguisticAttributes; import Model.Model; import Model.CrispValues.ConstantCrispValuesProvider; import Model.CrispValues.CrispValue; import Model.CrispValues.CrispValuesDatabase; import Model.CrispValues.ICrispValuesProvider; import Model.FuzzySets.FoodQualityLinguisticValues; import Model.LineralFunctions.Diagram; import View.Graphs.Graph; import sun.swing.JLightweightFrame; import javax.swing.JLabel; import javax.swing.SwingConstants; import java.awt.Font; import java.awt.event.MouseAdapter; import java.awt.event.MouseListener; import javax.swing.JButton; import javax.swing.JTable; import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.JPanel; import javax.swing.border.TitledBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import com.sun.glass.events.MouseEvent; import javax.swing.JRadioButton; public class MainWindow implements IView{ private JFrame frame; private JTextField generationValue1; private JTextField generationValue2; private JLabel generationLabel1; private JSlider generationSlider2; private JLabel generationLabel2; private JSlider generationSlider1; private ViewStateInfo viewStateInfo; private JLabel lblWartoWejciowa; private JTextField charmValue; private JTextField ServiceQualityValue; private JTextField FoodQualityValue; private JTable fuzzySetsValuesTable; private JPanel panel; private JTable rulesTable; private JPanel panel_2; private JPanel panel_3; private JLabel lblDefuzyfikator; private JTextField tipValueField; private Map<LinguisticAttributes, JSlider> crispValuesSliders = new HashMap<>(); private Map<LinguisticAttributes, JTextField> crispValuesTextFields = new HashMap<>(); private Map<DefuzzyficationMethod, JRadioButton> defuzzyficationMethodsButtons = new HashMap<>(); private Controller controller; private JPanel graphPanel; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Model model = new Model(); model.setCrispInputs(new CrispValue(0.44f), new CrispValue(0.44f), new CrispValue(0.11f)); ViewStateInfo stateInfo = new ViewStateInfo(model); stateInfo.setInputFuzzySets(model.getInputFuzzySets()); Controller controller = new Controller(model); MainWindow window = new MainWindow(stateInfo, controller); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public MainWindow(ViewStateInfo viewStateInfo, Controller controller) { initialize(viewStateInfo, controller); } /** * Initialize the contents of the frame. */ private void initialize(ViewStateInfo viewStateInfo, Controller controller) { this.viewStateInfo = viewStateInfo; this.controller = controller; frame = new JFrame(); frame.setBounds(10, 10, 1000, 740); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JComboBox generatorComboBox = new JComboBox(); generatorComboBox.setBounds(12, 12, 200, 24); frame.getContentPane().add(generatorComboBox); generatorComboBox.addItemListener((l)->{ controller.generatorComboBoxChanged(generatorComboBox.getSelectedIndex()); }); generationValue1 = new JTextField(); generationValue1.setBounds(169, 59, 43, 19); frame.getContentPane().add(generationValue1); generationValue1.setColumns(10); generationLabel1 = new JLabel("New label"); generationLabel1.setBounds(12, 45, 200, 15); frame.getContentPane().add(generationLabel1); generationSlider2 = new JSlider(); generationSlider2.setBounds(12, 107, 150, 16); frame.getContentPane().add(generationSlider2); generationValue2 = new JTextField(); generationValue2.setColumns(10); generationValue2.setBounds(169, 104, 43, 19); frame.getContentPane().add(generationValue2); generationLabel2 = new JLabel("New label"); generationLabel2.setBounds(12, 90, 206, 15); frame.getContentPane().add(generationLabel2); generationSlider1 = new JSlider(); generationSlider1.setBounds(12, 62, 150, 16); frame.getContentPane().add(generationSlider1); generationSlider1.setMinimum(0); generationSlider1.setMaximum(100); generationSlider1.setValue(50); generationSlider1.addChangeListener((l)-> { JSlider source = (JSlider)l.getSource(); if( !source.getValueIsAdjusting()){ int val = (int)source.getValue(); controller.generationSlider1Change(val); } }); generationSlider2.addChangeListener((l)-> { JSlider source = (JSlider)l.getSource(); if( !source.getValueIsAdjusting()){ int val = (int)source.getValue(); controller.generationSlider2Change(val); } }); controller.setView(this); // TODO UGLY HACK controller.setStateInfo(viewStateInfo); List<DistributionSettingProperties> distributionPropeties = viewStateInfo.getDistributionSettingProperties(); generatorComboBox.addItem(distributionPropeties.get(0).getTitle()); generatorComboBox.addItem(distributionPropeties.get(1).getTitle()); generationValue1.setEditable(false); generationValue2.setEditable(false); lblWartoWejciowa = new JLabel("Wartość wejściowa"); lblWartoWejciowa.setFont(new Font("Dialog", Font.BOLD, 16)); lblWartoWejciowa.setHorizontalAlignment(SwingConstants.CENTER); lblWartoWejciowa.setHorizontalTextPosition(SwingConstants.CENTER); lblWartoWejciowa.setBounds(12, 177, 189, 36); frame.getContentPane().add(lblWartoWejciowa); JButton generateButton = new JButton("Generuj losowo!"); generateButton.setBounds(12, 135, 200, 36); frame.getContentPane().add(generateButton); generateButton.addActionListener((l)->{ controller.generateButtonClicked(generationSlider1.getValue(), generationSlider2.getValue()); }); //------------------- TERA wartości crisp ServiceQualityValue = new JTextField(); ServiceQualityValue.setColumns(10); ServiceQualityValue.setBounds(169, 272, 43, 19); ServiceQualityValue.setEditable(false); frame.getContentPane().add(ServiceQualityValue); FoodQualityValue = new JTextField(); FoodQualityValue.setColumns(10); FoodQualityValue.setBounds(169, 317, 43, 19); FoodQualityValue.setEditable(false); frame.getContentPane().add(FoodQualityValue); charmValue = new JTextField(); charmValue.setColumns(10); charmValue.setBounds(169, 227, 43, 19); charmValue.setEditable(false); frame.getContentPane().add(charmValue); crispValuesTextFields.put(LinguisticAttributes.ServiceQuality, ServiceQualityValue); crispValuesTextFields.put(LinguisticAttributes.FoodQuality, FoodQualityValue); crispValuesTextFields.put(LinguisticAttributes.Charm, charmValue); JSlider charmSlider = new JSlider(); charmSlider.setBounds(12, 230, 150, 16); frame.getContentPane().add(charmSlider); crispValuesSliders.put(LinguisticAttributes.Charm, charmSlider); JLabel lblUrokKelnerki = new JLabel("Urok kelnerki"); lblUrokKelnerki.setBounds(12, 213, 206, 15); frame.getContentPane().add(lblUrokKelnerki); JSlider serviceQualitySlider = new JSlider(); serviceQualitySlider.setBounds(12, 275, 150, 16); frame.getContentPane().add(serviceQualitySlider); crispValuesSliders.put(LinguisticAttributes.ServiceQuality, serviceQualitySlider); JLabel ServiceQualityLabel = new JLabel("Jakość obsługi"); ServiceQualityLabel.setBounds(12, 258, 206, 15); frame.getContentPane().add(ServiceQualityLabel); JSlider foodQualitySlider = new JSlider(); foodQualitySlider.setBounds(12, 320, 150, 16); frame.getContentPane().add(foodQualitySlider); crispValuesSliders.put(LinguisticAttributes.FoodQuality, foodQualitySlider); for( Entry<LinguisticAttributes, JSlider> pair : crispValuesSliders.entrySet()){ pair.getValue().addChangeListener((l)->{ controller.attributeValueSliderChanged(pair.getKey(), pair.getValue().getValue()); }); } JLabel FoodQualityLabel = new JLabel("Jakość jedzenia"); FoodQualityLabel.setBounds(12, 303, 206, 15); frame.getContentPane().add(FoodQualityLabel); panel_2 = new JPanel(); panel_2.setBorder(new TitledBorder(null, "Wartości atrybutów", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel_2.setBounds(5, 333, 310, 241); frame.getContentPane().add(panel_2); panel_2.setLayout(null); panel = new JPanel(); panel.setBounds(7, 17, 300, 217); panel_2.add(panel); panel.setLayout(new BorderLayout()); fuzzySetsValuesTable = new JTable(); panel.add(fuzzySetsValuesTable, BorderLayout.CENTER); panel.add(fuzzySetsValuesTable.getTableHeader(), BorderLayout.NORTH); fuzzySetsValuesTable.setModel( viewStateInfo.getFuzzySetsValuesTableModel()); fuzzySetsValuesTable.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(java.awt.event.MouseEvent e) { controller.fuzzySetsValuesTableRowIsSelected(fuzzySetsValuesTable.getSelectedRow()); } }); panel_3 = new JPanel(); panel_3.setBorder(new TitledBorder(null, "Wyniki działania reguł", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel_3.setBounds(15, 586, 803, 100); frame.getContentPane().add(panel_3); panel_3.setLayout(null); JPanel panel_1 = new JPanel(); panel_1.setBounds(5, 17, 793, 141); panel_3.add(panel_1); panel_1.setLayout(new BorderLayout()); rulesTable = new JTable(); panel_1.add(rulesTable, BorderLayout.CENTER); rulesTable.setModel(viewStateInfo.getRulesTableModel()); rulesTable.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(java.awt.event.MouseEvent e) { controller.rulesTableRowIsSelected(rulesTable.getSelectedRow()); } }); lblDefuzyfikator = new JLabel("Defuzyfikator"); lblDefuzyfikator.setFont(new Font("Dialog", Font.BOLD, 18)); lblDefuzyfikator.setBounds(343, 437, 150, 55); frame.getContentPane().add(lblDefuzyfikator); JRadioButton method1Rdbt = new JRadioButton("Metoda pierwszego maksimum"); method1Rdbt.setBounds(333, 490, 251, 23); frame.getContentPane().add(method1Rdbt); JRadioButton method2Rdbt = new JRadioButton("Metoda ostatniego maksimum"); method2Rdbt.setBounds(333, 515, 251, 23); frame.getContentPane().add(method2Rdbt); JRadioButton method3Rdbt = new JRadioButton("Metoda środka maksimum"); method3Rdbt.setBounds(333, 540, 251, 23); frame.getContentPane().add(method3Rdbt); JRadioButton method4Rdbt = new JRadioButton("Metoda środka ciężkości"); method4Rdbt.setBounds(333, 565, 251, 23); frame.getContentPane().add(method4Rdbt); defuzzyficationMethodsButtons.put(DefuzzyficationMethod.FirstMaximum, method1Rdbt); defuzzyficationMethodsButtons.put(DefuzzyficationMethod.LastMaximum, method2Rdbt); defuzzyficationMethodsButtons.put(DefuzzyficationMethod.CenterOfMaximum, method3Rdbt); defuzzyficationMethodsButtons.put(DefuzzyficationMethod.COG, method4Rdbt); for( Entry<DefuzzyficationMethod, JRadioButton> pair : defuzzyficationMethodsButtons.entrySet()){ pair.getValue().addActionListener((l)->{ controller.defuzzyficationMethodButtonWasClicked(pair.getKey()); }); } JLabel lblWartoWyjciowa = new JLabel("Wartość wyjściowa"); lblWartoWyjciowa.setFont(new Font("Dialog", Font.BOLD, 19)); lblWartoWyjciowa.setBounds(598, 437, 229, 69); frame.getContentPane().add(lblWartoWyjciowa); JLabel lblNapiwekWynosi = new JLabel("Napiwek wynosi"); lblNapiwekWynosi.setBounds(598, 536, 115, 15); frame.getContentPane().add(lblNapiwekWynosi); tipValueField = new JTextField(); tipValueField.setEditable(false); tipValueField.setFont(new Font("Dialog", Font.BOLD, 19)); tipValueField.setText("17%"); tipValueField.setBounds(728, 514, 60, 60); frame.getContentPane().add(tipValueField); tipValueField.setColumns(10); graphPanel = new JPanel(); graphPanel.setBounds(310, 0, 728, 442); frame.getContentPane().add(graphPanel); try { graphPanel.add( Graph.getNiceGraph()); } catch (Exception e1) { e1.printStackTrace(); } controller.setShouldUpdateView(true); update(); } @Override public void update(){ DistributionSettingProperties activeDistribution = viewStateInfo.getActiveDistribution(); if( viewStateInfo.getActiveDistribution().isFirstSliderActive()){ generationSlider1.setEnabled(true); generationSlider1.setValue( activeDistribution.getValue1()); generationValue1.setText( new Integer(activeDistribution.getValue1()).toString()); generationLabel1.setText(activeDistribution.getValue1Title()); } else { generationSlider1.setEnabled(false); generationLabel1.setText("----"); } if( viewStateInfo.getActiveDistribution().isSecondSliderActive()){ generationSlider2.setEnabled(true); generationSlider2.setValue( activeDistribution.getValue2()); generationValue2.setText( new Integer(activeDistribution.getValue2()).toString()); generationLabel2.setText(activeDistribution.getValue2Title()); } else { generationSlider2.setEnabled(false); generationLabel2.setText("----"); } for( Entry<LinguisticAttributes, JTextField> pair : crispValuesTextFields.entrySet()){ pair.getValue().setText( new Integer( viewStateInfo.getLinguisticAttributeCrispValue( pair.getKey())).toString()+"%"); } for( Entry<LinguisticAttributes, JSlider> pair : crispValuesSliders.entrySet()){ pair.getValue().setValue( new Integer( viewStateInfo.getLinguisticAttributeCrispValue(pair.getKey()))); } for( Entry<DefuzzyficationMethod, JRadioButton> pair : defuzzyficationMethodsButtons.entrySet()){ if( viewStateInfo.getCurrentDefuzzyficationMethod() == pair.getKey()){ pair.getValue().setSelected(true); } else { pair.getValue().setSelected(false); } } tipValueField.setText(viewStateInfo.getCurrentTip()+"%"); viewStateInfo.getFuzzySetsValuesTableModel().fireTableDataChanged(); viewStateInfo.getRulesTableModel().fireTableDataChanged(); if( viewStateInfo.getCurrentDiagram() != null ){ graphPanel.removeAll(); Graph newGraph = new Graph("TIT", "OY", "OX", viewStateInfo.getCurrentDiagram()); graphPanel.add( newGraph); newGraph.setVisible(true); graphPanel.repaint(); graphPanel.revalidate(); } } }
defacto2k15/PSZT16L
src/View/MainWindow.java
249,705
import java.util.ArrayList; import java.util.Collections; public class Library { ArrayList<LibraryBook> bookList; public Library () { bookList = new ArrayList<LibraryBook> (); } /** * adds the given book to the library * @param book */ public void addBook (LibraryBook book) { bookList.add(book); } /** * prints all books in the library */ public void printLibrary () { System.out.println ("\nListing of books in the library\n"); for (LibraryBook book: bookList) System.out.println (book); System.out.println ("End of book listing\n"); } /** * locates a book in the library * @param book book being search in the library * @return book object if book is found * null otherwise */ public LibraryBook findBook (LibraryBook book) { int index = Collections.binarySearch(bookList, book); if (index >= 0) return bookList.get(index); else return null; } /** * sort books in the library by call number */ public void sortLibrary () { Collections.sort(bookList); } /** * performs processing for checking a book out of the library * @param patron person checking out book * @param dueDate date book is due to be returned * @param callNum call number of book */ public void checkout (String patron, String dueDate, String callNum) { LibraryBook searchItem = new CirculatingBook ("", "", "", callNum); LibraryBook book = findBook(searchItem); if (book == null) System.out.println ("Book " + callNum + " not found -- checkout impossible\n"); else book.checkout (patron, dueDate); } /** * processes checked-out book that is being returned * @param callNum call number of book being returned */ public void returned (String callNum) { LibraryBook searchItem = new CirculatingBook ("", "", "", callNum); LibraryBook book = findBook(searchItem); if (book == null) System.out.println ("Book " + callNum + " not found -- return impossible\n"); else book.returned (); } /** * main testing program * @param args not used */ public static void main (String args[]) { Library lib = new Library (); // set up library lib.addBook(new ReferenceBook ("Henry M. Walker", "Problems for Computer Solution using BASIC", "0-87626-717-7", "QA76.73.B3W335", "Iowa Room")); lib.addBook(new ReferenceBook ("Samuel A. Rebelsky", "Experiments in Java", "0201612674", "64.2 R25ex", "Iowa Room")); lib.addBook(new CirculatingBook ("John David Stone", "Algorithms for functional programming", "in process", "forthcoming")); lib.addBook(new CirculatingBook ("Henry M. Walker", "Computer Science 2: Principles of Software Engineering, Data Types, and Algorithms", "0-673-39829-3", "QA76.758.W35")); lib.addBook(new CirculatingBook ("Henry M. Walker", "Problems for Computer Solution using FORTRAN", "0-87626-654-5", "QA43.W34")); lib.addBook(new CirculatingBook ("Henry M. Walker", "Introduction to Computing and Computer Science with Pascal", "0-316-91841-5", "QA76.6.W3275")); lib.addBook(new CirculatingBook ("Samuel A. Rebelsky and Philip Barker", "ED-MEDIA 2002 : World Conference on Educational Multimedia, Hypermedia & Telecommunications", "14. 1-880094-45-2", "64.2 25e")); lib.addBook(new CirculatingBook ("Henry M. Walker", "Pascal: Problem Solving and Structured Program Design", "0-316-91848-2", "QA76.73.P2W35")); lib.addBook(new CirculatingBook ("Henry M. Walker", "The Limits of Computing", "0-7637-2552-8", "QA76.W185")); lib.addBook(new CirculatingBook ("Henry M. Walker", "The Tao of Computing", "0-86720-206-8", "QA76.W1855")); // sort books by call number lib.sortLibrary(); // print library lib.printLibrary(); // some users check out and return books lib.checkout("Donald Duck", "March 1, 2012", "QA43.W34"); lib.checkout("Donald Duck", "March 12, 2012", "QA76.6.W3275"); System.out.print("FAIL: "); lib.checkout("Donald Duck", "March 6, 2012", "64.2 R25ex"); lib.checkout("Minnie Mouse", "April 1, 2012", "64.2 25e"); System.out.print("FAIL: "); lib.checkout("Goofy", "February 28, 2012", "12345"); lib.returned("QA76.6.W3275"); System.out.print("FAIL: "); lib.returned("64.2 R25ex"); lib.checkout("Goofy", "March 28, 2012", "QA76.6.W3275"); // print final status of library lib.printLibrary(); } }
jason-tung/MKS21X
05Library/Library.java
249,706
/********************* */ /*! \file SimpleVC.java ** \verbatim ** Original author: Morgan Deters ** Major contributors: none ** Minor contributors (to current version): none ** This file is part of the CVC4 project. ** Copyright (c) 2009-2014 New York University and The University of Iowa ** See the file COPYING in the top-level source directory for licensing ** information.\endverbatim ** ** \brief A simple demonstration of the Java interface ** ** A simple demonstration of the Java interface. ** ** To run the resulting class file, you need to do something like the ** following: ** ** java \ ** -classpath path/to/CVC4.jar \ ** -Djava.library.path=/dir/containing/java/CVC4.so \ ** SimpleVC ** ** For example, if you are building CVC4 without specifying your own ** build directory, the build process puts everything in builds/, and ** you can run this example (after building it with "make") like this: ** ** java \ ** -classpath builds/examples:builds/src/bindings/CVC4.jar \ ** -Djava.library.path=builds/src/bindings/java/.libs \ ** SimpleVC **/ import edu.nyu.acsys.CVC4.*; public class SimpleVC { public static void main(String[] args) { System.loadLibrary("cvc4jni"); ExprManager em = new ExprManager(); SmtEngine smt = new SmtEngine(em); // Prove that for integers x and y: // x > 0 AND y > 0 => 2x + y >= 3 Type integer = em.integerType(); Expr x = em.mkVar("x", integer); Expr y = em.mkVar("y", integer); Expr zero = em.mkConst(new Rational(0)); Expr x_positive = em.mkExpr(Kind.GT, x, zero); Expr y_positive = em.mkExpr(Kind.GT, y, zero); Expr two = em.mkConst(new Rational(2)); Expr twox = em.mkExpr(Kind.MULT, two, x); Expr twox_plus_y = em.mkExpr(Kind.PLUS, twox, y); Expr three = em.mkConst(new Rational(3)); Expr twox_plus_y_geq_3 = em.mkExpr(Kind.GEQ, twox_plus_y, three); Expr formula = new Expr(em.mkExpr(Kind.AND, x_positive, y_positive)). impExpr(new Expr(twox_plus_y_geq_3)); System.out.println("Checking validity of formula " + formula + " with CVC4."); System.out.println("CVC4 should report VALID."); System.out.println("Result from CVC4 is: " + smt.query(formula)); } }
tiliang/CVC4
examples/SimpleVC.java
249,708
import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class Corelation { private String folder; private double error; private List<Double> exactCosine = new ArrayList<Double>(); private List<Double> approximateCosine = new ArrayList<Double>(); private int count = 0; double time = 0; public Corelation(String folder, double error) { this.folder = folder; this.error = error; } private void Accuracy() { long startTime = 0, stopTime = 0; startTime = System.nanoTime(); Simhash simhash = new Simhash(folder); for (int i = 0; i < simhash.filenames.length; i++) { for (int j = i + 1; j < simhash.filenames.length; j++) { double exact = simhash.exactCosine(simhash.filenames[i], simhash.filenames[j]); // if (exact < 0.85) // continue; double approx = simhash.approximateCosine(simhash.filenames[i], simhash.filenames[j]); exactCosine.add(exact); approximateCosine.add(approx); System.out.println(simhash.filenames[i] + " " + simhash.filenames[j] + " " + exact + " " + approx); if (approx < 0.8 && exact > 0.90) count++; // if (Math.abs(exact - approx) > error) // count++; } } stopTime = System.nanoTime(); time = (double) (stopTime - startTime) / 1000000000.0; System.out.println("Time: " + time+ " sec."); } public static void main(String[] args) { Corelation corelation = new Corelation("/Users/sumon/IOWA STATE UNIVERSITY/Fall 17/CPR E 528/Project/Dataset/space", 0.1); corelation.Accuracy(); //System.out.println(corelation.exactCosine); //System.out.println(corelation.approximateCosine); System.out.println(corelation.count); PrintWriter printer; try { printer = new PrintWriter("corelation-F17PA2-85.csv", "UTF-8"); for (int i = 0; i < corelation.exactCosine.size(); i++) { printer.println(corelation.exactCosine.get(i) + ", " + corelation.approximateCosine.get(i)); } printer.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
sumonbis/NearDuplicateDetection
Corelation.java
249,709
package szachy; import java.util.ArrayList; import java.util.Collection; import static szachy.SzachowaArena.jProgressBar1; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Patryk */ public class SI_MIN_MAX_Alfa_Beta { int pozycje = 0; int all_position = 0; int licznik; boolean tura_rywala, przelotcan, bleft, bright, wleft, wright, kingrochB, kingrochC, didRochB, didRochC; boolean przerwa; boolean zakaz; private final boolean wyjsciowa_tura; private final Kalkulator wynikowa; private boolean kontrola_pat(char[][] ustawienie, boolean strona, boolean przelotcan) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { int[] poza_krolewska = new int[2]; poza_krolewska[0] = j; poza_krolewska[1] = i; if (ustawienie[i][j] == 'K' || ustawienie[i][j] == 'k') { //System.out.println("wchodzi król "+(ustawienie[i][j]=='K'?"biały":"czarny")); if ((strona && ustawienie[i][j] == 'K') || (!strona && ustawienie[i][j] == 'k')) { // System.out.println("wchodzi "+ustawienie[i][j]+" "+strona); poza_krolewska[0] = i; poza_krolewska[1] = j; // System.out.println(ustawienie[poza_krolewska[0]][poza_krolewska[1]]); if (SzachMatPatKontrola.uciekaj(ustawienie, strona, poza_krolewska)) { return false; } } } else { if (SzachMatPatKontrola.znajdz_ruch(ustawienie, strona, ustawienie[i][j], poza_krolewska, przelotcan)) { return false; } } } } return true; } public SI_MIN_MAX_Alfa_Beta(char[][] ustawienie, boolean tura_rywala, boolean przelotcan, boolean bleft, boolean bright, boolean wleft, boolean wright, boolean kingrochB, boolean kingrochC, boolean dokonano_RB, boolean dokonano_RC, int kol, int licznik, int glebina) { this.licznik = licznik; this.tura_rywala = tura_rywala; this.wyjsciowa_tura = tura_rywala; this.przelotcan = przelotcan; this.bleft = bleft; this.bright = bright; this.wleft = wleft; this.wright = wright; this.didRochB = dokonano_RB; this.didRochC = dokonano_RC; this.kingrochB = kingrochB; this.kingrochC = kingrochC; wynikowa = KalkulatorPozycji.get(); } /** * * @param glebia * @param ruch * @param najwieksza * @param najmniejsza * @return */ public Ruch_wartosc wykonaj(int glebia, Collection<Ruch> ruch, int najwieksza, int najmniejsza) { int biezaca_ogolna = 0; Ruch najlepszy = null; all_position = all_position + ruch.size(); int elem = 0; for (final Ruch move : ruch) { elem++; jProgressBar1.setValue(elem); System.out.println(move.toString()); jProgressBar1.setString("Rozpatrywane:" + (move.toString()) + "| bieżacy wybór:" + (najlepszy != null ? najlepszy.toString() : "")); byte Nkolumna; if ((move.kolejnosc == 'P' || move.kolejnosc == 'p') && (Math.abs(pozyskajkordkolumna(move.koniec2) - pozyskajkordkolumna(move.start2)) == 2)) { Nkolumna = (byte) (pozyskajkordrzad(move.start1)); this.przelotcan = true; } else { Nkolumna = 0; this.przelotcan = false; } try { if (move.roszada && !move.dlugaroszada) { if (this.tura_rywala) { wright = false; } else { bright = false; } } else if (move.roszada) { wleft = false; } if (move.roszada) { if (this.tura_rywala) { this.didRochB = true; } else { this.didRochC = true; kingrochC = false; } } else { switch (move.kolejnosc) { case 'r': case 'R': if (!tura_rywala) { if (move.start1 == Ruch.kolumna.k1 && move.start2 == Ruch.rzad.r8) { bleft = false; } else if (move.start1 == Ruch.kolumna.k8 && move.start2 == Ruch.rzad.r8) { bright = false; } } else { if (move.start1 == Ruch.kolumna.k1 && move.start2 == Ruch.rzad.r1) { wleft = false; } else if (move.start1 == Ruch.kolumna.k8 && move.start2 == Ruch.rzad.r1) { wright = false; } } break; case 'K': case 'k': if (tura_rywala) { if (move.start1 == Ruch.kolumna.k5 && move.start2 == Ruch.rzad.r1) { kingrochB = false; } } else { if (move.start1 == Ruch.kolumna.k5 && move.start2 == Ruch.rzad.r8) { kingrochC = false; } } break; default: break; } } this.tura_rywala = !this.tura_rywala; biezaca_ogolna = (wyjsciowa_tura) ? minimum((glebia - 1), Nkolumna, najwieksza, najmniejsza, move.chessboard_after) : maximum((glebia - 1), Nkolumna, najwieksza, najmniejsza, move.chessboard_after); this.tura_rywala = !this.tura_rywala; if (wyjsciowa_tura) { setPrzerwa(kontrola_mat((move.chessboard_after), false, Nkolumna, przelotcan)); } else { setPrzerwa(kontrola_mat((move.chessboard_after), true, Nkolumna, przelotcan)); } if (move.roszada && !move.dlugaroszada) { if (this.tura_rywala) { wright = true; } else { bright = true; } } else if (move.roszada) { wleft = true; } if (move.roszada) { if (this.tura_rywala) { this.didRochB = false; } else { this.didRochC = false; } kingrochB = true; } else { switch (move.kolejnosc) { case 'r': case 'R': if (!tura_rywala) { if (move.start1 == Ruch.kolumna.k1 && move.start2 == Ruch.rzad.r8) { bleft = true; } else if (move.start1 == Ruch.kolumna.k8 && move.start2 == Ruch.rzad.r8) { bright = true; } } else { if (move.start1 == Ruch.kolumna.k1 && move.start2 == Ruch.rzad.r1) { wleft = true; } else if (move.start1 == Ruch.kolumna.k8 && move.start2 == Ruch.rzad.r1) { wright = true; } } break; case 'k': case 'K': if (tura_rywala) { if (move.start1 == Ruch.kolumna.k5 && move.start2 == Ruch.rzad.r1) { kingrochB = true; } } else { if (move.start1 == Ruch.kolumna.k5 && move.start2 == Ruch.rzad.r8) { kingrochC = true; } } break; default: break; } } setZakaz(false); if (wyjsciowa_tura && biezaca_ogolna > najwieksza) { najwieksza = biezaca_ogolna; najlepszy = move; } else if (!wyjsciowa_tura && biezaca_ogolna < najmniejsza) { najmniejsza = biezaca_ogolna; najlepszy = move; } jProgressBar1.setString("Rozpatrywane:" + move + "| bieżacy wybór:" + najlepszy.toString()); if (this.przerwa) { System.out.println("przerwa"); break; } } catch (Exception e) { System.out.println("ERROR POSITION"); e.printStackTrace(); return new Ruch_wartosc(move, (!wyjsciowa_tura ? Integer.MAX_VALUE : Integer.MIN_VALUE)); } } return new Ruch_wartosc(najlepszy, biezaca_ogolna); } public boolean isZakaz() { return zakaz; } public void setZakaz(boolean zakaz) { this.zakaz = zakaz; } private int maximum(final int glebia, int kolumna, int biggest, int samllest, char[][] chessboard) { if (glebia == 0 || koniec((chessboard), this.tura_rywala, this.przelotcan, kolumna)) { pozycje = pozycje + 1; /* for (Ruch r : kombinacja) { System.out.print(r.toString() + ","); } System.out.println("");*/ return this.wynikowa.zliczacz( chessboard,bleft, bright, wleft, wright, kingrochB, kingrochC, przelotcan, this.didRochB, this.didRochC,kolumna, glebia); } final Collection<Ruch> lista = Generator.generuj_posuniecia(chessboard, this.tura_rywala, this.przelotcan, this.bleft, this.bright, this.wleft, this.wright, this.kingrochB, this.kingrochC, kolumna, false); int tempB = biggest; all_position = all_position + lista.size(); for (final Ruch move : lista) { // System.out.println(move.toString()+ "|"+move.wspolczynnik_bitki); byte Nkolumna; if ((move.kolejnosc == 'P' || move.kolejnosc == 'p') && (Math.abs(pozyskajkordkolumna(move.koniec2) - pozyskajkordkolumna(move.start2)) == 2)) { Nkolumna = (byte) (pozyskajkordrzad(move.start1)); this.przelotcan = true; } else { Nkolumna = 0; this.przelotcan = false; } if (move.roszada && !move.dlugaroszada) { if (this.tura_rywala) { wright = false; } else { bright = false; } } else if (move.roszada) { wleft = false; } if (move.roszada) { if (this.tura_rywala) { this.didRochB = true; } else { this.didRochC = true; kingrochC = false; } } else { switch (move.kolejnosc) { case 'r': case 'R': if (!tura_rywala) { if (move.start1 == Ruch.kolumna.k1 && move.start2 == Ruch.rzad.r8) { bleft = false; } else if (move.start1 == Ruch.kolumna.k8 && move.start2 == Ruch.rzad.r8) { bright = false; } } else { if (move.start1 == Ruch.kolumna.k1 && move.start2 == Ruch.rzad.r1) { wleft = false; } else if (move.start1 == Ruch.kolumna.k8 && move.start2 == Ruch.rzad.r1) { wright = false; } } break; case 'K': case 'k': if (tura_rywala) { if (move.start1 == Ruch.kolumna.k5 && move.start2 == Ruch.rzad.r1) { kingrochB = false; } } else { if (move.start1 == Ruch.kolumna.k5 && move.start2 == Ruch.rzad.r8) { kingrochC = false; } } break; default: break; } } this.tura_rywala = !this.tura_rywala; tempB = Math.max(tempB, minimum(((glebia - 1)), Nkolumna, tempB, samllest, move.chessboard_after)); if (move.roszada && !move.dlugaroszada) { if (this.tura_rywala) { wright = true; } else { bright = true; } } else if (move.roszada) { wleft = true; } if (move.roszada) { if (this.tura_rywala) { this.didRochB = false; } else { this.didRochC = false; } kingrochB = true; } else { switch (move.kolejnosc) { case 'r': case 'R': if (!tura_rywala) { if (move.start1 == Ruch.kolumna.k1 && move.start2 == Ruch.rzad.r8) { bleft = true; } else if (move.start1 == Ruch.kolumna.k8 && move.start2 == Ruch.rzad.r8) { bright = true; } } else { if (move.start1 == Ruch.kolumna.k1 && move.start2 == Ruch.rzad.r1) { wleft = true; } else if (move.start1 == Ruch.kolumna.k8 && move.start2 == Ruch.rzad.r1) { wright = true; } } break; case 'k': case 'K': if (tura_rywala) { if (move.start1 == Ruch.kolumna.k5 && move.start2 == Ruch.rzad.r1) { kingrochB = true; } } else { if (move.start1 == Ruch.kolumna.k5 && move.start2 == Ruch.rzad.r8) { kingrochC = true; } } break; default: break; } } this.tura_rywala = !this.tura_rywala; this.przelotcan = (kolumna != 0); if (samllest <= tempB) { break; } } return tempB; } private int minimum(final int glebia, int kolumna, int biggest, int smallest, char[][] chessboard) { if (glebia == 0 || koniec((chessboard), this.tura_rywala, this.przelotcan, kolumna)) { pozycje = pozycje + 1; /* for (Ruch r : kombinacja) { System.out.print(r.toString() + ","); } System.out.println("");*/ return this.wynikowa.zliczacz( chessboard,przelotcan,bleft, bright, wleft, wright, kingrochB, kingrochC, this.didRochB, this.didRochC, kolumna, glebia); } final Collection<Ruch> lista = Generator.generuj_posuniecia(chessboard, this.tura_rywala, this.przelotcan, this.bleft, this.bright, this.wleft, this.wright, this.kingrochB, this.kingrochC, kolumna, false); int tempM = smallest; all_position = all_position + lista.size(); for (final Ruch move : lista) { byte Nkolumna; // System.out.println(move.toString()+ "|"+move.wspolczynnik_bitki); if ((move.kolejnosc == 'P' || move.kolejnosc == 'p') && (Math.abs(pozyskajkordkolumna(move.koniec2) - pozyskajkordkolumna(move.start2)) == 2)) { Nkolumna = (byte) (pozyskajkordrzad(move.start1)); this.przelotcan = true; } else { Nkolumna = 0; this.przelotcan = false; } if (move.roszada && !move.dlugaroszada) { if (this.tura_rywala) { wright = false; } else { bright = false; } } else if (move.roszada) { wleft = false; } if (move.roszada) { if (this.tura_rywala) { this.didRochB = true; } else { this.didRochC = true; kingrochC = false; } } else { switch (move.kolejnosc) { case 'r': case 'R': if (!tura_rywala) { if (move.start1 == Ruch.kolumna.k1 && move.start2 == Ruch.rzad.r8) { bleft = false; } else if (move.start1 == Ruch.kolumna.k8 && move.start2 == Ruch.rzad.r8) { bright = false; } } else { if (move.start1 == Ruch.kolumna.k1 && move.start2 == Ruch.rzad.r1) { wleft = false; } else if (move.start1 == Ruch.kolumna.k8 && move.start2 == Ruch.rzad.r1) { wright = false; } } break; case 'K': case 'k': if (tura_rywala) { if (move.start1 == Ruch.kolumna.k5 && move.start2 == Ruch.rzad.r1) { kingrochB = false; } } else { if (move.start1 == Ruch.kolumna.k5 && move.start2 == Ruch.rzad.r8) { kingrochC = false; } } break; default: break; } } this.tura_rywala = !this.tura_rywala; tempM = Math.min(tempM, maximum(((glebia - 1)), Nkolumna, biggest, tempM, move.chessboard_after)); if (move.roszada && !move.dlugaroszada) { if (this.tura_rywala) { wright = true; } else { bright = true; } } else if (move.roszada) { wleft = true; } if (move.roszada) { if (this.tura_rywala) { this.didRochB = false; } else { this.didRochC = false; } kingrochB = true; } else { switch (move.kolejnosc) { case 'r': case 'R': if (!tura_rywala) { if (move.start1 == Ruch.kolumna.k1 && move.start2 == Ruch.rzad.r8) { bleft = true; } else if (move.start1 == Ruch.kolumna.k8 && move.start2 == Ruch.rzad.r8) { bright = true; } } else { if (move.start1 == Ruch.kolumna.k1 && move.start2 == Ruch.rzad.r1) { wleft = true; } else if (move.start1 == Ruch.kolumna.k8 && move.start2 == Ruch.rzad.r1) { wright = true; } } break; case 'k': case 'K': if (tura_rywala) { if (move.start1 == Ruch.kolumna.k5 && move.start2 == Ruch.rzad.r1) { kingrochB = true; } } else { if (move.start1 == Ruch.kolumna.k5 && move.start2 == Ruch.rzad.r8) { kingrochC = true; } } break; default: break; } } this.tura_rywala = !this.tura_rywala; this.przelotcan = (kolumna != 0); if (tempM <= biggest) { break; } } return tempM; } private boolean koniec(char[][] ustawienie, boolean strona, boolean przelotcan, int kol) { int pionB = 0, pionC = 0, lekkieB = 0, lekkieC = 0, ciezkieB = 0, ciezkieC = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { switch (ustawienie[i][j]) { case 'P': pionB++; break; case 'p': pionC++; break; case 'N': case 'B': lekkieB++; break; case 'n': case 'b': lekkieC++; break; case 'R': case 'Q': ciezkieB++; break; case 'r': case 'q': ciezkieC++; break; } } } if (pionB < 1 && pionC < 1 && lekkieB < 2 && lekkieC < 2 && ciezkieB < 1 && ciezkieC < 1) { return true; } else { if (RuchZagrozenie_kontrola.szach(ustawienie, strona)) { return kontrola_mat(ustawienie, strona, (byte) kol, przelotcan); } else { return kontrola_pat(ustawienie, strona, przelotcan); } } } private boolean kontrola_mat(char[][] ustawienie, boolean strona, byte kol, boolean przelotcan) { int[] krol = new int[2]; if (RuchZagrozenie_kontrola.szach((ustawienie), strona)) { char[][] backup = new char[8][8]; char[][] backup1 = new char[8][8]; char[][] backup2 = new char[8][8]; char[][] backup3 = new char[8][8]; for (byte i = 0; i < 8; i++) { for (byte j = 0; j < 8; j++) { backup[i][j] = ustawienie[i][j]; backup1[i][j] = ustawienie[i][j]; backup2[i][j] = ustawienie[i][j]; backup3[i][j] = ustawienie[i][j]; if ((ustawienie[i][j] == 'K' && strona) || (ustawienie[i][j] == 'k' && !strona)) { krol[0] = i; krol[1] = j; } } } return !SzachMatPatKontrola.uciekaj(backup1, strona, krol) && !SzachMatPatKontrola.zastaw(backup2, strona, Wspomagacz.znajdzklopot(backup, strona), krol, przelotcan) && !SzachMatPatKontrola.znajdzodsiecz(backup3, strona, Wspomagacz.znajdzklopot(backup, strona), kol, przelotcan); } else { return false; } } private int pozyskajkordkolumna(Ruch.rzad kord) { switch (kord) { case r1: return 1; case r2: return 2; case r3: return 3; case r4: return 4; case r5: return 5; case r6: return 6; case r7: return 7; case r8: return 8; } return 0; } private int pozyskajkordrzad(Ruch.kolumna kord) { switch (kord) { case k1: return 1; case k2: return 2; case k3: return 3; case k4: return 4; case k5: return 5; case k6: return 6; case k7: return 7; case k8: return 8; } return 0; } public void setPrzerwa(boolean przerwa) { this.przerwa = przerwa; } public int getPozycje() { return pozycje; } public int getAll_position() { return all_position; } public boolean isPrzerwa() { return przerwa; } }
DragonAlphaProgramer/portfolio-szachy-Magister1
SI_MIN_MAX_Alfa_Beta.java
249,710
/* * Copyright (c) 2020, Board of Trustees of the University of Iowa * All rights reserved. * * Licensed under the BSD 3-Clause License. See LICENSE in the project root for license information. */ import java.util.Arrays; import java.util.Collections; import edu.uiowa.cs.clc.kind2.api.Kind2Api; import edu.uiowa.cs.clc.kind2.lustre.ComponentBuilder; import edu.uiowa.cs.clc.kind2.lustre.ContractBodyBuilder; import edu.uiowa.cs.clc.kind2.lustre.ContractBuilder; import edu.uiowa.cs.clc.kind2.lustre.Expr; import edu.uiowa.cs.clc.kind2.lustre.ExprUtil; import edu.uiowa.cs.clc.kind2.lustre.IdExpr; import edu.uiowa.cs.clc.kind2.lustre.ImportedComponentBuilder; import edu.uiowa.cs.clc.kind2.lustre.ModeBuilder; import edu.uiowa.cs.clc.kind2.lustre.ProgramBuilder; import edu.uiowa.cs.clc.kind2.lustre.TypeUtil; import edu.uiowa.cs.clc.kind2.results.Result; /** * This is an illustration of how to use the Java API for Kind 2 to implement a StopWatch Lustre * Program. */ public class StopWatch { /** * Run the main function to print the generated Lustre program and results of calling Kind 2. * * @param args inputs to the program (ignored) */ public static void main(String[] args) { // Begin constructing the Lustre program by creating a ProgramBuilder object ProgramBuilder pb = new ProgramBuilder(); // Add components to the program builder using pb's member methods pb.importFunction(sqrt()); pb.addContract(stopWatchSpec()); pb.addFunction(even()); pb.addFunction(toInt()); pb.addNode(count()); pb.addNode(sofar()); pb.addNode(since()); pb.addNode(sinceIncl()); pb.addNode(increased()); pb.addNode(stable()); pb.addNode(stopWatch()); // Build the program by calling the build() method // You can display the program using the toString() method System.out.println(pb.build().toString()); // Create a Kind2Api object to set options and check the Lustre program Kind2Api api = new Kind2Api(); // Call Kind2Api's execute method to run Kind 2 analysis on the lustre program. The results of // the analysis are saved in a Kind2Result object Result result = api.execute(pb.build()); // Check if the result object is initialized before printing it. if (result.isInitialized()) { System.out.println(result); } } /** * This methods constructs the following Lustre imported function: * * <pre> * function imported sqrt (n : real) returns (r : real); * (*@contract * assume (n) >= (0.0); * guarantee ((r) >= (0.0)) and (((r) * (r)) = (n)); * *) * </pre> * * @return a builder for the imported sqrt function */ static ImportedComponentBuilder sqrt() { // Use ExprUtil to construct various expressions IdExpr n = ExprUtil.id("n"); IdExpr r = ExprUtil.id("r"); // Use ContractBodyBuilder to construct a contract body ContractBodyBuilder cbb = new ContractBodyBuilder(); cbb.assume(ExprUtil.greaterEqual(n, ExprUtil.real("0.0"))); cbb.guarantee(ExprUtil.and(ExprUtil.greaterEqual(r, ExprUtil.real("0.0")), ExprUtil.equal(ExprUtil.multiply(r, r), n))); // Use ImportedComponentBuilder to construct an imported component (a function in this case) ImportedComponentBuilder fb = new ImportedComponentBuilder("sqrt"); fb.createVarInput("n", TypeUtil.REAL); fb.createVarOutput("r", TypeUtil.REAL); fb.setContractBody(cbb); return fb; } /** * This methods constructs the following Kind 2 contract: * * <pre> * contract StopWatchSpec (toggle : bool; reset : bool) returns (time : int); * let * var on : bool = (toggle) -> (((pre (on)) and (not (toggle))) or ((not (pre (on))) and (toggle))); * assume not ((toggle) and (reset)); * guarantee ((on) => ((time) = (1))) -> (true); * guarantee ((not (on)) => ((time) = (0))) -> (true); * guarantee (time) >= (0); * guarantee ((not (reset)) and (Since(reset, even(Count(toggle))))) => (Stable(time)); * guarantee ((not (reset)) and (Since(reset, not (even(Count(toggle)))))) => (Increased(time)); * guarantee (true) -> (((not (even(Count(toggle)))) and ((Count(reset)) = (0))) => ((time) > (pre (time)))); * mode resetting ( * require reset; * ensure (time) = (0); * ); * mode running ( * require on; * require not (reset); * ensure (true) -> ((time) = ((pre (time)) + (1))); * ); * mode stopped ( * require not (reset); * require not (on); * ensure (true) -> ((time) = (pre (time))); * ); * tel * </pre> * * @return a builder for the StopWatchSpec contract */ static ContractBuilder stopWatchSpec() { // Use ContractBuilder to construct a contract ContractBuilder cb = new ContractBuilder("StopWatchSpec"); // Use ContractBuilder's methods to specify inputs/outputs of the contract // For convenience, some methods return IdExpr objects for later use IdExpr toggle = cb.createVarInput("toggle", TypeUtil.BOOL); IdExpr reset = cb.createVarInput("reset", TypeUtil.BOOL); IdExpr time = cb.createVarOutput("time", TypeUtil.INT); IdExpr on = ExprUtil.id("on"); // Use ContractBodyBuilder to construct a contract body ContractBodyBuilder cbb = new ContractBodyBuilder(); cbb.createVarDef("on", TypeUtil.BOOL, ExprUtil.arrow(toggle, ExprUtil.or(ExprUtil.and(ExprUtil.pre(on), ExprUtil.not(toggle)), ExprUtil.and(ExprUtil.not(ExprUtil.pre(on)), toggle)))); cbb.assume(ExprUtil.not(ExprUtil.and(toggle, reset))); cbb.guarantee(ExprUtil.arrow(ExprUtil.implies(on, ExprUtil.equal(time, ExprUtil.integer(1))), ExprUtil.TRUE)); cbb.guarantee(ExprUtil.arrow( ExprUtil.implies(ExprUtil.not(on), ExprUtil.equal(time, ExprUtil.integer(0))), ExprUtil.TRUE)); cbb.guarantee(ExprUtil.greaterEqual(time, ExprUtil.integer(0))); cbb.guarantee(ExprUtil.implies( ExprUtil.and(ExprUtil.not(reset), ExprUtil.nodeCall(ExprUtil.id("Since"), reset, ExprUtil.functionCall(ExprUtil.id("even"), ExprUtil.nodeCall(ExprUtil.id("Count"), toggle)))), ExprUtil.nodeCall(ExprUtil.id("Stable"), time))); cbb.guarantee(ExprUtil.implies( ExprUtil.and(ExprUtil.not(reset), ExprUtil.nodeCall(ExprUtil.id("Since"), reset, ExprUtil.not(ExprUtil.functionCall(ExprUtil.id("even"), ExprUtil.nodeCall(ExprUtil.id("Count"), toggle))))), ExprUtil.nodeCall(ExprUtil.id("Increased"), time))); cbb.guarantee( ExprUtil .arrow(ExprUtil.TRUE, ExprUtil.implies(ExprUtil.and( ExprUtil.not(ExprUtil.functionCall(ExprUtil.id("even"), ExprUtil.nodeCall(ExprUtil.id("Count"), Collections.singletonList(toggle)))), ExprUtil.equal(ExprUtil.nodeCall(ExprUtil.id("Count"), reset), ExprUtil.integer(0))), ExprUtil.greater(time, ExprUtil.pre(time))))); // Use ModeBuilder to construct a contract mode ModeBuilder resetting = new ModeBuilder("resetting"); resetting.require(reset); resetting.ensure(ExprUtil.equal(time, ExprUtil.integer(0))); cbb.addMode(resetting); ModeBuilder running = new ModeBuilder("running"); running.require(on); running.require(ExprUtil.not(reset)); running.ensure(ExprUtil.arrow(ExprUtil.TRUE, ExprUtil.equal(time, ExprUtil.plus(ExprUtil.pre(time), ExprUtil.integer(1))))); cbb.addMode(running); ModeBuilder stopped = new ModeBuilder("stopped"); stopped.require(ExprUtil.not(reset)); stopped.require(ExprUtil.not(on)); stopped.ensure(ExprUtil.arrow(ExprUtil.TRUE, ExprUtil.equal(time, ExprUtil.pre(time)))); cbb.addMode(stopped); cb.setContractBody(cbb); return cb; } /** * This methods constructs the following Lustre function: * * <pre> * function even (N : int) returns (B : bool); * let * B = ((N) mod (2)) = (0); * tel * </pre> * * @return a builder for the even function */ static ComponentBuilder even() { // Use ComponentBuilder to construct a component (a function in this case) ComponentBuilder fb = new ComponentBuilder("even"); IdExpr N = fb.createVarInput("N", TypeUtil.INT); IdExpr B = fb.createVarOutput("B", TypeUtil.BOOL); fb.addEquation(B, ExprUtil.equal(ExprUtil.mod(N, ExprUtil.integer(2)), ExprUtil.integer(0))); return fb; } /** * This methods constructs the following Lustre function: * * <pre> * function toInt (X : bool) returns (N : int); * let * N = if (X) then (1) else (0); * tel * </pre> * * @return a builder for the toInt function */ static ComponentBuilder toInt() { ComponentBuilder f = new ComponentBuilder("toInt"); IdExpr X = f.createVarInput("X", TypeUtil.BOOL); IdExpr N = f.createVarOutput("N", TypeUtil.INT); f.addEquation(N, ExprUtil.ite(X, ExprUtil.integer(1), ExprUtil.integer(0))); return f; } /** * This methods constructs the following Lustre node: * * <pre> * node Count (X : bool) returns (N : int); * let * N = (toInt(X)) -> ((toInt(X)) + (pre (N))); * tel * </pre> * * @return a builder for the Count node */ static ComponentBuilder count() { ComponentBuilder nb = new ComponentBuilder("Count"); IdExpr X = nb.createVarInput("X", TypeUtil.BOOL); IdExpr N = nb.createVarOutput("N", TypeUtil.INT); Expr toIntX = ExprUtil.nodeCall(ExprUtil.id("toInt"), X); nb.addEquation(N, ExprUtil.arrow(toIntX, ExprUtil.plus(toIntX, ExprUtil.pre(N)))); return nb; } /** * This methods constructs the following Lustre node: * * <pre> * node Sofar (X : bool) returns (Y : bool); * let * Y = (X) -> ((X) and (pre (Y))); * tel * </pre> * * @return a builder for the SoFar node */ static ComponentBuilder sofar() { ComponentBuilder nb = new ComponentBuilder("Sofar"); IdExpr X = nb.createVarInput("X", TypeUtil.BOOL); IdExpr Y = nb.createVarOutput("Y", TypeUtil.BOOL); nb.addEquation(Y, ExprUtil.arrow(X, ExprUtil.and(X, ExprUtil.pre(Y)))); return nb; } /** * This methods constructs the following Lustre node: * * <pre> * node Since (X : bool; Y : bool) returns (Z : bool); * let * Z = (X) or ((Y) and ((false) -> (pre (Z)))); * tel * </pre> * * @return a builder for the Since node */ static ComponentBuilder since() { ComponentBuilder nb = new ComponentBuilder("Since"); IdExpr X = nb.createVarInput("X", TypeUtil.BOOL); IdExpr Y = nb.createVarInput("Y", TypeUtil.BOOL); IdExpr Z = nb.createVarOutput("Z", TypeUtil.BOOL); nb.addEquation(Z, ExprUtil.or(X, ExprUtil.and(Y, ExprUtil.arrow(ExprUtil.FALSE, ExprUtil.pre(Z))))); return nb; } /** * This methods constructs the following Lustre node: * * <pre> * node SinceIncl (X : bool; Y : bool) returns (Z : bool); * let * Z = (Y) and ((X) or ((false) -> (pre (Z)))); * tel * </pre> * * @return a builder for the SinceIncl node */ static ComponentBuilder sinceIncl() { ComponentBuilder nb = new ComponentBuilder("SinceIncl"); IdExpr X = nb.createVarInput("X", TypeUtil.BOOL); IdExpr Y = nb.createVarInput("Y", TypeUtil.BOOL); IdExpr Z = nb.createVarOutput("Z", TypeUtil.BOOL); nb.addEquation(Z, ExprUtil.and(Y, ExprUtil.or(X, ExprUtil.arrow(ExprUtil.FALSE, ExprUtil.pre(Z))))); return nb; } /** * This methods constructs the following Lustre node: * * <pre> * node Increased (N : int) returns (B : bool); * let * B = (true) -> ((N) > (pre (N))); * tel * </pre> * * @return a builder for the Increased node */ static ComponentBuilder increased() { ComponentBuilder nb = new ComponentBuilder("Increased"); IdExpr N = nb.createVarInput("N", TypeUtil.INT); IdExpr B = nb.createVarOutput("B", TypeUtil.BOOL); nb.addEquation(B, ExprUtil.arrow(ExprUtil.TRUE, ExprUtil.greater(N, ExprUtil.pre(N)))); return nb; } /** * This methods constructs the following Lustre node: * * <pre> * node Stable (N : int) returns (B : bool); * let * B = (true) -> ((N) = (pre (N))); * tel * </pre> * * @return a builder for the Stable node */ static ComponentBuilder stable() { ComponentBuilder nb = new ComponentBuilder("Stable"); IdExpr N = nb.createVarInput("N", TypeUtil.INT); IdExpr B = nb.createVarOutput("B", TypeUtil.BOOL); nb.addEquation(B, ExprUtil.arrow(ExprUtil.TRUE, ExprUtil.equal(N, ExprUtil.pre(N)))); return nb; } /** * This methods constructs the following Lustre node: * * <pre> * node Stopwatch (toggle : bool; reset : bool) returns (count : int); * (*@contract * import StopWatchSpec (toggle, reset) returns (count); * guarantee not (((::StopWatchSpec::resetting) and (::StopWatchSpec::running)) and (::StopWatchSpec::stopped)); * *) * var * running : bool; * let * running = ((false) -> (pre (running))) <> (toggle); * count = if (reset) then (0) else (if (running) then ((1) -> ((pre (count)) + (1))) else ((0) -> (pre (count)))); * tel * </pre> * * @return a builder for the StopWatch node */ static ComponentBuilder stopWatch() { ComponentBuilder nb = new ComponentBuilder("Stopwatch"); IdExpr toggle = nb.createVarInput("toggle", TypeUtil.BOOL); IdExpr reset = nb.createVarInput("reset", TypeUtil.BOOL); IdExpr count = nb.createVarOutput("count", TypeUtil.INT); ContractBodyBuilder cbb = new ContractBodyBuilder(); cbb.importContract("StopWatchSpec", Arrays.asList(toggle, reset), Collections.singletonList(count)); cbb.guarantee(ExprUtil.not(ExprUtil.and(ExprUtil.modeRef("StopWatchSpec", "resetting"), ExprUtil.modeRef("StopWatchSpec", "running"), ExprUtil.modeRef("StopWatchSpec", "stopped")))); nb.setContractBody(cbb); IdExpr running = nb.createLocalVar("running", TypeUtil.BOOL); nb.addEquation(running, ExprUtil.notEqual(ExprUtil.arrow(ExprUtil.FALSE, ExprUtil.pre(running)), toggle)); nb.addEquation(count, ExprUtil.ite(reset, ExprUtil.integer(0), ExprUtil.ite(running, ExprUtil.arrow(ExprUtil.integer(1), ExprUtil.plus(ExprUtil.pre(count), ExprUtil.integer(1))), ExprUtil.arrow(ExprUtil.integer(0), ExprUtil.pre(count))))); return nb; } }
kind2-mc/kind2-java-api
src/main/java/StopWatch.java
249,715
/** * Player class. * @author Aras Gungore * */ public class Player { /** * ID of the player. */ private final int ID; /** * Skill level of the player. */ private final int level; /** * The time which the player enters the training queue. */ public double training_queue_entry_time; /** * The time which the player enters the physiotherapy queue. */ public double physio_queue_entry_time; /** * The time which the player enters the massage queue. */ public double massage_queue_entry_time; /** * The duration which the player does training. */ public double training_duration; /** * The duration which the player gets massage. */ public double massage_duration; /** * Whether the player is available or not, meaning not being in any of the training, massage, or physiotherapy queues. */ public boolean is_available = true; /** * Number of times the player has taken the massage service. */ private int massage_count = 0; /** * The ID (aka index) of the physiotherapist the player has last visited. */ public int physiotherapist_ID; /** * The total duration which the player has waited in the massage queue. */ private double total_massage_waiting_duration = 0.0d; /** * The total duration which the player has waited in the physiotherapy queue. */ private double total_physio_waiting_duration = 0.0d; /** * Player constructor with two parameters; namely ID and level. * @param ID ID of the player. * @param level Skill level of the player. */ Player(final int ID, final int level) { this.ID = ID; this.level = level; } /** * Player takes the massage service, so this method increases the massage_count by 1. */ public void takeMassage() { ++massage_count; } /** * Increases the total_massage_waiting_duration by given amount. * @param waiting_duration The duration which the player has waited in the massage queue. */ public void increaseMassageWaitingDuration(final double waiting_duration) { total_massage_waiting_duration += waiting_duration; } /** * Increases the total_physio_waiting_duration by given amount. * @param waiting_duration The duration which the player has waited in the physiotherapy queue. */ public void increasePhysioWaitingDuration(final double waiting_duration) { total_physio_waiting_duration += waiting_duration; } /** * Getter method for the field "ID". * @return ID of the player. */ public int getID() { return ID; } /** * Getter method for the field "level". * @return Skill level of the player. */ public int getLevel() { return level; } /** * Getter method for the field "massage_count". * @return Number of times the player has taken the massage service. */ public int getMassageCount() { return massage_count; } /** * Getter method for the field "total_massage_waiting_duration". * @return The total duration which the player has waited in the massage queue. */ public double getTotalMassageWaitingDuration() { return total_massage_waiting_duration; } /** * Getter method for the field "total_physio_waiting_duration". * @return The total duration which the player has waited in the physiotherapy queue. */ public double getTotalPhysioWaitingDuration() { return total_physio_waiting_duration; } }
arasgungore/CMPE250-projects
ExcelFed/src/Player.java
249,718
/* * Copyright (C) 2000-2001 Iowa State University * * This file is part of mjc, the MultiJava Compiler, and the JML Project. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package junitutils; import java.util.StringTokenizer; import java.util.ArrayList; /** * Class for calculating a (somewhat) detailed comparison of two strings. * * @author Curtis Clifton * @version $Revision$ */ public class Diff { //--------------------------------------------------------------------- // CONSTRUCTORS //--------------------------------------------------------------------- /** * Calculate a difference between the given strings. * * @param oldTextLabel a label for the <code>oldText</code> parameter * @param oldText a value to be compared * @param newTextLabel a label for the <code>newText</code> parameter * @param newText a value to be compared */ public Diff(/*@ non_null */ String oldTextLabel, /*@ non_null */ String oldText, /*@ non_null */ String newTextLabel, /*@ non_null */ String newText) { this.oldText = oldText; this.newText = newText; this.differences = ""; calculate(oldTextLabel, newTextLabel); } //--------------------------------------------------------------------- // OPERATIONS //--------------------------------------------------------------------- /** * Sets the values of _areDifferent and differences according to a comparison * between oldText and newText * * @param oldTextLabel a label for the <code>oldText</code> parameter * @param newTextLabel a label for the <code>newText</code> parameter */ //@ ensures _areDifferent == areDifferent; private /*@ helper */ void calculate(/*@ non_null */ String oldTextLabel, /*@ non_null */ String newTextLabel) { // Accumulate the diff in differencesSB StringBuffer differencesSB = new StringBuffer(newText.length()); calculateDiffs(differencesSB); // Ignore local differences in the system class path for JAR files if (differencesSB.length() > 0 && differencesSB.indexOf(".jar") == -1) { // Some diffs accumulated, so the strings are different _areDifferent = true; // Prepend a key to the results. differences = NEWLINE + OLD_CH + oldTextLabel + NEWLINE + NEW_CH + newTextLabel + NEWLINE + NEWLINE + differencesSB.toString(); } else { // No diffs accumulated, so the strings must be the same or similar _areDifferent = false; differences = ""; } } private /*@ helper */ void calculateDiffs(/*@ non_null */ StringBuffer differencesSB) { String[] oldTextLines = splitByLine(oldText); String[] newTextLines = splitByLine(newText); // match by lines int oPos = 0; int nPos = 0; int lastOldMatch = -1; int lastNewMatch = -1; if (oldTextLines.length > 0 && newTextLines.length > 0) while (oPos < oldTextLines.length || nPos < newTextLines.length) { // this is a pretty dumb algorithm that doesn't handle // things like the insertion of a single new line in one // string or grouping if (oPos >= oldTextLines.length) oPos = oldTextLines.length-1; if (nPos >= newTextLines.length) nPos = newTextLines.length-1; boolean matched = false; for (int i = lastOldMatch+1; i<=oPos; ++i) { if ((/*@(non_null)*/oldTextLines[i]).equals(newTextLines[nPos])) { // Got a match for (int j=lastOldMatch+1; j<i; ++j) differencesSB.append((j+1) + OLD_CH + oldTextLines[j] + NEWLINE); for (int j=lastNewMatch+1; j<nPos; ++j) differencesSB.append((j+1) + NEW_CH + newTextLines[j] + NEWLINE); lastOldMatch = i; lastNewMatch = nPos; oPos = i+1; nPos++; matched = true; break; } } if (matched) continue; for (int i = lastNewMatch+1; i<=nPos; ++i) { if ((/*@(non_null)*/newTextLines[i]).equals(oldTextLines[oPos])) { // Got a match for (int j=lastOldMatch+1; j<oPos; ++j) differencesSB.append((j+1) + OLD_CH + oldTextLines[j] + NEWLINE); for (int j=lastNewMatch+1; j<i; ++j) differencesSB.append((j+1) + NEW_CH + newTextLines[j] + NEWLINE); lastOldMatch = oPos; lastNewMatch = i; oPos++; nPos = i + 1; matched = true; break; } } if (matched) continue; oPos++; nPos++; } // If we reached the end of one array before the other, then this // will print the remainders. for (oPos=lastOldMatch+1; oPos < oldTextLines.length; oPos++) { differencesSB.append((oPos + 1) + OLD_CH + oldTextLines[oPos] + NEWLINE); } // end of for () for (nPos=lastNewMatch+1; nPos < newTextLines.length; nPos++) { differencesSB.append((nPos + 1) + NEW_CH + newTextLines[nPos] + NEWLINE); } // end of for () } //@ ensures \nonnullelements(\result); /*@helper*/ private /*@non_null*/ String[/*#@non_null*/] splitByLine(/*@non_null*/ String text) { // thanks to Windows ridiculous two character newlines it is // hard to detect blank lines, so we don't bother trying StringTokenizer toker = new StringTokenizer(text, DELIM, false); ArrayList lines = new ArrayList(oldText.length() / 60); while (toker.hasMoreTokens()) { String tok = toker.nextToken(); lines.add(tok); } String[] result = new String[lines.size()]; lines.toArray(result); return result; } /** * Returns true if strings on which this was constructed are different. */ /*@ public normal_behavior @ ensures \result == areDifferent; @*/ public /*@ pure @*/ boolean areDifferent() { return _areDifferent; } /** * Returns the differences between the given strings. * */ //@ private normal_behavior //@ ensures \result == differences; //@ pure public String result() { return differences; } //--------------------------------------------------------------------- // PRIVILEGED DATA //--------------------------------------------------------------------- /** This is the supplied old text, to be compared against the new text */ private /*@ non_null */ String oldText; /** This is the supplied new text, to be compared against the old text */ private /*@ non_null */ String newText; /** This is set to true if the oldText and newText are not the same */ private boolean _areDifferent; /** * This output String holds the description of the differences between the old * and new text. */ /*@ spec_public */ private /*@ non_null */ String differences; //@ public model boolean areDifferent; //@ public represents areDifferent <- !differences.equals(""); //@ private invariant _areDifferent == areDifferent; /** This string holds line delimiters */ private static final /*@ non_null */ String DELIM = "\n\r\f"; /** This is the system new line character */ private static final /*@ non_null */ String NEWLINE = /*+@ (non_null String) */ System.getProperty("line.separator"); /** This string is used to mark lines of old text */ private static final /*@ non_null */ String OLD_CH = "< "; /** This string is used to mark lines of new text */ private static final /*@ non_null */ String NEW_CH = "> "; }
GaloisInc/JavaFE
Utils/junitutils/Diff.java
249,721
/* * Copyright 2015, Hridesh Rajan, Robert Dyer, * and Iowa State University of Science and Technology * * 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 boa; import java.io.IOException; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; /** * The main entry point for Boa-related tools. * * @author hridesh * */ public class BoaMain { public static void main(final String[] args) throws IOException { // parse the top-level command line options final Options options = new Options(); options.addOption("p", "parse", false, "check a Boa program (parse & semantic check)"); options.addOption("c", "compile", false, "compile a Boa program"); options.addOption("e", "execute", false, "execute a Boa program"); options.addOption("g", "generate", false, "generate a Boa dataset"); final CommandLine cl; try { if(args.length == 0) { printHelp(options, ""); return; } else { cl = new PosixParser().parse(options, new String[]{args[0]}); String[] tempargs = new String[args.length-1]; System.arraycopy(args, 1, tempargs, 0, args.length-1); if(cl.hasOption("c")) { boa.compiler.BoaCompiler.main(tempargs); } else if (cl.hasOption("p")) { boa.compiler.BoaCompiler.parseOnly(tempargs); } else if (cl.hasOption("e")) { boa.evaluator.BoaEvaluator.main(tempargs); } else if (cl.hasOption("g")) { boa.datagen.BoaGenerator.main(tempargs); } } } catch (final org.apache.commons.cli.ParseException e) { printHelp(options, e.getMessage()); } } private static final void printHelp (Options options, String message) { String header = "The most commonly used Boa options are:"; String footer = "\nPlease report issues at http://www.github.com/boalang/"; System.err.println(message); new HelpFormatter().printHelp("Boa", header, options, footer); } }
candoia/candoia
src/java/boa/BoaMain.java
249,722
/* * Sets.java - This file is part of the Jakstab project. * * Cross product method based on code taken from the MultiJava project. * Copyright 1998-2002, Iowa State University * Copyright 2007-2015 Johannes Kinder <[email protected]> * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, see <http://www.gnu.org/licenses/>. */ package org.jakstab.util; import java.util.*; import org.jakstab.util.Logger; /** * Helper functions for sets. * * @author Johannes Kinder */ public class Sets { @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(Sets.class); public static final <T> Set<Tuple<T>> crossProduct(Tuple<Set<T>> tupleOfSets) { return crossProductToIndex(tupleOfSets, tupleOfSets.size() - 1); } /* * This functions deals automatically with RTLNumber.WILDCARD and ALL_NUMBERS, since it * will assign the single element of ALL_NUMBERS, the WILDCARD, to all generated tuples */ private static final <T> Set<Tuple<T>> crossProductToIndex(Tuple<Set<T>> tupleOfSets, int pos) { Set<Tuple<T>> setOfTuples = new FastSet<Tuple<T>>(); if (pos < 0) { // we're generating the cross-product of 1 sets => return // the singleton set of the empty tuple setOfTuples.add(new Tuple<T>(0)); } else { // first recursively generate the cross-product of all earlier // positions Set<Tuple<T>> setOfEarlierTuples = crossProductToIndex(tupleOfSets, pos-1); // then extend each of these for each element at this position for (Tuple<T> earlierTuple : setOfEarlierTuples) { for (T component : tupleOfSets.get(pos)) { Tuple<T> newTuple = new Tuple<T>(pos+1); for (int i = 0; i < pos; i++) { newTuple.set(i, earlierTuple.get(i)); } newTuple.set(pos, component); setOfTuples.add(newTuple); } } } return setOfTuples; } }
Dmium/jakstab
src/org/jakstab/util/Sets.java
249,723
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Hridesh Rajan */ /*** * Calculation of Pi using the Panini language * * This computation uses the Monte Carlo Method. */ import java.util.Random; class Number { double value; Number (){ this.value = 0; } Number (double value){ this.value = value; } void incr() { value ++; } double value() { return value; } static double total(Number[] numbers) { double total = 0; for(Number n: numbers) total += n.value(); return total; } } capsule Worker () { Random prng = new Random (); Number compute(double num) { Number _circleCount = new Number(0); for (double j = 0; j < num; j++) { double x = prng.nextDouble(); double y = prng.nextDouble(); if ((x * x + y * y) < 1) _circleCount.incr(); } return _circleCount; } } capsule Pi (String[] args) { design { Worker workers[10]; } void run(){ if(args.length <= 0) { System.out.println("Usage: panini Pi <sample size>, try several hundred thousand samples."); return; } double totalSamples = Integer.parseInt(args[0]); double startTime = System.currentTimeMillis(); Number[] results = foreach(Worker w: workers) w.compute(totalSamples/workers.length); double total = 0; for (int i=0; i < workers.length; i++) total += results[i].value(); double pi = 4.0 * total / totalSamples; System.out.println("Pi : " + pi); double endTime = System.currentTimeMillis(); System.out.println("Time to compute Pi using " + totalSamples + " samples was:" + (endTime - startTime) + "ms."); } }
hridesh/panc
examples/Pi.java
249,725
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Yuheng Long */ capsule Pong(Ping ping) { boolean done = false; void act(int message) { if (!done) { ping.act(message); if (message % 1000 == 0) { System.out.println("message = " + message); } } } void done() { done = true; } } capsule Ping(Pong pong, int total) { boolean done = false; void act(int message) { if (message > 0) { publishPing(); } else { pong.done(); done = true; } } void done() { done = true; } private void publishPing() { total--; pong.act(total); } } capsule PingPong () { design { Ping ping; Pong pong; ping(pong, 1000000); pong(ping); } void run() { ping.act(1000000); } }
hridesh/panc
examples/PingPong.java
249,726
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Bryan Shrader */ class InvalidTransactionException extends IllegalArgumentException { public InvalidTransactionException() { super("unable to process request"); } } capsule BankAccount() { double balance = 100.0; //state is private and guaranteed to be accessed by only one thread void deposit(double money) { balance += money; System.out.println("depositing $"+money+": total now $"+balance); } void withdraw(double money) { if(balance - money < 0) { throw new InvalidTransactionException(); } balance -= money; System.out.println("withdrawing $"+money+": total now $"+balance); } } capsule Client1(BankAccount account) { void makeTransactions() { account.deposit(25); account.withdraw(10); } } capsule Client2(BankAccount account) { void makeTransactions() { account.withdraw(25); account.deposit(25); } } capsule Bank (){ design { Client1 c1; Client2 c2; BankAccount a; c1(a); c2(a); } void run() { c1.makeTransactions(); //Returns immediately: c1 works concurrently. c2.makeTransactions(); //Returns immediately: c1 works concurrently. } } /* * This example illustrates an instance where race conditions are avoided. * * Client1 and Client2 have the potential to be executed in separate threads. * Yet, regardless of the order in which the transactions are executed, * the integrity of BankAccount's state is preserved, since only one thread * has access thereto (thread safety by means of confinement). * */
hridesh/panc
examples/Bank.java
249,728
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Eric Lin, Hridesh Rajan */ capsule Helper () { Number fact(int current, int numIndents) { String indents = ""; for(int i=0; i<numIndents; i++) indents+= "\t"; System.out.println(indents + "Computing factoring for " + current); if(current == 0) return new Number(0); Number recursiveTerm = fact(current-1, numIndents+1); System.out.println(indents + "\tThe recursive term is " + recursiveTerm); Number answer = new Number(current + recursiveTerm.v()); System.out.println(indents + "Factorial of " + current + " is " + answer); return answer; } } capsule Factorial { design { Helper h; } void run(){ System.out.println(h.fact(10, 0).v()); } } class Number{ int number; Number(int number){ this.number = number; } int v(){ return number;} public String toString() { return "" + number; } }
hridesh/panc
examples/Factorial.java
249,729
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): http://99-bottles-of-beer.net */ capsule Bottles99 { void run() { for(int i=99; i>1; i--) System.out.println(nonZero(i)); System.out.println("1 bottle of beer on the wall, 1 bottle of beer.\n" + "Take one down and pass it around, no more bottles of beer on the wall.\n\n" + "No more bottles of beer on the wall, no more bottles of beer.\n" + "Go to the store and buy some more, 99 bottles of beer on the wall."); } private String nonZero(int num){ return num + " bottles of beer on the wall, "+ num + " bottles of beer.\n" + "Take one down and pass it around, " + (num-1)+" bottles of beer on the wall.\n"; } }
hridesh/panc
examples/Bottles99.java
249,731
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Hridesh Rajan */ // Short version: // To test compile this file and run this capsule. // $PATH_TO_PANC$/panc HelloWorld.java // $PATH_TO_PANINI$/panini HelloWorldShort capsule HelloWorldShort() { void run() { System.out.println("Panini: Hello World!"); } } //Longer version that illustrates most Panini features. //To test compile this file and run this capsule. //$PATH_TO_PANC$/panc HelloWorld.java //$PATH_TO_PANINI$/panini HelloWorld signature Stream { //A signature declaration void write(String s); } capsule Console () implements Stream { //Capsule declaration void write(String s) { //Capsule procedure System.out.println(s); } } capsule Greeter (Stream s) { //Requires an instance of Stream to work String message = "Hello World!"; // State declaration void greet(){ //Capsule procedure s.write("Panini: " + message); //Inter-capsule procedure call long time = System.currentTimeMillis(); s.write("Time is now: " + time); } } capsule HelloWorld() { design { //Design declaration Console c; //Capsule instance declaration Greeter g; //Another capsule instance declaration g(c); //Wiring, connecting capsule instance g to c } void run() { //An autonomous procedure g.greet(); //Inter-capsule procedure call } }
hridesh/panc
examples/HelloWorld.java
249,732
import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.regex.Pattern; import java.util.stream.Stream; import org.junit.Test; /** * @author Tyler Fenton * @author Sean Hinchee * @author Ryan Radomski */ public class CrawlerTest { public static Graph dummyGraph() { Graph gr = new Graph(new LinkedList<>()); Adjacency a = new Adjacency("A"); Adjacency b = new Adjacency("B"); Adjacency c = new Adjacency("C"); Adjacency d = new Adjacency("D"); Adjacency e = new Adjacency("E"); Adjacency f = new Adjacency("F"); Adjacency g = new Adjacency("G"); Adjacency h = new Adjacency("H"); gr.adjacencies.put("A", a); gr.adjacencies.put("B", b); gr.adjacencies.put("C", c); gr.adjacencies.put("D", d); gr.adjacencies.put("E", e); gr.adjacencies.put("F", f); gr.adjacencies.put("G", g); gr.adjacencies.put("H", h); a.children.add("B"); a.children.add("C"); a.children.add("D"); b.children.add("I"); b.children.add("J"); c.children.add("E"); c.children.add("F"); c.children.add("B"); c.children.add("D"); d.children.add("G"); d.children.add("H"); d.children.add("A"); e.children.add("A"); e.children.add("A"); a.length = 0; b.length = 1; c.length = 1; d.length = 1; e.length = 2; f.length = 2; g.length = 2; h.length = 2; return gr; } @Test public void subdoc() throws IOException { String doc = Util.curl(WikiCrawler.BASE_URL, "/wiki/Teletubbies"); String subdoc = Util.extractSubdoc(doc); Collection<String> results = Util.extractLinks(subdoc); assert (results.contains("/wiki/Pre-school")); } @Test public void influence() { Graph g = dummyGraph(); NetworkInfluence ne = new NetworkInfluence("smolgraph.txt"); ne.graph = g; System.out.println(ne.influence("F")); } @Test public void bfs() { Graph g = dummyGraph(); Util.bfs(g, "A", "H"); } @Test public void mostInfluentialModular() { Graph g = dummyGraph(); NetworkInfluence ne = new NetworkInfluence("smolgraph.txt"); ne.graph = g; g.adjacencies.keySet().stream().forEach(x -> System.out.println(x + " " + ne.influence(x))); System.out.println(ne.mostInfluentialModular(3)); } @Test public void mostInfluentialSubModular() { Graph g = dummyGraph(); NetworkInfluence ne = new NetworkInfluence("smolgraph.txt"); ne.graph = g; g.adjacencies.keySet().stream().forEach(x -> System.out.println(x + " " + ne.influence(x))); System.out.println(ne.mostInfluentialSubModular(3)); } @Test public void mostInfluentialDegree() { Graph g = dummyGraph(); NetworkInfluence ne = new NetworkInfluence("smolgraph.txt"); g.adjacencies.keySet().stream().forEach(x -> System.out.println(x + " " + ne.influence(x))); System.out.println(ne.mostInfluentialDegree(3)); } @Test public void containstopic() throws IOException { LinkedList<String> topics = new LinkedList<String>(); topics.add("are"); String doc = Util.curl(WikiCrawler.BASE_URL, "/wiki/Teletubbies"); assert (Util.hasTopics(topics, doc)); topics.add("mein"); topics.add("kampf"); assert (!Util.hasTopics(topics, doc)); } @Test public void addOne() throws IOException, InterruptedException { ArrayList<String> topics = new ArrayList<String>(); topics.add("loons"); Graph g = new Graph(topics); g.add(3, "/wiki/Duck"); } @Test public void add3() throws IOException, InterruptedException { ArrayList<String> topics = new ArrayList<String>(); topics.add("are"); WikiCrawler c = new WikiCrawler("/wiki/Gforth", 10, topics, "foo.txt"); c.crawl(); } @Test public void benchmark() throws IOException { ArrayList<String> topics = new ArrayList<String>(); topics.add("Iowa State"); topics.add("Cyclones"); Graph g = new Graph(topics); long startTime = System.nanoTime(); String doc = Util.curl(WikiCrawler.BASE_URL, "/wiki/Iowa_State_University"); long endTime = System.nanoTime(); System.out.println("curl: " + (float) (endTime - startTime) / 1000000); startTime = System.nanoTime(); String subdoc = Util.extractSubdoc(doc); endTime = System.nanoTime(); System.out.println("subdoc: " + (float) (endTime - startTime) / 1000000); startTime = System.nanoTime(); Util.extractLinks(subdoc); endTime = System.nanoTime(); System.out.println("extract links: " + (float) (endTime - startTime) / 1000000); startTime = System.nanoTime(); g.validatePage(subdoc, "/wiki/Iowa_State_University"); endTime = System.nanoTime(); System.out.println("validate page: " + (float) (endTime - startTime) / 1000000); } @Test public void big12() throws IOException { ArrayList<String> topics = new ArrayList<String>(); topics.add("Iowa State"); topics.add("Cyclones"); String doc = Util.extractSubdoc(Util.curl(WikiCrawler.BASE_URL, "/wiki/Big_12_Conference")); System.out.println(Pattern.compile("Cyclones").matcher(doc).find()); } @Test public void top10MID() throws IOException, InterruptedException { ArrayList<String> topics = new ArrayList<String>(); WikiCrawler c = new WikiCrawler("/wiki/Computer_Science", 100, topics, "WikiCS.txt"); c.crawl(); NetworkInfluence ni = new NetworkInfluence("WikiCS.txt"); ArrayList<String> al = ni.mostInfluentialDegree(10); System.out.println("Top 10 Most Inf. Sub. Mod.: "); System.out.println(al); System.out.println(); } @Test public void top10MIM() throws IOException, InterruptedException { ArrayList<String> topics = new ArrayList<String>(); WikiCrawler c = new WikiCrawler("/wiki/Computer_Science", 100, topics, "WikiCS.txt"); c.crawl(); NetworkInfluence ni = new NetworkInfluence("WikiCS.txt"); ArrayList<String> al = ni.mostInfluentialModular(10); System.out.println("Top 10 Most Inf. Sub. Mod.: "); al.stream().forEach(x -> System.out.println(x + " " + ni.graph.adjacencies.get(x).length)); System.out.println(); } @Test public void top10MISM() throws IOException, InterruptedException { ArrayList<String> topics = new ArrayList<String>(); WikiCrawler c = new WikiCrawler("/wiki/Computer_Science", 100, topics, "WikiCS.txt"); c.crawl(); NetworkInfluence ni = new NetworkInfluence("WikiCS.txt"); ArrayList<String> al = ni.mostInfluentialSubModular(10); System.out.println("Top 10 Most Inf. Sub. Mod.: "); System.out.println(al); System.out.println(); } @Test public void numEdges() throws IOException, InterruptedException { ArrayList<String> topics = new ArrayList<String>(); WikiCrawler c = new WikiCrawler("/wiki/Complexity_theory", 100, topics, "complexity.txt"); c.crawl(); } @Test public void isu() throws IOException, InterruptedException { ArrayList<String> topics = new ArrayList<String>(); topics.add("Iowa State"); topics.add("Cyclones"); WikiCrawler c = new WikiCrawler("/wiki/Iowa_State_University", 100, topics, "isu.txt"); c.crawl(); } }
henesy/PA2
PA2/src/CrawlerTest.java
249,733
/********************* */ /*! \file SimpleVCCompat.java ** \verbatim ** Original author: Morgan Deters ** Major contributors: none ** Minor contributors (to current version): none ** This file is part of the CVC4 project. ** Copyright (c) 2009-2013 New York University and The University of Iowa ** See the file COPYING in the top-level source directory for licensing ** information.\endverbatim ** ** \brief A simple demonstration of the Java compatibility interface ** (quite similar to the old CVC3 Java interface) ** ** A simple demonstration of the Java compatibility interface ** (quite similar to the old CVC3 Java interface). ** ** To run the resulting class file, you need to do something like the ** following: ** ** java \ ** -classpath path/to/CVC4compat.jar \ ** -Djava.library.path=/dir/containing/libcvc4bindings_java_compat.so \ ** SimpleVCCompat ** ** For example, if you are building CVC4 without specifying your own ** build directory, the build process puts everything in builds/, and ** you can run this example (after building it with "make") like this: ** ** java \ ** -classpath builds/examples:builds/src/bindings/compat/java/CVC4compat.jar \ ** -Djava.library.path=builds/src/bindings/compat/java/.libs \ ** SimpleVCCompat **/ import cvc3.*; public class SimpleVCCompat { public static void main(String[] args) { ValidityChecker vc = ValidityChecker.create(); // Prove that for integers x and y: // x > 0 AND y > 0 => 2x + y >= 3 Type integer = vc.intType(); Expr x = vc.varExpr("x", integer); Expr y = vc.varExpr("y", integer); Expr zero = vc.ratExpr(0); Expr x_positive = vc.gtExpr(x, zero); Expr y_positive = vc.gtExpr(y, zero); Expr two = vc.ratExpr(2); Expr twox = vc.multExpr(two, x); Expr twox_plus_y = vc.plusExpr(twox, y); Expr three = vc.ratExpr(3); Expr twox_plus_y_geq_3 = vc.geExpr(twox_plus_y, three); Expr formula = vc.impliesExpr(vc.andExpr(x_positive, y_positive), twox_plus_y_geq_3); System.out.println("Checking validity of formula " + formula + " with CVC4."); System.out.println("CVC4 should report VALID."); System.out.println("Result from CVC4 is: " + vc.query(formula)); } }
teh/CVC4
examples/SimpleVCCompat.java
249,734
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Hridesh Rajan, Steven M. Kautz */ /*** * An example client in the Panini language that goes with the EchoServer. */ import java.net.*; import java.io.*; capsule EchoClient() { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; BufferedReader stdIn = null; void run() { try { String userInput; open(); out.println("Hello Server!"); System.out.println("Server replied: " + in.readLine()); out.println("" + System.currentTimeMillis() + "."); System.out.println("Server replied: " + in.readLine()); out.println("Good bye."); System.out.println("Server replied: " + in.readLine()); close(); } catch (IOException e) { e.printStackTrace(System.err); } } private void open() { try { echoSocket = new Socket("localhost", 8080); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream())); stdIn = new BufferedReader(new InputStreamReader(System.in)); } catch (UnknownHostException e) { e.printStackTrace(System.err); } catch (IOException e) { e.printStackTrace(System.err); } } private void close() { try { out.close(); in.close(); stdIn.close(); echoSocket.close(); } catch (IOException e) { e.printStackTrace(System.err); } } }
hridesh/panc
examples/EchoClient.java
249,735
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Hridesh Rajan */ /*** * Classic KWIC system using the Panini language * * This implementation of the KWIC system is based on the example * presented in the following paper. * D. L. Parnas. 1972. On the criteria to be used in decomposing systems * into modules. Commun. ACM 15, 12 (December 1972), 1053-1058. * DOI=10.1145/361598.361623 http://doi.acm.org/10.1145/361598.361623 * */ capsule Output(Alphabetizer alphabetizer){ /** * Prints the lines at the standard output. * @param alphabetizer source of the sorted lines */ void print(){ for(int i = 0; i < alphabetizer.getLineCount(); i++) System.out.println(alphabetizer.getLineAsString(i)); } }
hridesh/panc
examples/KWIC/Output.java
249,736
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Hridesh Rajan */ class Number { int number; Number(int number){ this.number = number; } int v(){ return number;} public String toString() { return "" + number; } } class Sum extends Number { Number left; Number right; Sum(Number left, Number right){ super(0); this.left = left; this.right = right; } @Override int v() { return left.v() + right.v(); } } signature Worker { Number execute(int num); } capsule FibWorker (Worker w) implements Worker { Number execute(int n) { if (n < 2) return new Number(n); if (n < 13) return new Number(helper(13)); return new Sum (w.execute(n-1), w.execute(n-2)); } private int helper(int n) { int prev1=0, prev2=1; for(int i=0; i<n; i++) { int savePrev1 = prev1; prev1 = prev2; prev2 = savePrev1 + prev2; } return prev1; } } capsule Distributor (Worker[] workers) implements Worker { int current = 0; Number execute(int num) { Number result = workers[current].execute(num); current++; if(current == workers.length) current = 0; return result; } } capsule Main (Worker w) { design Factorial { FibWorker workers[8]; Distributor d; d(workers); wireall(workers, d); } void run(){ System.out.println(w.execute(30).v()); } }
hridesh/panc
examples/FactorialSeq.java
249,738
/* * Copyright (C) 2000-2001 Iowa State University * * This file is part of mjc, the MultiJava Compiler, adapted for ESC/Java2. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ * Author: David R. Cok */ package junitutils; import java.io.PrintStream; import java.io.*; import java.lang.reflect.Method; /** This class contains miscellaneous (static) utility functions that are useful in writing JUnit functional tests. */ public class Utils { /** Setting this field to true disables the capturing of the output; one would do this only for debugging purposes. */ static public boolean disable = false; /** A cached value of the usual System out stream. */ //@ spec_public final private static /*@non_null*/ PrintStream pso = /*+@ (non_null PrintStream) */ System.out; /** A cached value of the usual System err stream. */ //@ spec_public final private static /*@non_null*/ PrintStream pse = /*+@ (non_null PrintStream) */ System.err; /** Redirects System.out and System.err to the given PrintStream. Note that setStreams/restoreStreams operate on the global values of System.out and System.err; these implementations are not synchronized - you will need to take care of any race conditions if you utilize these in more than one thread. @param ps The stream that is the new output and error stream */ /*@ public normal_behavior @ requires disable; @ assignable \nothing; @ also @ public normal_behavior @ requires !disable; @ requires ps.isOpen; @ assignable System.out, System.err; @ ensures System.out == ps @ && System.err == ps; @*/ static public void setStreams(/*@ non_null */ PrintStream ps) { if (disable) return; System.out.flush(); System.err.flush(); System.setOut(ps); System.setErr(ps); } /** Creates a new output stream (which is returned) and makes it the stream into which the standard and error outputs are captured. @return an output stream into which standard and error output is captured */ /*@ public normal_behavior @ requires disable; @ assignable \nothing; @ ensures \fresh(\result); @ also @ public normal_behavior @ requires !disable; @ assignable System.out, System.err; @ ensures \fresh(\result); @ ensures \result.isOpen; @ ensures System.out.underlyingStream == \result; @ ensures System.err.underlyingStream == \result; @ ensures System.err == System.out; @*/ static public /*@ non_null */ ByteArrayOutputStream setStreams() { ByteArrayOutputStream ba = new ByteArrayOutputStream(10000); PrintStream ps = new PrintStream(ba); setStreams(ps); return ba; } // TODO - note the hard-coded size of the stream above. It needs to be // variable, or at least be sure to capture overflows. The size needs to // be large enough to hold the output of a test. /** Restores System.out and System.err to the initial, system-defined values. It is ok to call this method even if setStreams has not been called. <p> Note that setStreams/restoreStreams operate on the global values of System.out and System.err; these implementations are not synchronized - you will need to take care of any race conditions if you utilize these in more than one thread. */ /*@ public normal_behavior @ requires disable; @ assignable \nothing; @ also @ public normal_behavior @ requires !disable; @ assignable System.out, System.err; @ ensures System.out == pso @ && System.err == pse; @*/ static public void restoreStreams() { restoreStreams(false); } /** Restores System.out and System.err to the initial, system-defined values. It is ok to call this method even if setStreams has not been called. <p> Note that setStreams/restoreStreams operate on the global values of System.out and System.err; these implementations are not synchronized - you will need to take care of any race conditions if you utilize these in more than one thread. * @param close if true, the current output and error streams * are closed before being reset (if they are not currently the * System output and error streams) */ /*@ public normal_behavior @ requires disable; @ assignable \nothing; @ also @ public normal_behavior @ requires !disable; @ assignable System.out, System.err; @ ensures System.out == pso @ && System.err == pse; @ ensures (close && \old(System.out) != pso) ==> \old(System.out).wasClosed; @ ensures (close && \old(System.err) != pse) ==> \old(System.err).wasClosed; @*/ static public void restoreStreams(boolean close) { if (disable) return; if (close) { if (pso != System.out) System.out.close(); if (pse != System.err) System.err.close(); } System.setOut(pso); System.setErr(pse); } /** Parses a string into arguments as if it were a command-line, using the QuoteTokenizer to parse the tokens. @param s The String to parse @return The input string parsed into command-line arguments */ //@ ensures \nonnullelements(\result); static public /*@ non_null */ String[/*#@non_null*/] parseLine(/*@ non_null */String s) { QuoteTokenizer q = new QuoteTokenizer(s); java.util.ArrayList args = new java.util.ArrayList(); while (q.hasMoreTokens()) { String a = q.nextToken(); args.add(a); } Object[] o = args.toArray(new String[args.size()]); return (/*+@non_null*/String[/*#@non_null*/])o; //@ nowarn Cast; } /** Parses a string into arguments as if it were a command-line, using the QuoteTokenizer to parse the tokens. Adds to the existing list of arguments. @param s The String to parse @return The input string parsed into command-line arguments */ //@ ensures \nonnullelements(\result); static public /*@ non_null */ String[] parseLineWithArgs(/*@ non_null */String s, /*@ non_null */String[] originalArgs) { QuoteTokenizer q = new QuoteTokenizer(s); java.util.ArrayList args = new java.util.ArrayList(); // Add in existing arguments for (int i=0; i < originalArgs.length; i++) { String a = originalArgs[i]; args.add (a); } // Add in specific arguments from the list of files while (q.hasMoreTokens()) { String a = q.nextToken(); args.add(a); } return (String[])args.toArray(new String[args.size()]); } /** An enumerator that parses a string into tokens, according to the rules a command-line would use. White space separates tokens, with double-quoted and single-quoted strings recognized. */ // FIXME - does not handle escape sequences in strings, nor // quoted strings that are not the whole token, e.g. // a b c+"asd" should be three tokens, "a", "b", and c+"asd" . static public class QuoteTokenizer { /** The String being tokenized */ /*@ spec_public */ final private /*@non_null*/ String ss; /** A char array representation of the String being tokenized */ /*@ spec_public */ final private /*@non_null*/ char[] cc; /** The position in the char array */ /*@ spec_public */ private int pos = 0; /*@ invariant pos >= 0; @ invariant pos <= cc.length; @*/ /** Initializes the tokenizer with the given String * @param s the String to be tokenized */ //@ modifies ss,cc; //@ ensures s == ss; public QuoteTokenizer(/*@ non_null */ String s) { ss = s; cc = s.toCharArray(); } /*@ public model boolean moreTokens; @ public represents moreTokens <- @ (\exists int i; pos <= i && i < cc.length; @ Character.isWhitespace(cc[i])); @*/ /*@ public model boolean moreChar; @ public represents moreChar <- pos < cc.length; @*/ //@ public invariant_redundantly moreTokens ==> moreChar; /*+@ public invariant_redundantly @ moreChar && !Character.isWhitespace(cc[pos]) ==> moreTokens; @*/ /** * @return true if there are more tokens to be returned */ /*@ public normal_behavior @ modifies pos; @ ensures \result == moreChar; @ ensures \result ==> !Character.isWhitespace(cc[pos]); */ /*+@ ensures_redundantly \result ==> moreTokens; @ ensures \result == moreTokens; // true but esc cannot prove @ ensures moreTokens == \old(moreTokens); // true but esc cannot prove @*/ public boolean hasMoreTokens() { while (pos < cc.length && Character.isWhitespace(cc[pos])) pos++; return pos < cc.length; } /** * @return the next token if there is one, otherwise null */ /*@ public normal_behavior @ requires moreChar; @ modifies pos; @ ensures pos > \old(pos); @ also public normal_behavior @ requires !moreChar; @ modifies \nothing; @ ensures \result == null; @*/ //@ also signals_only IndexOutOfBoundsException; /*+@ also @ public normal_behavior @ requires moreTokens; @ modifies pos; @ ensures \result != null; @ also public normal_behavior @ requires !moreTokens; @ modifies pos; @ ensures \result == null; @*/ public /*@nullable*/String nextToken() { String res = null; while (pos < cc.length && Character.isWhitespace(cc[pos])) ++pos; if (pos == cc.length) return res; int start = pos; if (cc[pos] == '"') { ++pos; while (pos < cc.length && cc[pos] != '"' ) ++pos; if (cc[pos] == '"') ++pos; //@ nowarn IndexTooBig; res = ss.substring(start+1,pos-1); } else if (cc[pos] == '\'') { ++pos; while (pos < cc.length && cc[pos] != '\'' ) ++pos; if (cc[pos] == '\'') ++pos; //@ nowarn IndexTooBig; res = ss.substring(start+1,pos-1); } else { while (pos < cc.length && !Character.isWhitespace(cc[pos])) ++pos; res = ss.substring(start,pos); } return res; } //@ nowarn Exception; } /** Deletes the contents of a directory, including subdirectories. If the second argument is true, the directory itself is deleted as well. @param d The directory whose contents are deleted @param removeDirectoryItself if true, the directory itself is deleted @return false if something could not be deleted; true if everything was successfully deleted */ static public boolean recursivelyRemoveDirectory(/*@ non_null */ File d, boolean removeDirectoryItself) { if (!d.exists()) return true; boolean success = true; File[] fl = d.listFiles(); if (fl != null) { for (int ff=0; ff<fl.length; ++ff) { if (fl[ff].isDirectory()) { if (!recursivelyRemoveDirectory(fl[ff],true)) success = false; } else { if (!fl[ff].delete()) success = false; } } } if (removeDirectoryItself) { if (!d.delete()) success = false; } return success; } /** Reads the contents of the file with the given name, returning a String. This is an optimized version that uses the byte array provided and presumes that the file is shorter than the length of the array. @param filename The file to be read @param cb A temporary byte array to speed reading @return The contents of the file @throws java.io.IOException */ // FIXME - can we check that the file is too long without losing the efficiency benefits? static public /*@ non_null */ String readFile(/*@ non_null */ String filename, /*@ non_null */ byte[] cb) throws java.io.IOException { int i = 0; int j = 0; java.io.FileInputStream f = null; try { f = new java.io.FileInputStream(filename); while (j != -1) { i = i + j; j = f.read(cb,i,cb.length-i); } } finally { if (f != null) f.close(); } return new String(cb,0,i); } /** * Reads a file, returning a String containing the contents * @param filename the file to be read * @return the contents of the file as a String, or null if the * file could not be read */ static public /*@nullable*/String readFileX(/*@ non_null */ String filename) { try { return readFile(filename); } catch (Exception e ) { System.out.println("Could not read file " + filename); // FIXME - need a better way to report and catch errors } return null; } /** Reads the contents of the file with the given name, returning a String. This version presumes the file is shorter than an internal buffer. FIXME @param filename The file to be read @return The contents of the file @throws IOException */ static public /*@ non_null */ String readFile(/*@ non_null */ String filename) throws java.io.IOException { StringBuffer sb = new StringBuffer(10000); char[] cb = new char[10000]; // This hard-coded value can be anything; // smaller numbers will be less efficient since more reads // may result int j = 0; java.io.FileReader f = null; try { f = new java.io.FileReader(filename); while (j != -1) { j = f.read(cb,0,cb.length); if (j != -1) sb.append(cb,0,j); } } finally { if (f != null) f.close(); } return sb.toString(); } /** * Executes the static compile(String[]) method of the given class * @param cls The class whose 'compile' method is be invoked * @param args The String[] argument of the method * @return The standard output and error output of the invocation */ //@ requires \nonnullelements(args); static public String executeCompile(/*@ non_null */ Class cls, /*@ non_null */ String[] args) throws SecurityException, NoSuchMethodException { return executeMethod(cls,"compile",args); } /** Finds and executes the method with the given name in the given class; the method must have a single argument of type String[]. The 'args' parameter is supplied to it as its argument. * @param cls The class whose method is to be invoked * @param methodname The method to be invoked * @param args The argument of the method * @return The standard output and error output of the invocation */ //@ requires \nonnullelements(args); static private String executeMethod(/*@ non_null */ Class cls, /*@ non_null */ String methodname, /*@ non_null */ String[] args) throws SecurityException, NoSuchMethodException { try { Method method = cls.getMethod(methodname, new Class[] { String[].class }); return executeMethod(method,args); } catch (NoSuchMethodException e) { System.err.println("No method compile in class " + cls); // FIXME - better error return needed e.printStackTrace(); throw e; // new RuntimeException(e.toString()); } } /** Calls the given method on the given String[] argument. Any standard output and error output is collected and returned as the String return value. * @param method The static method to be invoked * @param args The argument of the method * @return The standard output and error output of the method */ //@ requires \nonnullelements(args); static private String executeMethod(/*@ non_null */ Method method, /*@ non_null */ String[] args) { try { ByteArrayOutputStream ba = setStreams(); /*Object result =*/ method.invoke(null,new Object[]{args}); // The following line might cause a cast error, but since b is not used it is comment out. // boolean b = ((Boolean)result).booleanValue(); return ba.toString(); } catch (Exception e) { Utils.restoreStreams(); // FIXME - see comment in TestFilesTestSuite.java // Need the above restore before we try to print something System.out.println(e.toString()); // FIXME - need better error handling } finally { Utils.restoreStreams(); } return null; } /** The suffix to append to create the golden output filename */ static private final String ORACLE_SUFFIX = "-expected"; /** The suffix to append to create the actual output filename */ static private final String SAVED_SUFFIX = "-ckd"; /** Compares the given string to the content of the given file using a comparator that ignores platform differences in line-endings. The method has the side effect of saving the string value in a file for later comparison if the string and file are different, and making sure that the actual output file (the -ckd file) is deleted if the string and file are the same. The expected output filename is the rootname + "-expected"; the actual output filename is the rootname + "-ckd". * * @param s the String to compare * @param rootname the prefix of the file name * @return The Diff structure that contains the comparison * @throws java.io.IOException */ static public Diff compareStringToFile(/*@ non_null */ String s, String rootname) throws java.io.IOException { String ss = Utils.readFile(rootname+ORACLE_SUFFIX); Diff df = new Diff( "expected", ss, "actual", s ); if (!df.areDifferent()) { // If the two strings match, the test succeeds and we make sure // that there is no -ckd file to confuse anyone. (new File(rootname+SAVED_SUFFIX)).delete(); } else { // If the strings do not match, we save the actual string and // fail the test. FileWriter f = null; try { f = new FileWriter(rootname+SAVED_SUFFIX); f.write(s); } finally { if (f != null) f.close(); } } return df; } /** This deletes all files (in the current directory) whose names match the given pattern in a regular-expression sense; however, it is only implemented for patterns consisting of characters and at most one '*', since I'm not going to rewrite an RE library. * @param pattern the pattern to match against filenames */ static public void removeFiles(/*@ non_null */ String pattern) { File[] list; int k = pattern.indexOf("*"); if (k == -1) { list = new File[] { new File(pattern) }; } else if (k == 0) { final String s = pattern.substring(1); FileFilter ff = new FileFilter() { public boolean accept(File f) { return f.isFile() && f.getName().endsWith(s); } }; list = (new File(".")).listFiles(ff); } else if (k+1 == pattern.length()) { final String s = pattern.substring(0,k); FileFilter ff = new FileFilter() { public boolean accept(File f) { return f.isFile() && f.getName().startsWith(s); } }; list = (new File(".")).listFiles(ff); } else { final String s = pattern.substring(0,k); final String ss = pattern.substring(k+1); final int j = pattern.length()-1; FileFilter ff = new FileFilter() { public boolean accept(File f) { return f.isFile() && f.getName().length() >= j && f.getName().startsWith(s) && f.getName().endsWith(ss); } }; list = (new File(".")).listFiles(ff); } for (int i = 0; i<list.length; ++i) { //System.out.println("DELETING " +list[i].getName()); list[i].delete(); } } }
GaloisInc/JavaFE
Utils/junitutils/Utils.java
249,740
// Reece Yang // // This class simulates a simplified version of the Iowa Lottery Game. package U5A2; public class Lottery { private int[] numbers; private int powerBall; public Lottery() { numbers = new int[5]; powerBall = (int)(35 * Math.random() + 1); int[] choices = new int[59]; for (int i = 0; i < 59; i++) { choices[i] = i + 1; } int n; // fill numbers array for (int i = 0; i < 5; i++) { do { n = (int)(59 * Math.random()); } while (choices[n] == 0); numbers[i] = choices[n]; choices[n] = 0; } } public int check(int[] nums, int pb) { int matches = 0; int won = 0; // if the powerball matches if (pb == powerBall) { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (numbers[i] == nums[j]) { matches++; } } } switch (matches) { case 5: won = 1000000; break; case 4: won = 10000; break; case 3: won = 100; break; case 2: won = 7; break; case 1: won = 4; break; case 0: won = 4; break; } } else { // if the powerball doesn't match for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (numbers[i] == nums[j]) { matches++; } } } switch (matches) { case 5: won = 500000; break; case 4: won = 100; break; case 3: won = 7; break; } } return won; } public int[] getNumbers() { return numbers; } public int getPowerBall() { return powerBall; } }
reeceyang/AP-Computer-Science
src/U5A2/Lottery.java
249,743
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Hridesh Rajan */ package lib; public class CharC { char v; public CharC(char v) { this.v = v; } public char value() { return v; } }
hridesh/panc
examples/KWIC/lib/CharC.java
249,744
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): */ class Bool { private boolean v; public Bool(boolean v) { this.v = v; } public boolean value() { return v; } } capsule Fork () { boolean isTaken = false; Bool take() { if (isTaken) return new Bool(false); else { isTaken = true; return new Bool(true); } } void giveBack() { isTaken = false; } } capsule Philosopher (Fork left, Fork right, String name) { void act() { for (int count=3; count>0; count--) { think(); tryEat(); } } private void think() { System.out.println(name + " is thinking"); yield(1000); } private void tryEat() { System.out.println(name + " is hungry so they are trying to take fork 1."); boolean ate = false; while (!ate) { if (left.take().value()) { System.out.println(name + " acquired fork 1 so now they are trying to take fork 2."); if (right.take().value()) { System.out.println(name + " acquired both forks so now they are eating."); for (int eat = 0, temp=0; eat < 10000; eat++) temp = eat * eat * eat * eat; ate = true; right.giveBack(); } left.giveBack(); if(!ate) yield(100); } } } } capsule Philosophers { design { Fork f1, f2, f3; Philosopher p1, p2, p3; p1(f1,f2, "Aristotle"); p2(f2,f3, "Demosthenes"); p3(f3,f1, "Socrates"); } void run() { p1.act(); p2.act(); p3.act(); } }
hridesh/panc
examples/Philosophers.java
249,746
import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; public class BlockPermutedSimhash { String folder; private List<char[]> table = new ArrayList<char[]>(); Simhash simhash; HashMap<Integer, Integer> similar = new HashMap<Integer, Integer>(); public BlockPermutedSimhash(String folder) { this.folder = folder; simhash = new Simhash(folder); } private void blockPermutation() { table = simhash.fingerprint(); compareAdjacent(table); for (int i = 0; i < 31; i += 2) { for (int j = 0; j < table.size(); j++) { table.set(j, rotateLeft(table.get(j), 2)); } compareAdjacent(table); } } private char[] rotateLeft(char[] t, int rotation) { if (rotation == 0) return t; char temp1, temp2; temp1 = t[0]; temp2 = t[1]; for (int i = 2; i < t.length; i++) { t[i - 2] = t[i]; } t[t.length - 2] = temp1; t[t.length - 1] = temp2; return t; } private void compareAdjacent(List<char[]> table) { System.out.println("--------------------"); List<Fingerprint> t = new ArrayList<Fingerprint>(); for (int i = 0; i < table.size(); i++) { BigInteger b = new BigInteger(new String(table.get(i)), 2); t.add(new Fingerprint(i, b)); // System.out.println(new String(table.get(i)) + " " + b); } Collections.sort(t, new Comparator<Fingerprint>() { public int compare(Fingerprint c1, Fingerprint c2) { return c1.hashValue.compareTo(c2.hashValue); } }); for (int i = 0; i < t.size() - 1; i++) { int index1 = t.get(i).getIndex(); int index2 = t.get(i + 1).getIndex(); int distance = simhash.hammingDistance(table.get(index1), table.get(index2)); if (distance < 7) { if (!((similar.containsKey(index1) && similar.get(index1).equals(index2) || (similar.containsKey(index2) && similar.get(index2).equals(index1))))) { similar.put(index1, index2); System.out.println(simhash.filenames[index1] + " " + simhash.filenames[index2] + " " + distance); } } } System.out.println(similar.size()); } private List<String> createPermutation(int G) { List<String> blocks = new ArrayList<String>(); for (int i = 1; i <= G; i++) { for (int j = i + 1; j <= G; j++) { for (int k = j + 1; k <= G; k++) { blocks.add(i + "" + j + "" + k); } } } return blocks; } public static void main(String[] args) { long startTime = 0, stopTime = 0; startTime = System.nanoTime(); double time = 0; BlockPermutedSimhash blockPermutedSimhash = new BlockPermutedSimhash( "/Users/sumon/IOWA STATE UNIVERSITY/Fall 17/CPR E 528/Project/Dataset/space"); blockPermutedSimhash.blockPermutation(); stopTime = System.nanoTime(); time = (double) (stopTime - startTime) / 1000000000.0; System.out.println("Time: " + time+ " sec."); } } class Fingerprint { int index; BigInteger hashValue; public Fingerprint(int index, BigInteger hashValue) { this.index = index; this.hashValue = hashValue; } public int getIndex() { return index; } public BigInteger getHashValue() { return hashValue; } }
sumonbis/NearDuplicateDetection
BlockPermutedSimhash.java
249,749
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Rex Fernando, Eric Lin */ class BooleanC { boolean v; public BooleanC(boolean v) { this.v = v; } public boolean value() { return v; } } capsule Barber(WaitingRoom r) { boolean isSleeping = false; void wake(){ isSleeping = false; System.out.println("Barber Woke up"); work(); while (r.leave().value()) { work(); } sleep(); } void sleep(){ System.out.println("Barber went to sleep"); isSleeping = true; } void work(){ System.out.println("Barber working"); yield(1000); } BooleanC isSleeping(){ return new BooleanC(isSleeping); } } capsule WaitingRoom(int queue, int cap) { BooleanC sit(){ if (queue<cap) { queue++; System.out.println("Sitting in waiting room"); return new BooleanC(true); } else return new BooleanC(false); } BooleanC leave(){ if(queue>0){ queue--; return new BooleanC(true); } else return new BooleanC(false); } } capsule Customers(Barber b, WaitingRoom r) { void generate() { for (int numCustomers=1; numCustomers <=5; numCustomers++) { System.out.println("Customer wants haircut"); if (!b.isSleeping().value()) { trySit(); } else { System.out.println("Customer is waking barber up"); b.wake(); } yield(1000); } } void trySit(){ System.out.println("Barber is busy, trying to sit down"); if(!r.sit().value()) { System.out.println("Waiting room is full, so leaving"); } } } capsule Barbershop { design { Barber b; WaitingRoom w; Customers cs[5]; b(w); w(0, 10); wireall(cs, b, w); } void run() { for(Customers c: cs) c.generate(); } }
hridesh/panc
examples/Barbershop.java
249,750
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Hridesh Rajan */ package lib; public class Strings { String[] v; public Strings(String[] v) { this.v = v; } public String[] value() { return v; } }
hridesh/panc
examples/KWIC/lib/Strings.java
249,752
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Hridesh Rajan */ /*** * Classic KWIC system using the Panini language * * This implementation of the KWIC system is based on the example * presented in the following paper. * D. L. Parnas. 1972. On the criteria to be used in decomposing systems * into modules. Commun. ACM 15, 12 (December 1972), 1053-1058. * DOI=10.1145/361598.361623 http://doi.acm.org/10.1145/361598.361623 * */ /** * The Control capsule controls all other capsules in the KWIC system * to achieve the desired functionality. */ capsule Control (){ design { LineStorage lines; LineStorage shifts; Input input; CircularShifter shifter; Alphabetizer alphabetizer; Output output; Control control; String file = "../shaks12.txt"; alphabetizer(shifter); shifter(lines,shifts); input(lines); output(alphabetizer); } /** * Parses the data, makes shifts and sorts them. At the end prints the * sorted shifts. * @param file name of the input file */ void run(){ input.parse(file); shifter.setup(lines); alphabetizer.alpha(); output.print(); } /** * Main function checks the command line arguments. The program expects * exactly one command line argument specifying the name of the file * that contains the data. If the program has not been started with * proper command line arguments, main function exits * with an error message. Otherwise, a KWIC instance is created and program * control is passed to it. * @param args command line arguments */ public static void main(String[] args){ if(args.length != 1){ System.err.println("KWIC Usage: java kwic.ms.KWIC file_name"); System.exit(1); } KWIC kwic = new KWIC(); kwic.execute(args[0]); } }
hridesh/panc
examples/KWIC/KWIC.java
249,753
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Hridesh Rajan */ /*** * This Panini program illustrates the use of a distributor pattern * in capsule-oriented programming to implement facilities similar * to a task pool. The program itself implements a simple recursive * computation of a fibonacci number. */ signature Worker { Number execute(int num); } capsule FibWorker (Worker w) implements Worker { Number execute(int n) { if (n < 2) return new Number(n); if (n < 13) return new Number(helper(n)); return new Sum (w.execute(n-1), w.execute(n-2)); } private int helper(int n) { int prev1=0, prev2=1; for(int i=0; i<n; i++) { int savePrev1 = prev1; prev1 = prev2; prev2 = savePrev1 + prev2; } return prev1; } } capsule Distributor (Worker[] workers) implements Worker { int current = 0; Number execute(int num) { Number result = workers[current].execute(num); current++; if(current == workers.length) current = 0; return result; } } capsule Fibonacci (String[] args) { design { FibWorker workers[10]; Distributor d; d(workers); wireall(workers, d); } void run(){ try { System.out.println(d.execute(Integer.parseInt(args[0])).v()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { System.out.println("Usage: panini Fibonacci <Number>"); } } } class Number { int number; Number(int number){ this.number = number; } int v(){ return number;} public String toString() { return "" + number; } } class Sum extends Number { Number left; Number right; Sum(Number left, Number right){ super(0); this.left = left; this.right = right; } @Override int v() { return left.v() + right.v(); } }
hridesh/panc
examples/Fibonacci.java
249,754
import java.io.File; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class Simhash { private static final int HASHLENGTH = 64; private final String FOLDER; private HashMap<String, Integer> dictionary = new HashMap<String, Integer>(); public String[] filenames; HashMap<String, List<Word>> vectors = new HashMap<String, List<Word>>(); public Simhash(String folder) { this.FOLDER = folder; createDictionary(); } private void createDictionary() { filenames = allDocs(); int count = 0; System.out.print("Loading data.."); for (int i = 0; i < filenames.length; i++) { if (i % 100 == 0) System.out.println("."); vectors.put(filenames[i], new ArrayList<Word>()); HashMap<String, Integer> words = getAllWords(filenames[i]); for (String w : words.keySet()) { if (!dictionary.containsKey(w)) { dictionary.put(w, count); count++; } vectors.get(filenames[i]).add(new Word(dictionary.get(w), words.get(w))); } } // System.out.println(dictionary); } public String[] allDocs() { File[] files = getAllFiles(FOLDER); List<String> results = new ArrayList<String>(); for (File file : files) { if (file.isFile()) { results.add(file.getName()); } } String[] fileNameArray = new String[results.size()]; fileNameArray = results.toArray(fileNameArray); if (fileNameArray.length < 1) { System.out.println("Error: No file in the specified directory."); System.exit(0); } return fileNameArray; } // Get all the files from the given directory path private File[] getAllFiles(String path) { File[] allFiles = new File(path).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return !name.equals(".DS_Store"); } }); return allFiles; } // Returns array of processed words in lowercase from the given file private HashMap<String, Integer> getAllWords(String file) { Scanner s; HashMap<String, Integer> words = new HashMap<String, Integer>(); try { s = new Scanner(new File(FOLDER + "/" + file), "ISO-8859-1"); while (s.hasNext()) { String w = s.next().replaceAll("[.,:;’']", "").toLowerCase(); if (w.length() < 3 || w.equals("the")) continue; if (!words.containsKey(w)) { words.put(w, 1); } else { words.put(w, words.get(w) + 1); } } s.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } return words; } public double exactJaccard(String file1, String file2) { double exactJaccard; //System.out.println(file1 + " " + file2); List<Integer> wordsFile1 = new ArrayList<Integer>(); List<Integer> wordsFile2 = new ArrayList<Integer>(); List<Word> words1 = vectors.get(file1); List<Word> words2 = vectors.get(file2); //System.out.println("he " + words1); for (Word w : words1) { wordsFile1.add(w.getWord()); //System.out.print("hi " + w.getWord() + " "); } for (Word w : words2) { wordsFile2.add(w.getWord()); } Set<Integer> unionSet = new HashSet<Integer>(); // remove duplicates unionSet.addAll(wordsFile1); unionSet.addAll(wordsFile2); exactJaccard = (double) (wordsFile1.size() + wordsFile2.size() - unionSet.size()) / unionSet.size(); return exactJaccard; } public double exactCosine(String file1, String file2) { double exactCosine; List<Integer> wordsFile1 = new ArrayList<Integer>(); List<Integer> wordsFile2 = new ArrayList<Integer>(); List<Word> words1 = vectors.get(file1); List<Word> words2 = vectors.get(file2); for (Word w : words1) { wordsFile1.add(w.getWord()); } for (Word w : words2) { wordsFile2.add(w.getWord()); } Set<Integer> unionSet = new HashSet<Integer>(); // remove duplicates unionSet.addAll(wordsFile1); unionSet.addAll(wordsFile2); exactCosine = (double) (wordsFile1.size() + wordsFile2.size() - unionSet.size()) / Math.sqrt(wordsFile1.size() * wordsFile2.size()); return exactCosine; } public char[] simhashSignature(String fileName) { char[] sig = new char[HASHLENGTH]; int[] temp = new int[HASHLENGTH]; for (Word w : vectors.get(fileName)) { int wrd = w.getWord(); int freq = w.getfrequency(); long wordHash = MurmurHash.hash64(Integer.toString(wrd)); char[] wh = String.format("%064d", new BigInteger(Long.toBinaryString(wordHash))).toCharArray(); for (int i = 0; i < wh.length; i++) { if (wh[i] == '1') temp[i] += freq; else temp[i] -= freq; } } for (int i = 0; i < HASHLENGTH; i++) { if (temp[i] < 0) sig[i] = '0'; else sig[i] = '1'; } // System.out.println(sig.size); return sig; } // approximateCosine public double approximateCosine(String file1, String file2) { char[] sig1 = simhashSignature(file1); char[] sig2 = simhashSignature(file2); int distance = hammingDistance(sig1, sig2); double similarity = 1 - ((double) distance / HASHLENGTH); return similarity; } public int hammingDistance(char[] sig1, char[] sig2) { int count = 0; for (int i = 0; i < sig1.length; i++) { if (sig1[i] != sig2[i]) count++; } return count; } public List<char[]> fingerprint() { //HashMap<String, char[]> table = new HashMap<String, char[]>(); List<char[]> table = new ArrayList<char[]>(); for (int i =0; i<filenames.length;i++) { char[] sig = simhashSignature(filenames[i]); table.add(sig); //System.out.println(sig); } return table; } public int numTerms() { return dictionary.size(); } public static void main(String[] args) { Simhash simhash = new Simhash("/Users/sumon/IOWA STATE UNIVERSITY/Fall 17/CPR E 528/Project/Dataset/Space"); System.out.println(simhash.exactJaccard("space-771.txt", "space-753.txt")); System.out.println(simhash.exactCosine("space-771.txt", "space-753.txt")); System.out.println(simhash.approximateCosine("space-771.txt", "space-753.txt")); //simhash.fingerprint(); } } class Word { private int word, frequency; public Word(int word, int frequency) { this.word = word; this.frequency = frequency; } public int getWord() { return word; } public int getfrequency() { return frequency; } }
sumonbis/NearDuplicateDetection
Simhash.java
249,756
package dataaccess; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import classes.Address; import classes.*; public class Main { public static void main(String[] args) { User user = new User("ali", "ali123", UserRole.ADMIN); User user2 = new User("john", "john123", UserRole.LIBRARIAN); Address add = new Address("1000N", "Fairfield", "Iowa", 52557); //Members Member mmbr1 = new Member("Ali", "Ahmadi", add, "641-451-3308"); Member mmbr2 = new Member("John", "Doe", add, "641-451-3309"); Member mmbr3 = new Member("Bob", "Artist", add, "641-451-3307"); Member mmbr4 = new Member("Mike", "Jackson", add, "641-451-3306"); //System.out.println(mmbr1); //Authors Author author1 = new Author(1, "Donald", "Trump", add, "641-451-3305", "Phd", "Nobel Prize Holder"); List<Author> authors = new ArrayList<>(); authors.add(author1); //Books Book book1 = new Book("Algorithm", "ISBN-111111", authors, 3, 21); Book book2 = new Book("Mathematic", "ISBN-222222", authors, 3, 21); Book book3 = new Book("Data science", "ISBN-333333", authors, 1, 21); Book book4 = new Book("Physics", "ISBN-444444", authors, 1, 21); Book Periodical1 = new Book("Fashion Magazin", "ISBN-555555", authors, 2, 7); Book Periodical2 = new Book("Art Magazin", "ISBN-666666", authors, 2, 7); Book Periodical3 = new Book("Society Magazin", "ISBN-777777", authors, 2, 7); //System.out.println(book1); //Checkout CheckoutRecord checkout1 = new CheckoutRecord(1, mmbr1, book1.checkout()); CheckoutRecord checkout2 = new CheckoutRecord(2, mmbr1, Periodical1.checkout()); CheckoutRecord checkout3 = new CheckoutRecord(3, mmbr2, book2.checkout()); CheckoutRecord checkout4 = new CheckoutRecord(4, mmbr2, Periodical1.checkout()); CheckoutRecord checkout5 = new CheckoutRecord(5, mmbr3, book3.checkout(), LocalDate.of(2018, 01, 01)); CheckoutRecord checkout6 = new CheckoutRecord(6, mmbr3, Periodical2.checkout()); CheckoutRecord checkout7 = new CheckoutRecord(7, mmbr4, book4.checkout()); CheckoutRecord checkout8 = new CheckoutRecord(8, mmbr4, Periodical3.checkout(), LocalDate.of(2019, 01, 01)); //System.out.println(checkout1); //DataAccess DataAccess da = new DataAccessFacade(); da.saveMember(mmbr1); da.saveMember(mmbr2); da.saveMember(mmbr3); da.saveMember(mmbr4); da.saveBook(book1); da.saveBook(book2); da.saveBook(book3); da.saveBook(book4); da.saveBook(Periodical1); da.saveBook(Periodical2); da.saveBook(Periodical3); da.saveCheckoutRecord(checkout1); da.saveCheckoutRecord(checkout2); da.saveCheckoutRecord(checkout3); da.saveCheckoutRecord(checkout4); da.saveCheckoutRecord(checkout5); da.saveCheckoutRecord(checkout6); da.saveCheckoutRecord(checkout7); da.saveCheckoutRecord(checkout8); da.saveUser(user); da.saveUser(user2); HashMap<Integer, Member> members = da.readMembers(); System.out.println(members); HashMap<String, Book> books = da.readBooks(); System.out.println(books); HashMap<Integer, CheckoutRecord> records = da.readCheckoutRecords(); System.out.println(records); HashMap<String, User> users = da.readUsers(); System.out.println(users); } }
aliahmadi4/LibraryManagementSystem
src/dataaccess/Main.java
249,759
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org/ * * Contributor(s): Hridesh Rajan */ import AILib.*; capsule CrossOver (float probability) { Generation compute(Generation g) { int genSize = g.size(); Generation g1 = new Generation(g); for (int i = 0; i < genSize; i += 2) { Parents p = g.pickParents(); g1.add( p.tryCrossOver(probability) ); } return g1; } } capsule Mutation (float probability) { Generation mutate(Generation g) { int genSize = g.size(); Generation g1 = new Generation(g); for (int i = 0; i < genSize; i += 2) { Parents p = g.pickParents(); g1.add( p.tryMutation(probability)); } return g1; } } capsule Fittest { Generation last = null; void check(Generation g) { if(last ==null) last = g; else { Fitness f1 = g.getFitness(); Fitness f2 = last.getFitness(); if( f1.average() > f2.average() ) last = g; } } Fitness bestFitness() { return last.getFitness(); } } capsule Logger { void logit(Generation g) { logGeneration(g); } long generationNumber = 0; void logGeneration(Generation g){ Fitness f = g.getFitness(); System.out.println("Generation #"+(generationNumber++) + ": Fitness = " + f.average() + " (avg), " + f.maximum() + " (max)."); } void log(String msg) { System.out.println(msg); } } capsule GA (String[] args) { design { CrossOver c; Mutation m; Fittest f; Logger l ; c(0.9f); m(0.0001f); } private int maxDepth() { if (args.length < 1) { return 6; //default; } else { return Integer.parseInt(args[0]); } } void run() { Individual individual = new BooleanIndividual(); Generation g = new Generation(100, individual); l.logit(g); explore(g, 0, maxDepth()); //Initial generation, initial depth, max iterations. Fitness fitness = f.bestFitness(); float avgFitness = fitness.average(); float maxFitness = fitness.maximum(); l.log("Final Results: Fitness " + avgFitness + "(avg), " + maxFitness + " (max)."); } private void explore (Generation g, int depth, int maxIteration) { if (depth > maxIteration) return; Generation g1 = c.compute(g); Generation g2 = m.mutate(g); explore(g1, depth + 1, maxIteration); explore(g2, depth + 1, maxIteration); f.check(g1); f.check(g2); l.logit(g1); l.logit(g2); } }
hridesh/panc
examples/GA/GA.java
249,760
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Hridesh Rajan */ /*** * A simple example of a pipeline architecture in the Panini language * * This pipeline is organized as: * Source -> Average -> Sum -> Min -> Max -> Sink * * Here, capsule Source generates a set of random numbers, * capsule Average maintains a running average, capsule Sum maintains * a running total, and the Sink reports that a number has been * processed by the pipeline. * */ import java.util.Random; signature Stage { void consume(long n); } capsule Average (Stage next) implements Stage { long average = 0; long count = 0; void consume(long n) { next.consume(n); if (n != -1) { average = ((count * average) + n) / (count + 1); count++; } else System.out.println("Average of " + count + " numbers was " + average + "."); } } capsule Sum (Stage next) implements Stage { long sum = 0; void consume(long n) { next.consume(n); if (n != -1) { sum += n; } else System.out.println("Sum of numbers was " + sum + "."); } } capsule Min (Stage next) implements Stage { long min = Long.MAX_VALUE; void consume(long n) { next.consume(n); if (n != -1) { if(n < min) min = n; } else System.out.println("Min of numbers was " + min + "."); } } capsule Max (Stage next) implements Stage { long max = 0; void consume(long n) { next.consume(n); if (n != -1) { if ( n > max) max = n; } else System.out.println("Max of numbers was " + max + "."); } } capsule Sink(long num) implements Stage { long count = 0; void consume(long n) { if (n != -1) { count++; } else System.out.println("Successful " + count + " runs!!"); } } capsule Pipeline { design { Average avg; Sum sum; Min min; Max max; Sink snk; avg(sum); sum(min); min(max); max(snk); snk(500); } Random prng = new Random (); void run() { for (int j = 0; j < 500; j++) { long n = prng.nextInt(1024); avg.consume(n); } avg.consume(-1); yield(2); } }
hridesh/panc
examples/Pipeline.java
249,761
package src.StartMenu; import src.UI.UIUtils; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class StartPanel extends JPanel { /** * This is the start screen to display first. */ public StartPanel(Frame frame) { super(); BoxLayout boxLayout = new BoxLayout(this, BoxLayout.Y_AXIS); setLayout(boxLayout); setSize(frame.getSize()); JLabel title = UIUtils.addTitle("Iowa State University", new Font(Font.SANS_SERIF, Font.BOLD, 50),this); title.setForeground(new Color(250, 180, 0)); add(createBackgroundImage()); setAlignmentX(CENTER_ALIGNMENT); add(createStartButton(frame)); } private JLabel createBackgroundImage() { BufferedImage imageResource; try { imageResource = ImageIO.read(new File("CSEClubLogo.png")); } catch (IOException e) { throw new RuntimeException(e); } JLabel image = new JLabel(new ImageIcon(imageResource)); image.setAlignmentX(CENTER_ALIGNMENT); return image; } private JButton createStartButton(Frame frame) { JButton startButton = new JButton("Start Program"); startButton.setVerticalTextPosition(AbstractButton.CENTER); startButton.setAlignmentX(CENTER_ALIGNMENT); startButton.setAlignmentY(BOTTOM_ALIGNMENT); startButton.addActionListener((l) -> frame.showGameList()); startButton.setForeground(Color.white); startButton.setBackground(new Color(140, 0, 0)); startButton.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); startButton.setFocusPainted(false); startButton.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20)); startButton.setForeground(new Color(255, 255, 200)); return startButton; } @Override protected void paintComponent(Graphics g) { } }
CSE-Club-ISU/STEM-Programs
src/StartMenu/StartPanel.java
249,762
package com.rexprog.audiowaveseekbar; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.os.Build; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class AudioWaveSeekBar extends View { private static Paint paintInner; private static Paint paintOuter; private int width; private int height; private float startX; private int thumbX = 0; private View parentView; private Context context; private int thumbDX = 0; private byte[] waveformBytes; private boolean pressed = false; private boolean startDragging = false; private SeekBarChangeListener seekBarChangeListener; private int innerColor = 0xffafbcd7; private int outerColor = 0xff3b5998; private int pressedColor = 0xffa7b8dc; private int duration; public AudioWaveSeekBar(Context context) { this(context, null); } public AudioWaveSeekBar(Context context, AttributeSet attrs) { this(context, attrs, 0); } public AudioWaveSeekBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; if (paintInner == null) { paintInner = new Paint(); paintOuter = new Paint(); } } public static float dip2px(Context context, float dp) { return dp * context.getResources().getDisplayMetrics().density; } public static float px2cm(Context context, float cm) { return (cm / 2.54f) * context.getResources().getDisplayMetrics().density; } public void setOnSeekBarChangeListener(SeekBarChangeListener seekBarDelegate) { seekBarChangeListener = seekBarDelegate; } public void setColors(int inner, int outer, int selected) { innerColor = inner; outerColor = outer; pressedColor = selected; } public void setWaveform(byte[] waveform) { waveformBytes = waveform; invalidate(); } public void setProgress(float progress) { if (duration != 0) progress = progress / duration; else progress = 0; thumbX = (int) Math.ceil(width * progress); if (thumbX < 0) { thumbX = 0; } else if (thumbX > width) { thumbX = width; } invalidate(); } public void setParentView(View view) { parentView = view; } public void setDuration(int duration) { this.duration = duration; } public void setSize(int w, int h) { width = w; height = h; invalidate(); } @Override public boolean onTouchEvent(MotionEvent event) { boolean result = onTouch(event.getAction(), event.getX(), event.getY()); if (result) invalidate(); return result || super.onTouchEvent(event); } public boolean onTouch(int action, float x, float y) { if (action == MotionEvent.ACTION_DOWN) { if (0 <= x && x <= width && y >= 0 && y <= height) { startX = x; pressed = true; thumbDX = (int) (x - thumbX); startDragging = false; return true; } } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { if (pressed) { if (action == MotionEvent.ACTION_UP && seekBarChangeListener != null) { seekBarChangeListener.OnSeekBarChangeListener((int) (((float) thumbX / (float) width) * duration)); } pressed = false; return true; } } else if (action == MotionEvent.ACTION_MOVE) { if (pressed) { if (startDragging) { thumbX = (int) (x - thumbDX); if (thumbX < 0) { thumbX = 0; } else if (thumbX > width) { thumbX = width; } } if (startX != -1 && Math.abs(x - startX) > px2cm(context, 0.2f)) { if (parentView != null && parentView.getParent() != null) { parentView.getParent().requestDisallowInterceptTouchEvent(true); } startDragging = true; startX = -1; } return true; } } return false; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); setSize(right - left, bottom - top); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (waveformBytes == null || width == 0) { return; } float totalBarsCount = width / dip2px(context, 3); if (totalBarsCount <= 0.1f) return; int max = waveformBytes[0]; int min = waveformBytes[0]; for (int i = 1; i < waveformBytes.length; i++) { if (waveformBytes[i] > max) max = waveformBytes[i]; if (waveformBytes[i] < min) min = waveformBytes[i]; } int samplesCount = waveformBytes.length; float samplesPerBar = samplesCount / totalBarsCount; float barCounter = 0; int nextBarNum = 0; paintInner.setColor(pressed ? pressedColor : innerColor); paintOuter.setColor(outerColor); int barNum = 0; int lastBarNum; int drawBarCount; for (int a = 0; a < samplesCount; a++) { if (a != nextBarNum) { continue; } drawBarCount = 0; lastBarNum = nextBarNum; while (lastBarNum == nextBarNum) { barCounter += samplesPerBar; nextBarNum = (int) barCounter; drawBarCount++; } int value = (waveformBytes[a] - min) % (max + 1); for (int b = 0; b < drawBarCount; b++) { float x = barNum * dip2px(context, 4); if (x < thumbX && x + dip2px(context, 3) < thumbX) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) canvas.drawRoundRect(x, height - Math.max(dip2px(context, 3), height * value / max), x + dip2px(context, 3), height, 50, 50, paintOuter); else canvas.drawRect(x, height - Math.max(dip2px(context, 3), height * value / max), x + dip2px(context, 3), height, paintOuter); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) canvas.drawRoundRect(x, height - Math.max(dip2px(context, 3), height * value / max), x + dip2px(context, 3), height, 50, 50, paintInner); else canvas.drawRect(x, height - Math.max(dip2px(context, 3), height * value / max), x + dip2px(context, 3), height, paintInner); if (x < thumbX) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) canvas.drawRoundRect(x, height - Math.max(dip2px(context, 3), height * value / max), thumbX, height, 50, 50, paintOuter); else canvas.drawRect(x, height - Math.max(dip2px(context, 3), height * value / max), thumbX, height, paintOuter); } } barNum++; } } } public interface SeekBarChangeListener { void OnSeekBarChangeListener(int progress); } }
PuzzleTakX/PuzzleTak_AudioWaveSeekBar
main/pt.java
249,763
import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.io.SyndFeedInput; import com.sun.syndication.io.XmlReader; import java.net.URL; import java.util.Random; public class NewsPoster implements Runnable{ private long timeStart; public NewsPoster(){ this.timeStart = System.currentTimeMillis(); } public void postNews() { try { String[] cities = {"quebec", "toronto", "warsaw", "amsterdam", "rotterdam", "riga", "oslo", "stockholm", "prague", "sydney", "london", "berlin", "beijing", "delhi", "tokyo", "california", "iowa", "zurich", "geneva"}; var random = new Random(); URL feedSource = new URL("https://news.google.com/news/rss/headlines/section/geo/" + cities[random.nextInt(cities.length - 1)]); SyndFeedInput input = new SyndFeedInput(); SyndFeed feed = input.build(new XmlReader(feedSource)); for (var o : feed.getEntries()) { SyndEntry entry = (SyndEntry) o; var tweeter = new Tweeter(); tweeter.setTweet(entry.getTitle() + " " + entry.getLink()); tweeter.postTweet(); break; } } catch (Exception e) { e.printStackTrace(); System.err.println(e); } } @Override public void run() { while(true) { if (System.currentTimeMillis() - timeStart > 60000) { var newsPoster = new NewsPoster(); newsPoster.postNews(); timeStart = System.currentTimeMillis(); } } } }
assemblu/TwitterBot
src/NewsPoster.java
249,764
package ex3; public class Person { private String name; private int id; private static int uniqueid = 0; public Person(String name) { this.name = name; id = uniqueid; uniqueid++; //System.out.println("this person's id is" + this.id); } public int getid() { return id; } public String toString() { return "Person " + name + " with id " + id; } //this method should ideally be in a seperate class public static void main(String[] args) { Person Jim= new Person("Jim"); Person Sarah= new Person("Sarah"); Person Rachel= new Person("Rachel"); Quarantine Galesburg= new Quarantine(); Quarantine Iowa= new Quarantine(); Galesburg.addPerson(Jim); //adds Jim once to city Iowa.addPerson(Jim); //adds Jim to state Iowa.addPerson(Rachel);//adds Rachel to state Galesburg.addPerson(Jim);//add Jim again to Galesburg System.out.println(Galesburg);//prints out Jim only once and does not repeat System.out.println(Iowa); } }
shuja-waraich-03/HW_CodeReviews
src/ex3/Person.java
249,765
package main; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.UIManager; import edu.mum.account.Account; import edu.mum.account.AccountFactory; import edu.mum.account.IAccount; import edu.mum.client.ClientFactory; import edu.mum.client.IClient; import edu.mum.entry.DepositOperation; import edu.mum.entry.Entry; import edu.mum.entry.OperationManager; import edu.mum.entry.WithdrawOperation; import edu.mum.gui.Gui; public class FinCo { protected Map<String, IAccount> accounts = new HashMap<>(); protected List<IClient> clients = new ArrayList<>(); protected OperationManager opManager = new OperationManager(); public FinCo(){ setup(); // printAccounts(); } public static void main(String[] args) { try { // Add the following code if you want the Look and Feel // to be set to the Look and Feel of the native system. try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } //Create a new instance of our application's frame, and make it visible. (new Gui(new FinCo())).setVisible(true); } catch (Throwable t) { t.printStackTrace(); //Ensure the application exits with an error condition. System.exit(1); } } public void addAccountToList(IAccount account) { accounts.put(account.getAccountNo(), account); } public void addClientToList(IClient client) { clients.add(client); } public void setup(){ //Creating clients and accounts IClient[] client = new IClient[5]; client[0] = ClientFactory.createPerson("Keng","4th", "Fairfield", "Iowa", "34242", "[email protected]", new Date()); client[1] = ClientFactory.createPerson("John","4th street", "Des Moines", "Iowa", "34242", "[email protected]", new Date()); client[2] = ClientFactory.createPerson("Jimmy Kon","Nevile 3rd", "Chicago", "Illinois", "367676", "[email protected]", new Date()); client[3] = ClientFactory.createOrganization("Finco Ltd","1000N 4th", "Fairfield", "Iowa", "34242", "[email protected]", 12); client[4] = ClientFactory.createOrganization("Getnet Info","Burlington", "Washington DC", "Washington", "89876", "[email protected]", 5); int i=1; StringBuilder prefix = new StringBuilder("2224"); for(IClient c:client){ this.addClientToList(c); IAccount acc = new Account(c,prefix.append(i++).toString()); c.addAccount(acc); this.addAccountToList(acc); prefix.deleteCharAt(prefix.length()-1); } } //Create personal account public IAccount createAccountForPerson(String name,String street,String city, String state, String zip, String email, Date birthDate,String accountNo, AccountFactory factory) { IClient client = ClientFactory.createPerson(name, street, city, state, zip, email, birthDate); if(client != null) { addClientToList(client); IAccount acc = factory.createAccount(client, accountNo); client.addAccount(acc); return acc; } return null; } //Create organizational account public IAccount createAccountForOrganization(String name,String street,String city, String state, String zip, String email, int noOfEmployees,String accountNo,AccountFactory factory) { IClient client = ClientFactory.createOrganization(name, street, city, state, zip, email, noOfEmployees); if(client != null) { addClientToList(client); IAccount acc = factory.createAccount(client, accountNo); client.addAccount(acc); return acc; } return null; } public void printAccounts() { Set<String> accNos = accounts.keySet(); for(String no:accNos) { IAccount acc = accounts.get(no); System.out.println(acc); } } //Depositing public double depositing(String accountNo,double amount) { //Get account IAccount account = accounts.get(accountNo); //Create deposit operation and submit it. opManager.submit(new DepositOperation(account,new Entry(new Date(),amount))); return account.getBalance(); } //Withdrawing public double withdrawing(String accountNo,double amount) { IAccount account = accounts.get(accountNo); opManager.submit(new WithdrawOperation(account,new Entry(new Date(),amount))); return account.getBalance(); } //Getters public Map<String, IAccount> getAccounts() { return accounts; } public List<IClient> getClients() { return clients; } }
kengsrengtang/FinCO_Framework
src/main/FinCo.java
249,766
public enum State { alabama, alaska, arizona, arkansas, california, colorado, connecticut, delaware, florida, georgia, hawaii, idaho, illinois, nebraska, nevada, hampshire, jersey, mexico, york, carolina, dakota, ohio, oklahoma, oregon, pennsylvania, indiana, iowa, kansas, kentucky, louisiana, maine, maryland, massachusetts, michigan, minnesota, mississippi, missouri, montana, rhodeisland, tennessee, texas, utah, vermont, virginia, washington, wisconsin, wyoming }
ArelySkywalker/Java
Ashbot-master 2/src/State.java
249,768
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Eric Lin, Rex Fernando */ class DoubleC { double v; public DoubleC(double v) { this.v = v; } public double value() { return v; } } class IntC { int v; public IntC(int v) { this.v = v; } public int value() { return v; } } capsule Body (Body[] bodies, double x, double y, double vx, double vy, double m, double dt) { void calcNextV(IntC start) { System.out.println("start calculating the next V"); for (int i = start.value(); i < bodies.length; i++) { double dx = x - bodies[i].getX().value(); double dy = y - bodies[i].getX().value(); double dSquared = dx * dx + dy * dy; double distance = Math.sqrt(dSquared); double mag = dt / (dSquared * distance); vx -= dx * bodies[i].getM().value() * mag; vy -= dy * bodies[i].getM().value() * mag; bodies[i].incrVX(new DoubleC(dx * m * mag)); bodies[i].incrVY(new DoubleC(dy * m * mag)); } } void step() { x += dt * vx; y += dt * vy; } DoubleC getX() {return new DoubleC(x);} DoubleC getY() {return new DoubleC(y);} DoubleC getVX() {return new DoubleC(vx);} DoubleC getVY() {return new DoubleC(vy);} DoubleC getM() {return new DoubleC(m);} void incrVX(DoubleC v) {vx = v.value();} void incrVY(DoubleC v) {vy = v.value();} } capsule Nbody { design { Body b[5]; double SOLAR_MASS = 4 * Math.PI * Math.PI; double DAYS_PER_YEAR = 365.24; // jupiter b[0](b, 4.84143144246472090e+00, -1.16032004402742839e+00, 1.66007664274403694e-03 * DAYS_PER_YEAR, 7.69901118419740425e-03 * DAYS_PER_YEAR, 9.54791938424326609e-04 * SOLAR_MASS, 0.01); // saturn b[1](b, 8.34336671824457987e+00, 4.12479856412430479e+00, -2.76742510726862411e-03 * DAYS_PER_YEAR, 4.99852801234917238e-03 * DAYS_PER_YEAR, 2.85885980666130812e-04 * SOLAR_MASS, 0.01); // uranus b[2](b, 1.28943695621391310e+01, -1.51111514016986312e+01, 2.96460137564761618e-03 * DAYS_PER_YEAR, 2.37847173959480950e-03 * DAYS_PER_YEAR, 4.36624404335156298e-05 * SOLAR_MASS, 0.01); // neptune b[3](b, 1.53796971148509165e+01, -2.59193146099879641e+01, 2.68067772490389322e-03 * DAYS_PER_YEAR, 1.62824170038242295e-03 * DAYS_PER_YEAR, 5.15138902046611451e-05 * SOLAR_MASS, 0.01); // sun b[4](b,0,0,0,0,SOLAR_MASS, 0.01); } void run() { for (int i = 0; i < b.length; i++) { b[i].calcNextV(new IntC(i+1)); } for (int i = 0; i < b.length; i++) { b[i].step(); } } }
hridesh/panc
examples/Nbody.java
249,770
import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Predicate; import org.junit.Before; import org.junit.Test; /*Predicate - func. takes in value returns true/false Stream - seq. of data items that are produced one at a time. Classes to support functional-style operations, it isn't meant to replace collection, just make it easier to interact with them. */ public class FilterCollectionJava8 { enum Region{ NORTH, SOUTH, EAST, WEST; } class BBTeam{ int pointScored; String teamName; Region region; public BBTeam(int pointScored, String teamName, Region region){ super(); this.pointScored = pointScored; this.teamName = teamName; this.region = region; } public String toString(){ return "BBTeam [pointScored= " + pointScored + " teamName= " + teamName + ", region= " + region + "]"; } } List<BBTeam> teams; public void setUP(){ teams = new ArrayList<>(); teams.add(new BBTeam(55,"Wisconsin", Region.WEST)); teams.add(new BBTeam(65,"Wisconsin", Region.WEST)); teams.add(new BBTeam(67,"San Diego", Region.WEST)); teams.add(new BBTeam(43,"Iowa State", Region.EAST)); teams.add(new BBTeam(43,"Iowa State", Region.EAST)); teams.add(new BBTeam(43,"Iowa State", Region.EAST)); teams.add(new BBTeam(43,"Iowa State", Region.EAST)); teams.add(new BBTeam(98,"Florida", Region.SOUTH)); teams.add(null); teams.add(new BBTeam(98, null, Region.SOUTH)); } //Create Predicate Predicate<BBTeam> westRegion = new Predicate<BBTeam>(){ public boolean test(BBTeam t){ return t.region == Region.WEST; } }; Predicate<BBTeam> eastRegion = (BBTeam p) -> p.region == Region.EAST; public void filter_by_region(){ teams.stream().filter(westRegion).forEach(p -> System.out.println(p) ); } public void filter_by_score(){ teams.stream().filter(p -> p.pointScored >= 60).forEach(p -> System.out.println(p)); } public void filter_by_team_to_collection(){ Predicate<BBTeam> nonNullPredicate = Objects::nonNull; Predicate<BBTeam> nameNotNull = p -> p.teamName != null; Predicate<BBTeam> teamPredicate = p -> p.teamName.equals("Wisconsin"); Predicate<BBTeam> fullPredicate = nonNullPredicate.and(nameNotNull).and(teamPredicate); teams.stream().filter(p -> p.teamName.equals("Wisconsin")).forEach(p -> System.out.println(p)); } }
Arifur794/JavaArrayListFilteringPractice
src/FilterCollectionJava8.java
249,771
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Hridesh Rajan, Eric Lin, Rex Fernando */ import java.util.Queue; import java.util.LinkedList; class Customer { private String name; public Customer(String name) { this.name = name; } public String getName() { return name; } } capsule Barber(WaitingRoom r, boolean isSleeping, int totalCustomers) { void run() { int totalHairCuts = 0; while (totalHairCuts < totalCustomers) { if (!isSleeping) { Customer c = r.whosNext(); if(!c.equals(null)) { System.out.println("Barber working on customer " + c.getName()); totalHairCuts++; } else { System.out.println("Barber went to sleep"); isSleeping = true; } } else yield(1000); } } void wakeIfSleeping() { if(isSleeping) { isSleeping = false; System.out.println("Barber Woke up"); } } } capsule WaitingRoom(int cap) { Queue<Customer> queue = new LinkedList<Customer>(); void sit(Customer c){ if (queue.size()<cap) { queue.offer(c); System.out.println("Customer " + c.getName() + " Sitting in waiting room"); } else System.out.println("Waiting room is full, so " + "customer" + c.getName() + " is leaving"); } Customer whosNext() { return queue.poll(); } } capsule Customers(Barber b, WaitingRoom r, String[] customerNames) { int idCounter = 0; void generate() { for (int i = 0; i < customerNames.length; i++) { Customer c = new Customer(customerNames[i]); System.out.println("Customer " + c.getName() + " wants haircut."); b.wakeIfSleeping(); r.sit(c); yield(1000); } } } capsule Barbershop { design { int numCustomers = 5; int numGenerators = 2; Barber b; WaitingRoom w; Customers gs[numGenerators]; b(w, true, numGenerators * numCustomers); w(10); gs[0](b,w, new String[]{"Hridesh", "Eric", "Sean", "Yuheng", "Ganesha"}); gs[1](b,w, new String[]{"Steven", "Sarah", "Bryan", "Lorand", "Rex"}); } void run() { for(Customers generator: gs) generator.generate(); } }
hridesh/panc
examples/Barbershop2.java
249,772
// ---------------------------------------------------------------------------- // Copyright 2007-2013, GeoTelematic Solutions, Inc. // All rights reserved // ---------------------------------------------------------------------------- // // 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. // // ---------------------------------------------------------------------------- // Change History: // 2006/06/30 Martin D. Flynn // -Initial release // ---------------------------------------------------------------------------- package org.opengts.db; import java.util.*; import org.opengts.util.*; import org.opengts.geocoder.*; public class USState { // ------------------------------------------------------------------------ private static HashMap<String,StateInfo> globalStateMap = new HashMap<String,StateInfo>(); /** *** StateInfo class **/ private static class StateInfo { private String code = null; private String name = null; private String abbrev = null; public StateInfo(String code, String name, String abbrev) { this.code = code; this.name = name; this.abbrev = abbrev; } public String getCode() { return this.code; } public String getAbbreviation() { return this.abbrev; } public String getName() { return this.name; } } // ------------------------------------------------------------------------ private static StateInfo stateMapArray[] = new StateInfo[] { new StateInfo("AL", "Alabama" , "Ala." ), new StateInfo("AK", "Alaska" , "Alaska"), new StateInfo("AS", "American" , "Samoa" ), new StateInfo("AZ", "Arizona" , "Ariz." ), new StateInfo("AR", "Arkansas" , "Ark." ), new StateInfo("CA", "California" , "Calif."), new StateInfo("CO", "Colorado" , "Colo." ), new StateInfo("CT", "Connecticut" , "Conn." ), new StateInfo("DE", "Delaware" , "Del." ), new StateInfo("DC", "Dist. of Columbia" , "D.C." ), new StateInfo("FL", "Florida" , "Fla." ), new StateInfo("GA", "Georgia" , "Ga." ), new StateInfo("GU", "Guam" , "Guam" ), new StateInfo("HI", "Hawaii" , "Hawaii"), new StateInfo("ID", "Idaho" , "Idaho" ), new StateInfo("IL", "Illinois" , "Ill." ), new StateInfo("IN", "Indiana" , "Ind." ), new StateInfo("IA", "Iowa" , "Iowa" ), new StateInfo("KS", "Kansas" , "Kans." ), new StateInfo("KY", "Kentucky" , "Ky." ), new StateInfo("LA", "Louisiana" , "La." ), new StateInfo("ME", "Maine" , "Maine" ), new StateInfo("MD", "Maryland" , "Md." ), new StateInfo("MH", "Marshall Islands" , "MH" ), new StateInfo("MA", "Massachusetts" , "Mass." ), new StateInfo("MI", "Michigan" , "Mich." ), new StateInfo("FM", "Micronesia" , "FM" ), new StateInfo("MN", "Minnesota" , "Minn." ), new StateInfo("MS", "Mississippi" , "Miss." ), new StateInfo("MO", "Missouri" , "Mo." ), new StateInfo("MT", "Montana" , "Mont." ), new StateInfo("NE", "Nebraska" , "Nebr." ), new StateInfo("NV", "Nevada" , "Nev." ), new StateInfo("NH", "New Hampshire" , "N.H." ), new StateInfo("NJ", "New Jersey" , "N.J." ), new StateInfo("NM", "New Mexico" , "N.M." ), new StateInfo("NY", "New York" , "N.Y." ), new StateInfo("NC", "North Carolina" , "N.C." ), new StateInfo("ND", "North Dakota" , "N.D." ), new StateInfo("MP", "Northern Marianas" , "MP" ), new StateInfo("OH", "Ohio" , "Ohio" ), new StateInfo("OK", "Oklahoma" , "Okla." ), new StateInfo("OR", "Oregon" , "Ore." ), new StateInfo("PW", "Palau" , "PW" ), new StateInfo("PA", "Pennsylvania" , "Pa." ), new StateInfo("PR", "Puerto Rico" , "P.R." ), new StateInfo("RI", "Rhode Island" , "R.I." ), new StateInfo("SC", "South Carolina" , "S.C." ), new StateInfo("SD", "South Dakota" , "S.D." ), new StateInfo("TN", "Tennessee" , "Tenn." ), new StateInfo("TX", "Texas" , "Tex." ), new StateInfo("UT", "Utah" , "Utah" ), new StateInfo("VT", "Vermont" , "Vt." ), new StateInfo("VA", "Virginia" , "Va." ), new StateInfo("VI", "Virgin Islands" , "V.I." ), new StateInfo("WA", "Washington" , "Wash." ), new StateInfo("WV", "West Virginia" , "W.Va." ), new StateInfo("WI", "Wisconsin" , "Wis." ), new StateInfo("WY", "Wyoming" , "Wyo." ), }; static { for (int i = 0; i < stateMapArray.length; i++) { String st = stateMapArray[i].getCode(); globalStateMap.put(st, stateMapArray[i]); } } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ /** *** Gets the state name for the specified state code *** @param code The state code *** @return The state name, or an empty String if the state code was not found **/ public static String getStateName(String code) { if (code != null) { if (code.startsWith(ReverseGeocode.COUNTRY_US_)) { code = code.substring(ReverseGeocode.COUNTRY_US_.length()); } StateInfo si = globalStateMap.get(code); return (si != null)? si.getName() : ""; } else { return null; } } // ------------------------------------------------------------------------ /** *** Gets the state code for the specified state name *** @param name The state name *** @return The state code, or an empty String if the state name was not found **/ public static String getStateCode(String name) { if (name != null) { for (Iterator<String> i = globalStateMap.keySet().iterator(); i.hasNext();) { String code = i.next(); StateInfo si = globalStateMap.get(code); if (si.getName().equalsIgnoreCase(name)) { return code; } } return null; } else { return null; } } // ------------------------------------------------------------------------ /** *** Gets the state abbreviation for the specified state code *** @param code The state code *** @return The state abbreviation, or an empty String if the state code was not found **/ public static String getStateAbbreviation(String code) { if (code != null) { if (code.startsWith(ReverseGeocode.COUNTRY_US_)) { code = code.substring(ReverseGeocode.COUNTRY_US_.length()); } StateInfo si = globalStateMap.get(code); return (si != null)? si.getAbbreviation() : ""; } else { return null; } } // ------------------------------------------------------------------------ }
vimukthi-git/OpenGTS_2.4.9
src/org/opengts/db/USState.java
249,774
package Problem1; public class Main { public static void main(String[] args) { Customer c1 = new Customer("Alice", "Bue", "8493"); Address c1BillingAddress = new Address("1000 N St", "Assin Foso", "Ohio", "4444"); c1.setBillingAddress(c1BillingAddress); Address c1shippingAddress = new Address("1000 N St Ship", "Assin Foso Ship", "Ohio Ship", "4444"); c1.setShippingAddress(c1shippingAddress); Customer c2 = new Customer("Tom", "Bradly", "8494"); Address c2BillingAddress = new Address("1001 N St", "Fairfield", "Iowa", "5555"); c2.setBillingAddress(c2BillingAddress); Address c2shippingAddress = new Address("1001 N St Ship", "Fairfield Ship", "Iowa Ship", "5555"); c2.setShippingAddress(c2shippingAddress); Customer c3 = new Customer("Ama", "Adelle", "8495"); Address c3BillingAddress = new Address("1002 N St", "Odumasi", "Chicago", "7777"); c3.setBillingAddress(c3BillingAddress); Address c3shippingAddress = new Address("1002 N St Ship", "Odumasi Ship", "Chicago Ship", "7777"); c3.setShippingAddress(c3shippingAddress); Customer[] cArr = {c1, c2, c3}; for (Customer c : cArr){ if(c.getBillingAddress().state.equals("Chicago")){ System.out.println(c.toString()); } } } }
abboahene/FPPAssigmment3
src/Problem1/Main.java
249,775
/* * Copyright 2014, Anthony Urso, Hridesh Rajan, Robert Dyer, * and Iowa State University of Science and Technology * * 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 boa.types; /** * A {@link BoaScalar} representing a 64 bit integer value. * * @author anthonyu */ public class BoaInt extends BoaScalar { /** {@inheritDoc} */ @Override public BoaScalar arithmetics(final BoaType that) { // if that is a function, check its return value if (that instanceof BoaFunction) return this.arithmetics(((BoaFunction) that).getType()); // otherwise, if it is an int, the type is int else if (that instanceof BoaInt) return new BoaInt(); // otherwise, if it's a time, the type is time else if (that instanceof BoaTime) return new BoaTime(); // otherwise if it's a float, the type is float else if (that instanceof BoaFloat) return new BoaFloat(); // otherwise, check the default return super.arithmetics(that); } /** {@inheritDoc} */ @Override public boolean assigns(final BoaType that) { // time can be assigned to ints if (that instanceof BoaTime) return true; // otherwise, just check the defaults return super.assigns(that); } /** {@inheritDoc} */ @Override public boolean accepts(final BoaType that) { return this.assigns(that); } /** {@inheritDoc} */ @Override public String toString() { return "int"; } /** {@inheritDoc} */ @Override public String toJavaType() { return "long"; } /** {@inheritDoc} */ @Override public String toBoxedJavaType() { return "Long"; } /** {@inheritDoc} */ @Override public String defaultValue() { return "0L"; } }
hyjorc1/compiler
src/java/boa/types/BoaInt.java
249,778
package audio; import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.FloatControl; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import util.Debug; /** * Player for a Wav file * * @author harvey */ public class AudioWav implements AudioPlayer { private boolean running; private Clip player; private File audiofile; /** * Creates a new Wav file player * @param audiofile The file to be played */ public AudioWav(File audiofile) { running = false; this.audiofile = audiofile; try { player = AudioSystem.getClip(); AudioInputStream ais = AudioSystem.getAudioInputStream(audiofile); player.open(ais); } catch (LineUnavailableException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedAudioFileException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Play the sound * @param loop Whether to loop or not */ public void play(boolean loop) { try { if(running) stop(); running = true; player = AudioSystem.getClip(); AudioInputStream ais = AudioSystem.getAudioInputStream(audiofile); player.open(ais); player.start(); if (loop) player.loop(Clip.LOOP_CONTINUOUSLY); } catch (Exception e) { System.err.println(e.getMessage()); } } /** * Stop playback */ public void stop() { running = false; player.stop(); player.drain(); player.close(); } /** * Returns whether the player is running or not * @return bool for whether the file is playing or not */ public boolean isRunning() { return running; } /** * Sets playback volume * @param vol New volume * @param pan New L/R balance */ public void setVol(float vol, float pan) { FloatControl volControl = (FloatControl) player.getControl(FloatControl.Type.MASTER_GAIN); FloatControl panControl = (FloatControl) player.getControl(FloatControl.Type.PAN); if (vol <= volControl.getMaximum() && vol >= volControl.getMinimum()) volControl.setValue(vol); else Debug.say("Invalid Volume parameter"); if (-1 <= pan && pan <= 1) panControl.setValue(pan); else Debug.say("Invalid pan parameter"); } /** * Gets volume * @return Volume as float */ public float getVol() { FloatControl volControl = (FloatControl) player.getControl(FloatControl.Type.MASTER_GAIN); return volControl.getValue(); } /** * Gets pan * @return Pan as float */ public float getPan() { FloatControl panControl = (FloatControl) player.getControl(FloatControl.Type.PAN); return panControl.getValue(); } }
georgehtaylor1/cmiyc_client
src/audio/AudioWav.java
249,780
import java.util.Scanner; /** * Created by User on 10/02/2017. */ public class Example37 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int name = 0; int answer = 1; String[][] states = new String[50][2]; states = getStates(states); int count = 0; while(name < 50) { System.out.print("What is the capital of " + states[name][0] + "? "); String a = scan.nextLine(); if (a.equalsIgnoreCase(states[name][answer])) { System.out.println("Your answer is correct."); count++; } else System.out.println("The correct answer should be " + states[name][answer] + "."); name++; System.out.println(); } System.out.println("The correct count is " + count); } public static String[][] getStates(String[][] x) { x = new String[][]{{"Alabama", "Montgomery"}, {"Alaska", "Juneau"}, {"Arizona", "Phoenix"}, {"Arkansas", "Little Rock"}, {"California", "Sacramento"}, {"Colorado", "Denver"}, {"Connecticut", "Hartford"}, {"Delaware", "Dover"}, {"Florida", "Tallahassee"}, {"Georgia", "Atlanta"}, {"Hawaii", "Honolulu"}, {"Idaho", "Boise"}, {"Illinois", "Springfield"}, {"Indiana", "Indianapolis"}, {"Iowa", "Des Moines"}, {"Kansas", "Topeka"}, {"Kentucky", "Frankfort"}, {"Louisiana", "Baton Rouge"}, {"Maine", "Augusta"}, {"Maryland", "Annapolis"}, {"Massachusetts", "Boston"}, {"Michigan", "Lansing"}, {"Minnesota", "Saint Paul"}, {"Mississippi", "Jackson"}, {"Missouri", "Jefferson City"}, {"Montana", "Helena"}, {"Nebraska", "Lincoln"}, {"Nevada", "Carson City"}, {"New Hampshire", "Concord"}, {"New Jersey", "Trenton"}, {"New Mexico", "Santa Fe"}, {"New York", "Albany"}, {"North Carolina", "Raleigh"}, {"North Dakota", "Bismarck"}, {"Ohio", "Columbus"}, {"Oklahoma", "Oklahoma City"}, {"Oregon", "Salem"}, {"Pennsylvania", "Harrisburg"}, {"Rhode Island", "Providence"}, {"South Carolina", "Columbia"}, {"South Dakota", "Pierre"}, {"Tennessee", "Nashville"}, {"Texas", "Austin"}, {"Utah", "Salt Lake City"}, {"Vermont", "Montpelier"}, {"Virginia", "Richmond"}, {"Washington", "Olympia"}, {"West Virginia", "Charleston"}, {"Wisconsin", "Madison"}, {"Wyoming", "Cheyenne"}}; return x; } }
emretanriverdi/java-liang-solutions
ChapterVIII/Example37.java
249,783
import static org.junit.Assert.assertEquals; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class ValidationTests { static WebDriver driver; static String pathChromeDriver="chromedriver.exe"; static String pathFile="file:///C:/Users/Nedim/Desktop/HW4/task1/validation.html"; @BeforeClass public static void openBrowser() { System.setProperty("webdriver.chrome.driver", pathChromeDriver); driver = new ChromeDriver() ; driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); } @AfterClass public static void closeBrowser() { driver.quit(); } @Test public void successTest() throws InterruptedException { driver.get(pathFile); driver.manage().window().maximize(); driver.findElement(By.id("txtFirstName")).sendKeys("Bob"); driver.findElement(By.id("txtLastName")).sendKeys("Smith"); driver.findElement(By.name("selectGender")).sendKeys("Male"); driver.findElement(By.name("selectState")).sendKeys("Iowa"); driver.findElement(By.id("txtEmail")).sendKeys("[email protected]"); driver.findElement(By.id("txtPhone")).sendKeys("5151111111"); driver.findElement(By.id("txtAddress")).sendKeys("Ames,IA"); driver.findElement(By.id("btnValidate")).click(); String message = driver.findElement(By.id("FinalResult")).getText(); assertEquals(message, "OK"); Thread.sleep(3000); } @Test public void failedTest() throws InterruptedException { driver.get(pathFile); driver.manage().window().maximize(); driver.findElement(By.id("txtFirstName")).sendKeys("Bob"); driver.findElement(By.id("txtLastName")).sendKeys("Smith"); driver.findElement(By.name("selectGender")).sendKeys("Male"); driver.findElement(By.name("selectState")).sendKeys("Iowa"); driver.findElement(By.id("txtEmail")).sendKeys("[email protected]"); driver.findElement(By.id("txtPhone")).sendKeys("515AAA1111"); driver.findElement(By.id("txtAddress")).sendKeys("Ames,IA"); driver.findElement(By.id("btnValidate")).click(); String message = driver.findElement(By.id("FinalResult")).getText(); assertEquals(message, "Error"); Thread.sleep(3000); } }
NedimHodzic/SE-COMS-319
HW4/ValidationTests.java
249,784
import operations.OperationChain; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.stream.Stream; public class Part1 { public static void main(String[] args) { var inputFileName = "0.csv"; var outputFileName = "result.csv"; try (Stream<String> stream = Files.lines(Paths.get(Part1.class.getResource(inputFileName).toURI())); OutputStream os = new FileOutputStream(outputFileName)) { var result = OperationChain .create(List.of(stream), OperationChain.ChainMode.FOR_EACH) .filter(3, "Iowa") .pluck(10) .max() .streams() .get(0); result.forEachOrdered(x -> { try { os.write(x.getBytes()); } catch (IOException e) { e.printStackTrace(); } }); } catch (Exception e) { e.printStackTrace(); } } }
olgkpln/UpsolverProcessChain
src/main/java/Part1.java
249,785
import java.util.ArrayList; import java.util.Random; import java.awt.Color; public class MapNodeCreation { /** * Creates and orders the Australian territories * @param colorDomain * @return ArrayList<State> */ public ArrayList<State> generateAustraliaNodes(ArrayList<String> colorDomain) { //Create map ArrayList<State> mapOrdered = new ArrayList<>(); //Generate each of the territories State westernAustralia = new State("Western Australia", "WA",colorDomain); State northernTerritory = new State("Northern Territory", "NT",colorDomain); State southAustralia = new State("South Australia", "SA",colorDomain); State queensland = new State("Queensland", "Q",colorDomain); State newSouthWales = new State("New South Wales", "NSW",colorDomain); State victoria= new State("Victoria", "V",colorDomain); State tasmania= new State("Tasmania", "T",colorDomain); //Add territories to the map mapOrdered.add(westernAustralia); mapOrdered.add(northernTerritory); mapOrdered.add(southAustralia); mapOrdered.add(queensland); mapOrdered.add(newSouthWales); mapOrdered.add(victoria); mapOrdered.add(tasmania); //Add the neighbors for each state westernAustralia.addNeighbor(northernTerritory); westernAustralia.addNeighbor(southAustralia); northernTerritory.addNeighbor(westernAustralia); northernTerritory.addNeighbor(southAustralia); northernTerritory.addNeighbor(queensland); southAustralia.addNeighbor(westernAustralia); southAustralia.addNeighbor(northernTerritory); southAustralia.addNeighbor(queensland); southAustralia.addNeighbor(newSouthWales); southAustralia.addNeighbor(victoria); queensland.addNeighbor(northernTerritory); queensland.addNeighbor(southAustralia); queensland.addNeighbor(newSouthWales); newSouthWales.addNeighbor(queensland); newSouthWales.addNeighbor(southAustralia); newSouthWales.addNeighbor(victoria); victoria.addNeighbor(southAustralia); victoria.addNeighbor(newSouthWales); //Randomly order the map by selecting a random value in the OrderedList ArrayList<State> mapRandom = new ArrayList<>(); //Select the root node in the list Random rng = new Random(); int selection = rng.nextInt(mapOrdered.size()); State temp = mapOrdered.get(selection); mapRandom.add(temp); mapOrdered.remove(selection); while (!mapOrdered.isEmpty()) { selection = rng.nextInt(mapOrdered.size()); temp.next = mapOrdered.get((selection)); mapRandom.add(temp.next); mapOrdered.remove(selection); temp = temp.next; } return mapRandom; } /** * Generates and orders the US States * @param colorDomain * @return ArrayList<State> */ public ArrayList<State> generateAmericaNodes(ArrayList<String> colorDomain) { //Create map ArrayList<State> mapOrdered = new ArrayList<>(); State alabama = new State("alabama", "AL", colorDomain); State alaska = new State("alaska", "AK",colorDomain); State arizona = new State("arizona","AZ", colorDomain); State arkansas = new State("arkansas","AR", colorDomain); State california = new State("california", "CA",colorDomain); State colorado = new State("colorado", "CO",colorDomain); State connecticut = new State("connecticut","CT", colorDomain); State delaware = new State("delaware", "DE",colorDomain); State florida = new State("florida", "FL",colorDomain); State georgia = new State("georgia","GA", colorDomain); State hawaii = new State("hawaii", "HI",colorDomain); State idaho = new State("idaho", "ID", colorDomain); State illinois = new State("illinois", "IL",colorDomain); State indiana = new State("indiana", "IN",colorDomain); State iowa = new State("iowa", "IA",colorDomain); State kansas = new State("kansas","KS", colorDomain); State kentucky = new State("kentucky", "KY",colorDomain); State louisiana = new State("louisiana", "LA",colorDomain); State maine = new State("maine", "ME",colorDomain); State maryland = new State("maryland", "MD",colorDomain); State massachusetts = new State("massachusetts", "MA",colorDomain); State michigan = new State("michigan", "MI",colorDomain); State minnesota = new State("minnesota", "MN",colorDomain); State mississippi = new State("mississippi", "MS",colorDomain); State missouri = new State("missouri", "MO",colorDomain); State montana = new State("montana", "MT",colorDomain); State nebraska = new State("nebraska", "NE",colorDomain); State nevada = new State("nevada", "NV", colorDomain); State newHampshire = new State("newHampshire", "NH",colorDomain); State newJersey = new State("newJersey", "NJ",colorDomain); State newMexico = new State("newMexico", "NM",colorDomain); State newYork = new State("newYork", "NY",colorDomain); State northCarolina = new State("northCarolina", "NC",colorDomain); State northDakota = new State("northDakota", "ND",colorDomain); State ohio = new State("ohio", "OH",colorDomain); State oklahoma = new State("oklahoma", "OK",colorDomain); State oregon = new State("oregon", "OR",colorDomain); State pennsylvania = new State("pennsylvania", "PA",colorDomain); State rhodeIsland = new State("rhodeIsland", "RI",colorDomain); State southCarolina = new State("southCarolina", "SC",colorDomain); State southDakota = new State("southDakota", "SD",colorDomain); State tennessee = new State("tennessee", "TN",colorDomain); State texas = new State("texas", "TX",colorDomain); State utah = new State("utah", "UT",colorDomain); State vermont = new State("vermont", "VT",colorDomain); State virginia = new State("virginia", "VA",colorDomain); State washington = new State("washington", "WA",colorDomain); State westVirginia = new State("westVirginia", "WV",colorDomain); State wisconsin = new State("wisconsin", "WI",colorDomain); State wyoming = new State("wyoming", "WY",colorDomain); mapOrdered.add(alabama); mapOrdered.add(alaska); mapOrdered.add(arizona); mapOrdered.add(arkansas); mapOrdered.add(california); mapOrdered.add(colorado); mapOrdered.add(connecticut); mapOrdered.add(delaware); mapOrdered.add(florida); mapOrdered.add(georgia); mapOrdered.add(hawaii); mapOrdered.add(idaho); mapOrdered.add(illinois); mapOrdered.add(indiana); mapOrdered.add(iowa); mapOrdered.add(kansas); mapOrdered.add(kentucky); mapOrdered.add(louisiana); mapOrdered.add(maine); mapOrdered.add(maryland); mapOrdered.add(massachusetts); mapOrdered.add(michigan); mapOrdered.add(minnesota); mapOrdered.add(mississippi); mapOrdered.add(missouri); mapOrdered.add(montana); mapOrdered.add(nebraska); mapOrdered.add(nevada); mapOrdered.add(newHampshire); mapOrdered.add(newJersey); mapOrdered.add(newMexico); mapOrdered.add(newYork); mapOrdered.add(northCarolina); mapOrdered.add(northDakota); mapOrdered.add(ohio); mapOrdered.add(oklahoma); mapOrdered.add(oregon); mapOrdered.add(pennsylvania); mapOrdered.add(rhodeIsland); mapOrdered.add(southCarolina); mapOrdered.add(southDakota); mapOrdered.add(tennessee); mapOrdered.add(texas); mapOrdered.add(utah); mapOrdered.add(vermont); mapOrdered.add(virginia); mapOrdered.add(washington); mapOrdered.add(westVirginia); mapOrdered.add(wisconsin); mapOrdered.add(wyoming); alabama.addNeighbor(mississippi); alabama.addNeighbor(tennessee); alabama.addNeighbor(florida); alabama.addNeighbor(georgia); arizona.addNeighbor(nevada); arizona.addNeighbor(newMexico); arizona.addNeighbor(utah); arizona.addNeighbor(california); arizona.addNeighbor(colorado); arkansas.addNeighbor(oklahoma); arkansas.addNeighbor(tennessee); arkansas.addNeighbor(texas); arkansas.addNeighbor(louisiana); arkansas.addNeighbor(mississippi); arkansas.addNeighbor(missouri); california.addNeighbor(oregon); california.addNeighbor(arizona); california.addNeighbor(nevada); colorado.addNeighbor(newMexico); colorado.addNeighbor(oklahoma); colorado.addNeighbor(utah); colorado.addNeighbor(wyoming); colorado.addNeighbor(arizona); colorado.addNeighbor(kansas); colorado.addNeighbor(nebraska); connecticut.addNeighbor(newYork); connecticut.addNeighbor(rhodeIsland); connecticut.addNeighbor(massachusetts); delaware.addNeighbor(newJersey); delaware.addNeighbor(pennsylvania); delaware.addNeighbor(maryland); florida.addNeighbor(georgia); florida.addNeighbor(alabama); georgia.addNeighbor(northCarolina); georgia.addNeighbor(southCarolina); georgia.addNeighbor(tennessee); georgia.addNeighbor(alabama); georgia.addNeighbor(florida); idaho.addNeighbor(utah); idaho.addNeighbor(washington); idaho.addNeighbor(wyoming); idaho.addNeighbor(montana); idaho.addNeighbor(nevada); idaho.addNeighbor(oregon); illinois.addNeighbor(kentucky); illinois.addNeighbor(missouri); illinois.addNeighbor(wisconsin); illinois.addNeighbor(indiana); illinois.addNeighbor(iowa); illinois.addNeighbor(michigan); indiana.addNeighbor(michigan); indiana.addNeighbor(ohio); indiana.addNeighbor(illinois); indiana.addNeighbor(kentucky); iowa.addNeighbor(nebraska); iowa.addNeighbor(southDakota); iowa.addNeighbor(wisconsin); iowa.addNeighbor(illinois); iowa.addNeighbor(minnesota); iowa.addNeighbor(missouri); kansas.addNeighbor(nebraska); kansas.addNeighbor(oklahoma); kansas.addNeighbor(colorado); kansas.addNeighbor(missouri); kentucky.addNeighbor(tennessee); kentucky.addNeighbor(virginia); kentucky.addNeighbor(westVirginia); kentucky.addNeighbor(illinois); kentucky.addNeighbor(indiana); kentucky.addNeighbor(missouri); kentucky.addNeighbor(ohio); louisiana.addNeighbor(texas); louisiana.addNeighbor(arkansas); louisiana.addNeighbor(mississippi); maine.addNeighbor(newHampshire); maryland.addNeighbor(virginia); maryland.addNeighbor(westVirginia); maryland.addNeighbor(delaware); maryland.addNeighbor(pennsylvania); massachusetts.addNeighbor(newYork); massachusetts.addNeighbor(rhodeIsland); massachusetts.addNeighbor(vermont); massachusetts.addNeighbor(connecticut); massachusetts.addNeighbor(newHampshire); michigan.addNeighbor(ohio); michigan.addNeighbor(wisconsin); michigan.addNeighbor(illinois); michigan.addNeighbor(indiana); michigan.addNeighbor(minnesota); minnesota.addNeighbor(northDakota); minnesota.addNeighbor(southDakota); minnesota.addNeighbor(wisconsin); minnesota.addNeighbor(iowa); minnesota.addNeighbor(michigan); mississippi.addNeighbor(louisiana); mississippi.addNeighbor(tennessee); mississippi.addNeighbor(alabama); mississippi.addNeighbor(arkansas); missouri.addNeighbor(nebraska); missouri.addNeighbor(oklahoma); missouri.addNeighbor(tennessee); missouri.addNeighbor(arkansas); missouri.addNeighbor(illinois); missouri.addNeighbor(iowa); missouri.addNeighbor(kansas); missouri.addNeighbor(kentucky); montana.addNeighbor(southDakota); montana.addNeighbor(wyoming); montana.addNeighbor(idaho); montana.addNeighbor(northDakota); nebraska.addNeighbor(missouri); nebraska.addNeighbor(southDakota); nebraska.addNeighbor(wyoming); nebraska.addNeighbor(colorado); nebraska.addNeighbor(iowa); nebraska.addNeighbor(kansas); nevada.addNeighbor(idaho); nevada.addNeighbor(oregon); nevada.addNeighbor(utah); nevada.addNeighbor(arizona); nevada.addNeighbor(california); newHampshire.addNeighbor(vermont); newHampshire.addNeighbor(maine); newHampshire.addNeighbor(massachusetts); newJersey.addNeighbor(pennsylvania); newJersey.addNeighbor(delaware); newJersey.addNeighbor(newYork); newMexico.addNeighbor(oklahoma); newMexico.addNeighbor(texas); newMexico.addNeighbor(utah); newMexico.addNeighbor(arizona); newMexico.addNeighbor(colorado); newYork.addNeighbor(pennsylvania); newYork.addNeighbor(rhodeIsland); newYork.addNeighbor(vermont); newYork.addNeighbor(connecticut); newYork.addNeighbor(massachusetts); newYork.addNeighbor(newJersey); northCarolina.addNeighbor(tennessee); northCarolina.addNeighbor(virginia); northCarolina.addNeighbor(georgia); northCarolina.addNeighbor(southCarolina); northDakota.addNeighbor(southDakota); northDakota.addNeighbor(minnesota); northDakota.addNeighbor(montana); ohio.addNeighbor(michigan); ohio.addNeighbor(pennsylvania); ohio.addNeighbor(westVirginia); ohio.addNeighbor(indiana); ohio.addNeighbor(kentucky); oklahoma.addNeighbor(missouri); oklahoma.addNeighbor(newMexico); oklahoma.addNeighbor(texas); oklahoma.addNeighbor(arkansas); oklahoma.addNeighbor(colorado); oklahoma.addNeighbor(kansas); oregon.addNeighbor(nevada); oregon.addNeighbor(washington); oregon.addNeighbor(california); oregon.addNeighbor(idaho); pennsylvania.addNeighbor(newYork); pennsylvania.addNeighbor(ohio); pennsylvania.addNeighbor(westVirginia); pennsylvania.addNeighbor(delaware); pennsylvania.addNeighbor(maryland); pennsylvania.addNeighbor(newJersey); rhodeIsland.addNeighbor(massachusetts); rhodeIsland.addNeighbor(newYork); rhodeIsland.addNeighbor(connecticut); southCarolina.addNeighbor(northCarolina); southCarolina.addNeighbor(georgia); southDakota.addNeighbor(nebraska); southDakota.addNeighbor(northDakota); southDakota.addNeighbor(wyoming); southDakota.addNeighbor(iowa); southDakota.addNeighbor(minnesota); southDakota.addNeighbor(montana); tennessee.addNeighbor(mississippi); tennessee.addNeighbor(missouri); tennessee.addNeighbor(northCarolina); tennessee.addNeighbor(virginia); tennessee.addNeighbor(alabama); tennessee.addNeighbor(arkansas); tennessee.addNeighbor(georgia); tennessee.addNeighbor(kentucky); texas.addNeighbor(newMexico); texas.addNeighbor(oklahoma); texas.addNeighbor(arkansas); texas.addNeighbor(louisiana); utah.addNeighbor(nevada); utah.addNeighbor(newMexico); utah.addNeighbor(wyoming); utah.addNeighbor(arizona); utah.addNeighbor(colorado); utah.addNeighbor(idaho); vermont.addNeighbor(newHampshire); vermont.addNeighbor(newYork); vermont.addNeighbor(massachusetts); virginia.addNeighbor(northCarolina); virginia.addNeighbor(tennessee); virginia.addNeighbor(westVirginia); virginia.addNeighbor(kentucky); virginia.addNeighbor(maryland); washington.addNeighbor(oregon); washington.addNeighbor(idaho); westVirginia.addNeighbor(pennsylvania); westVirginia.addNeighbor(virginia); westVirginia.addNeighbor(kentucky); westVirginia.addNeighbor(maryland); westVirginia.addNeighbor(ohio); wisconsin.addNeighbor(michigan); wisconsin.addNeighbor(minnesota); wisconsin.addNeighbor(illinois); wisconsin.addNeighbor(iowa); wyoming.addNeighbor(nebraska); wyoming.addNeighbor(southDakota); wyoming.addNeighbor(utah); wyoming.addNeighbor(colorado); wyoming.addNeighbor(idaho); wyoming.addNeighbor(montana); //Randomly order the map by selecting a random value in the OrderedList ArrayList<State> mapRandom = new ArrayList<>(); //Select the root node in the list Random rng = new Random(); int selection = rng.nextInt(mapOrdered.size()); State temp = mapOrdered.get(selection); mapRandom.add(temp); mapOrdered.remove(selection); while (!mapOrdered.isEmpty()) { selection = rng.nextInt(mapOrdered.size()); temp.next = mapOrdered.get((selection)); mapRandom.add(temp.next); mapOrdered.remove(selection); temp = temp.next; } return mapRandom; } }
jameswooten/kcolorproject
src/MapNodeCreation.java
249,786
/* * This file is part of the Panini project at Iowa State University. * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * For more details and the latest version of this code please see * http://paninij.org * * Contributor(s): Hridesh Rajan */ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.FileNotFoundException; import java.util.StringTokenizer; /*** * Classic KWIC system using the Panini language * * This implementation of the KWIC system is based on the example * presented in the following paper. * D. L. Parnas. 1972. On the criteria to be used in decomposing systems * into modules. Commun. ACM 15, 12 (December 1972), 1053-1058. * DOI=10.1145/361598.361623 http://doi.acm.org/10.1145/361598.361623 * */ /** * Input capsule is responsible for reading and parsing the content of * a KWIC input file. The format of the KWIC input file is as follows: * <ul> * <li>Lines are separated by the line separator character(s) (on Unix '\n', on Windows '\r\n') * <li>Each line consists of a number of words. Words are delimited by any number and combination * of the space chracter (' ') and the horizontal tabulation chracter ('\t'). * </ul> * Data is parsed and stored in memory as an instance of the LineStorage class: * <ul> * <li>All line separators are removed from the data; for each new line in the file a new line * is added to the LineStorage instance * <li>All horizontal tabulation word delimiters are removed * <li>All space character word delimiters are removed * <li>From characters between any two word delimiters a new string is created; the new string * is added as a word to a particular line. * </ul> */ capsule Input (LineStorage line_storage){ void parse(String file) { try{ BufferedReader reader = new BufferedReader(new FileReader(file)); String line = reader.readLine(); while(line != null){ StringTokenizer tokenizer = new StringTokenizer(line); // " \t\n\r\f" are delimiter character if(tokenizer.countTokens() > 0) line_storage.addEmptyLine(); while(tokenizer.hasMoreTokens()) line_storage.addWord(tokenizer.nextToken(), line_storage.getLineCount() - 1); line = reader.readLine(); } }catch(FileNotFoundException exc){ exc.printStackTrace(); System.err.println("KWIC Error: Could not open " + file + "file."); System.exit(1); }catch(IOException exc){ exc.printStackTrace(); System.err.println("KWIC Error: Could not read " + file + "file."); System.exit(1); } } }
hridesh/panc
examples/KWIC/Input.java